cuddGroup.c 69 KB
Newer Older
Alan Mishchenko committed
1 2 3 4 5 6 7 8 9
/**CFile***********************************************************************

  FileName    [cuddGroup.c]

  PackageName [cudd]

  Synopsis    [Functions for group sifting.]

  Description [External procedures included in this file:
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
                <ul>
                <li> Cudd_MakeTreeNode()
                </ul>
        Internal procedures included in this file:
                <ul>
                <li> cuddTreeSifting()
                </ul>
        Static procedures included in this module:
                <ul>
                <li> ddTreeSiftingAux()
                <li> ddCountInternalMtrNodes()
                <li> ddReorderChildren()
                <li> ddFindNodeHiLo()
                <li> ddUniqueCompareGroup()
                <li> ddGroupSifting()
                <li> ddCreateGroup()
                <li> ddGroupSiftingAux()
                <li> ddGroupSiftingUp()
                <li> ddGroupSiftingDown()
                <li> ddGroupMove()
                <li> ddGroupMoveBackward()
                <li> ddGroupSiftingBackward()
                <li> ddMergeGroups()
                <li> ddDissolveGroup()
                <li> ddNoCheck()
                <li> ddSecDiffCheck()
                <li> ddExtSymmCheck()
                <li> ddVarGroupCheck()
                <li> ddSetVarHandled()
                <li> ddResetVarHandled()
                <li> ddIsVarHandled()
                </ul>]
Alan Mishchenko committed
42 43 44

  Author      [Shipra Panda, Fabio Somenzi]

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  Copyright   [Copyright (c) 1995-2004, Regents of the University of Colorado

  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:

  Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

  Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

  Neither the name of the University of Colorado nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.]
Alan Mishchenko committed
76 77 78

******************************************************************************/

79
#include "misc/util/util_hack.h"
Alan Mishchenko committed
80 81
#include "cuddInt.h"

82 83 84
ABC_NAMESPACE_IMPL_START


85

Alan Mishchenko committed
86 87 88 89 90
/*---------------------------------------------------------------------------*/
/* Constant declarations                                                     */
/*---------------------------------------------------------------------------*/

/* Constants for lazy sifting */
91 92
#define DD_NORMAL_SIFT  0
#define DD_LAZY_SIFT    1
Alan Mishchenko committed
93 94

/* Constants for sifting up and down */
95 96
#define DD_SIFT_DOWN    0
#define DD_SIFT_UP      1
Alan Mishchenko committed
97 98 99 100 101 102 103 104 105

/*---------------------------------------------------------------------------*/
/* Stucture declarations                                                     */
/*---------------------------------------------------------------------------*/

/*---------------------------------------------------------------------------*/
/* Type declarations                                                         */
/*---------------------------------------------------------------------------*/

106 107
    typedef int (*DD_CHKFP)(DdManager *, int, int);

Alan Mishchenko committed
108 109 110 111 112
/*---------------------------------------------------------------------------*/
/* Variable declarations                                                     */
/*---------------------------------------------------------------------------*/

#ifndef lint
113
static char rcsid[] DD_UNUSED = "$Id: cuddGroup.c,v 1.44 2009/02/21 18:24:10 fabio Exp $";
Alan Mishchenko committed
114 115
#endif

116 117
static  int     *entry;
extern  int     ddTotalNumberSwapping;
Alan Mishchenko committed
118
#ifdef DD_STATS
119
extern  int     ddTotalNISwaps;
Alan Mishchenko committed
120 121 122 123 124 125 126
static  int     extsymmcalls;
static  int     extsymm;
static  int     secdiffcalls;
static  int     secdiff;
static  int     secdiffmisfire;
#endif
#ifdef DD_DEBUG
127 128
static  int     pr = 0; /* flag to enable printing while debugging */
                        /* by depositing a 1 into it */
Alan Mishchenko committed
129
#endif
130
static unsigned int originalSize;
Alan Mishchenko committed
131 132 133 134 135 136 137 138 139 140 141

/*---------------------------------------------------------------------------*/
/* Macro declarations                                                        */
/*---------------------------------------------------------------------------*/

/**AutomaticStart*************************************************************/

/*---------------------------------------------------------------------------*/
/* Static function prototypes                                                */
/*---------------------------------------------------------------------------*/

142
static int ddTreeSiftingAux (DdManager *table, MtrNode *treenode, Cudd_ReorderingType method);
Alan Mishchenko committed
143
#ifdef DD_STATS
144
static int ddCountInternalMtrNodes (DdManager *table, MtrNode *treenode);
Alan Mishchenko committed
145
#endif
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
static int ddReorderChildren (DdManager *table, MtrNode *treenode, Cudd_ReorderingType method);
static void ddFindNodeHiLo (DdManager *table, MtrNode *treenode, int *lower, int *upper);
static int ddUniqueCompareGroup (int *ptrX, int *ptrY);
static int ddGroupSifting (DdManager *table, int lower, int upper, DD_CHKFP checkFunction, int lazyFlag);
static void ddCreateGroup (DdManager *table, int x, int y);
static int ddGroupSiftingAux (DdManager *table, int x, int xLow, int xHigh, DD_CHKFP checkFunction, int lazyFlag);
static int ddGroupSiftingUp (DdManager *table, int y, int xLow, DD_CHKFP checkFunction, Move **moves);
static int ddGroupSiftingDown (DdManager *table, int x, int xHigh, DD_CHKFP checkFunction, Move **moves);
static int ddGroupMove (DdManager *table, int x, int y, Move **moves);
static int ddGroupMoveBackward (DdManager *table, int x, int y);
static int ddGroupSiftingBackward (DdManager *table, Move *moves, int size, int upFlag, int lazyFlag);
static void ddMergeGroups (DdManager *table, MtrNode *treenode, int low, int high);
static void ddDissolveGroup (DdManager *table, int x, int y);
static int ddNoCheck (DdManager *table, int x, int y);
static int ddSecDiffCheck (DdManager *table, int x, int y);
static int ddExtSymmCheck (DdManager *table, int x, int y);
static int ddVarGroupCheck (DdManager * table, int x, int y);
static int ddSetVarHandled (DdManager *dd, int index);
static int ddResetVarHandled (DdManager *dd, int index);
static int ddIsVarHandled (DdManager *dd, int index);
Alan Mishchenko committed
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

/**AutomaticEnd***************************************************************/

/*---------------------------------------------------------------------------*/
/* Definition of exported functions                                          */
/*---------------------------------------------------------------------------*/


/**Function********************************************************************

  Synopsis    [Creates a new variable group.]

  Description [Creates a new variable group. The group starts at
  variable and contains size variables. The parameter low is the index
  of the first variable. If the variable already exists, its current
  position in the order is known to the manager. If the variable does
  not exist yet, the position is assumed to be the same as the index.
  The group tree is created if it does not exist yet.
  Returns a pointer to the group if successful; NULL otherwise.]

  SideEffects [The variable tree is changed.]

  SeeAlso     [Cudd_MakeZddTreeNode]

******************************************************************************/
MtrNode *
Cudd_MakeTreeNode(
  DdManager * dd /* manager */,
  unsigned int  low /* index of the first group variable */,
  unsigned int  size /* number of variables in the group */,
  unsigned int  type /* MTR_DEFAULT or MTR_FIXED */)
{
    MtrNode *group;
    MtrNode *tree;
    unsigned int level;

    /* If the variable does not exist yet, the position is assumed to be
    ** the same as the index. Therefore, applications that rely on
    ** Cudd_bddNewVarAtLevel or Cudd_addNewVarAtLevel to create new
    ** variables have to create the variables before they group them.
    */
    level = (low < (unsigned int) dd->size) ? dd->perm[low] : low;

    if (level + size - 1> (int) MTR_MAXHIGH)
210
        return(NULL);
Alan Mishchenko committed
211 212 213 214

    /* If the tree does not exist yet, create it. */
    tree = dd->tree;
    if (tree == NULL) {
215 216 217 218
        dd->tree = tree = Mtr_InitGroupTree(0, dd->size);
        if (tree == NULL)
            return(NULL);
        tree->index = dd->invperm[0];
Alan Mishchenko committed
219 220 221 222 223 224 225 226 227 228
    }

    /* Extend the upper bound of the tree if necessary. This allows the
    ** application to create groups even before the variables are created.
    */
    tree->size = ddMax(tree->size, ddMax(level + size, (unsigned) dd->size));

    /* Create the group. */
    group = Mtr_MakeGroup(tree, level, size, type);
    if (group == NULL)
229
        return(NULL);
Alan Mishchenko committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261

    /* Initialize the index field to the index of the variable currently
    ** in position low. This field will be updated by the reordering
    ** procedure to provide a handle to the group once it has been moved.
    */
    group->index = (MtrHalfWord) low;

    return(group);

} /* end of Cudd_MakeTreeNode */


/*---------------------------------------------------------------------------*/
/* Definition of internal functions                                          */
/*---------------------------------------------------------------------------*/


/**Function********************************************************************

  Synopsis    [Tree sifting algorithm.]

  Description [Tree sifting algorithm. Assumes that a tree representing
  a group hierarchy is passed as a parameter. It then reorders each
  group in postorder fashion by calling ddTreeSiftingAux.  Assumes that
  no dead nodes are present.  Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
int
cuddTreeSifting(
  DdManager * table /* DD table */,
262
  Cudd_ReorderingType method /* reordering method for the groups of leaves */)
Alan Mishchenko committed
263 264 265 266 267 268 269 270 271 272 273 274
{
    int i;
    int nvars;
    int result;
    int tempTree;

    /* If no tree is provided we create a temporary one in which all
    ** variables are in a single group. After reordering this tree is
    ** destroyed.
    */
    tempTree = table->tree == NULL;
    if (tempTree) {
275 276
        table->tree = Mtr_InitGroupTree(0,table->size);
        table->tree->index = table->invperm[0];
Alan Mishchenko committed
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    }
    nvars = table->size;

#ifdef DD_DEBUG
    if (pr > 0 && !tempTree) (void) fprintf(table->out,"cuddTreeSifting:");
    Mtr_PrintGroups(table->tree,pr <= 0);
#endif

#ifdef DD_STATS
    extsymmcalls = 0;
    extsymm = 0;
    secdiffcalls = 0;
    secdiff = 0;
    secdiffmisfire = 0;

    (void) fprintf(table->out,"\n");
    if (!tempTree)
294 295
        (void) fprintf(table->out,"#:IM_NODES  %8d: group tree nodes\n",
                       ddCountInternalMtrNodes(table,table->tree));
Alan Mishchenko committed
296 297 298 299 300 301 302 303 304 305 306
#endif

    /* Initialize the group of each subtable to itself. Initially
    ** there are no groups. Groups are created according to the tree
    ** structure in postorder fashion.
    */
    for (i = 0; i < nvars; i++)
        table->subtables[i].next = i;


    /* Reorder. */
307
    result = ddTreeSiftingAux(table, table->tree, method);
Alan Mishchenko committed
308

309
#ifdef DD_STATS         /* print stats */
Alan Mishchenko committed
310
    if (!tempTree && method == CUDD_REORDER_GROUP_SIFT &&
311 312 313 314
        (table->groupcheck == CUDD_GROUP_CHECK7 ||
         table->groupcheck == CUDD_GROUP_CHECK5)) {
        (void) fprintf(table->out,"\nextsymmcalls = %d\n",extsymmcalls);
        (void) fprintf(table->out,"extsymm = %d",extsymm);
Alan Mishchenko committed
315 316
    }
    if (!tempTree && method == CUDD_REORDER_GROUP_SIFT &&
317 318 319 320
        table->groupcheck == CUDD_GROUP_CHECK7) {
        (void) fprintf(table->out,"\nsecdiffcalls = %d\n",secdiffcalls);
        (void) fprintf(table->out,"secdiff = %d\n",secdiff);
        (void) fprintf(table->out,"secdiffmisfire = %d",secdiffmisfire);
Alan Mishchenko committed
321 322 323 324
    }
#endif

    if (tempTree)
325
        Cudd_FreeTree(table);
Alan Mishchenko committed
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
    return(result);

} /* end of cuddTreeSifting */


/*---------------------------------------------------------------------------*/
/* Definition of static functions                                            */
/*---------------------------------------------------------------------------*/


/**Function********************************************************************

  Synopsis    [Visits the group tree and reorders each group.]

  Description [Recursively visits the group tree and reorders each
  group in postorder fashion.  Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddTreeSiftingAux(
  DdManager * table,
  MtrNode * treenode,
350
  Cudd_ReorderingType method)
Alan Mishchenko committed
351 352 353 354 355 356 357 358 359 360 361
{
    MtrNode  *auxnode;
    int res;
    Cudd_AggregationType saveCheck;

#ifdef DD_DEBUG
    Mtr_PrintGroups(treenode,1);
#endif

    auxnode = treenode;
    while (auxnode != NULL) {
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
        if (auxnode->child != NULL) {
            if (!ddTreeSiftingAux(table, auxnode->child, method))
                return(0);
            saveCheck = table->groupcheck;
            table->groupcheck = CUDD_NO_CHECK;
            if (method != CUDD_REORDER_LAZY_SIFT)
              res = ddReorderChildren(table, auxnode, CUDD_REORDER_GROUP_SIFT);
            else
              res = ddReorderChildren(table, auxnode, CUDD_REORDER_LAZY_SIFT);
            table->groupcheck = saveCheck;

            if (res == 0)
                return(0);
        } else if (auxnode->size > 1) {
            if (!ddReorderChildren(table, auxnode, method))
                return(0);
        }
        auxnode = auxnode->younger;
Alan Mishchenko committed
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    }

    return(1);

} /* end of ddTreeSiftingAux */


#ifdef DD_STATS
/**Function********************************************************************

  Synopsis    [Counts the number of internal nodes of the group tree.]

  Description [Counts the number of internal nodes of the group tree.
  Returns the count.]

  SideEffects [None]

******************************************************************************/
static int
ddCountInternalMtrNodes(
  DdManager * table,
  MtrNode * treenode)
{
    MtrNode *auxnode;
    int     count,nodeCount;


    nodeCount = 0;
    auxnode = treenode;
    while (auxnode != NULL) {
410 411 412 413 414 415
        if (!(MTR_TEST(auxnode,MTR_TERMINAL))) {
            nodeCount++;
            count = ddCountInternalMtrNodes(table,auxnode->child);
            nodeCount += count;
        }
        auxnode = auxnode->younger;
Alan Mishchenko committed
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    }

    return(nodeCount);

} /* end of ddCountInternalMtrNodes */
#endif


/**Function********************************************************************

  Synopsis    [Reorders the children of a group tree node according to
  the options.]

  Description [Reorders the children of a group tree node according to
  the options. After reordering puts all the variables in the group
  and/or its descendents in a single group. This allows hierarchical
  reordering.  If the variables in the group do not exist yet, simply
  does nothing. Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddReorderChildren(
  DdManager * table,
  MtrNode * treenode,
442
  Cudd_ReorderingType method)
Alan Mishchenko committed
443 444
{
    int lower;
445
    int upper = -1;
Alan Mishchenko committed
446 447 448 449 450 451
    int result;
    unsigned int initialSize;

    ddFindNodeHiLo(table,treenode,&lower,&upper);
    /* If upper == -1 these variables do not exist yet. */
    if (upper == -1)
452
        return(1);
Alan Mishchenko committed
453 454

    if (treenode->flags == MTR_FIXED) {
455
        result = 1;
Alan Mishchenko committed
456 457
    } else {
#ifdef DD_STATS
458
        (void) fprintf(table->out," ");
Alan Mishchenko committed
459
#endif
460 461 462 463
        switch (method) {
        case CUDD_REORDER_RANDOM:
        case CUDD_REORDER_RANDOM_PIVOT:
            result = cuddSwapping(table,lower,upper,method);
Alan Mishchenko committed
464
            break;
465 466 467 468 469 470 471 472 473
        case CUDD_REORDER_SIFT:
            result = cuddSifting(table,lower,upper);
            break;
        case CUDD_REORDER_SIFT_CONVERGE:
            do {
                initialSize = table->keys - table->isolated;
                result = cuddSifting(table,lower,upper);
                if (initialSize <= table->keys - table->isolated)
                    break;
Alan Mishchenko committed
474
#ifdef DD_STATS
475 476
                else
                    (void) fprintf(table->out,"\n");
Alan Mishchenko committed
477
#endif
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
            } while (result != 0);
            break;
        case CUDD_REORDER_SYMM_SIFT:
            result = cuddSymmSifting(table,lower,upper);
            break;
        case CUDD_REORDER_SYMM_SIFT_CONV:
            result = cuddSymmSiftingConv(table,lower,upper);
            break;
        case CUDD_REORDER_GROUP_SIFT:
            if (table->groupcheck == CUDD_NO_CHECK) {
                result = ddGroupSifting(table,lower,upper,ddNoCheck,
                                        DD_NORMAL_SIFT);
            } else if (table->groupcheck == CUDD_GROUP_CHECK5) {
                result = ddGroupSifting(table,lower,upper,ddExtSymmCheck,
                                        DD_NORMAL_SIFT);
            } else if (table->groupcheck == CUDD_GROUP_CHECK7) {
                result = ddGroupSifting(table,lower,upper,ddExtSymmCheck,
                                        DD_NORMAL_SIFT);
            } else {
                (void) fprintf(table->err,
                               "Unknown group ckecking method\n");
                result = 0;
            }
            break;
        case CUDD_REORDER_GROUP_SIFT_CONV:
            do {
                initialSize = table->keys - table->isolated;
                if (table->groupcheck == CUDD_NO_CHECK) {
                    result = ddGroupSifting(table,lower,upper,ddNoCheck,
                                            DD_NORMAL_SIFT);
                } else if (table->groupcheck == CUDD_GROUP_CHECK5) {
                    result = ddGroupSifting(table,lower,upper,ddExtSymmCheck,
                                            DD_NORMAL_SIFT);
                } else if (table->groupcheck == CUDD_GROUP_CHECK7) {
                    result = ddGroupSifting(table,lower,upper,ddExtSymmCheck,
                                            DD_NORMAL_SIFT);
                } else {
                    (void) fprintf(table->err,
                                   "Unknown group ckecking method\n");
                    result = 0;
                }
Alan Mishchenko committed
519
#ifdef DD_STATS
520
                (void) fprintf(table->out,"\n");
Alan Mishchenko committed
521
#endif
522 523 524 525
                result = cuddWindowReorder(table,lower,upper,
                                           CUDD_REORDER_WINDOW4);
                if (initialSize <= table->keys - table->isolated)
                    break;
Alan Mishchenko committed
526
#ifdef DD_STATS
527 528
                else
                    (void) fprintf(table->out,"\n");
Alan Mishchenko committed
529
#endif
530 531 532 533 534 535 536 537 538
            } while (result != 0);
            break;
        case CUDD_REORDER_WINDOW2:
        case CUDD_REORDER_WINDOW3:
        case CUDD_REORDER_WINDOW4:
        case CUDD_REORDER_WINDOW2_CONV:
        case CUDD_REORDER_WINDOW3_CONV:
        case CUDD_REORDER_WINDOW4_CONV:
            result = cuddWindowReorder(table,lower,upper,method);
Alan Mishchenko committed
539
            break;
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
        case CUDD_REORDER_ANNEALING:
            result = cuddAnnealing(table,lower,upper);
            break;
        case CUDD_REORDER_GENETIC:
            result = cuddGa(table,lower,upper);
            break;
        case CUDD_REORDER_LINEAR:
            result = cuddLinearAndSifting(table,lower,upper);
            break;
        case CUDD_REORDER_LINEAR_CONVERGE:
            do {
                initialSize = table->keys - table->isolated;
                result = cuddLinearAndSifting(table,lower,upper);
                if (initialSize <= table->keys - table->isolated)
                    break;
Alan Mishchenko committed
555
#ifdef DD_STATS
556 557
                else
                    (void) fprintf(table->out,"\n");
Alan Mishchenko committed
558
#endif
559 560 561 562 563 564 565 566 567 568 569 570
            } while (result != 0);
            break;
        case CUDD_REORDER_EXACT:
            result = cuddExact(table,lower,upper);
            break;
        case CUDD_REORDER_LAZY_SIFT:
            result = ddGroupSifting(table,lower,upper,ddVarGroupCheck,
                                    DD_LAZY_SIFT);
            break;
        default:
            return(0);
        }
Alan Mishchenko committed
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
    }

    /* Create a single group for all the variables that were sifted,
    ** so that they will be treated as a single block by successive
    ** invocations of ddGroupSifting.
    */
    ddMergeGroups(table,treenode,lower,upper);

#ifdef DD_DEBUG
    if (pr > 0) (void) fprintf(table->out,"ddReorderChildren:");
#endif

    return(result);

} /* end of ddReorderChildren */


/**Function********************************************************************

  Synopsis    [Finds the lower and upper bounds of the group represented
  by treenode.]

  Description [Finds the lower and upper bounds of the group
  represented by treenode.  From the index and size fields we need to
  derive the current positions, and find maximum and minimum.]

  SideEffects [The bounds are returned as side effects.]

  SeeAlso     []

******************************************************************************/
static void
ddFindNodeHiLo(
  DdManager * table,
  MtrNode * treenode,
  int * lower,
  int * upper)
{
    int low;
    int high;

    /* Check whether no variables in this group already exist.
    ** If so, return immediately. The calling procedure will know from
    ** the values of upper that no reordering is needed.
    */
    if ((int) treenode->low >= table->size) {
617 618 619
        *lower = table->size;
        *upper = -1;
        return;
Alan Mishchenko committed
620 621 622 623 624 625
    }

    *lower = low = (unsigned int) table->perm[treenode->index];
    high = (int) (low + treenode->size - 1);

    if (high >= table->size) {
626 627 628 629 630 631
        /* This is the case of a partially existing group. The aim is to
        ** reorder as many variables as safely possible.  If the tree
        ** node is terminal, we just reorder the subset of the group
        ** that is currently in existence.  If the group has
        ** subgroups, then we only reorder those subgroups that are
        ** fully instantiated.  This way we avoid breaking up a group.
Alan Mishchenko committed
632
        */
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
        MtrNode *auxnode = treenode->child;
        if (auxnode == NULL) {
            *upper = (unsigned int) table->size - 1;
        } else {
            /* Search the subgroup that strands the table->size line.
            ** If the first group starts at 0 and goes past table->size
            ** upper will get -1, thus correctly signaling that no reordering
            ** should take place.
            */
            while (auxnode != NULL) {
                int thisLower = table->perm[auxnode->low];
                int thisUpper = thisLower + auxnode->size - 1;
                if (thisUpper >= table->size && thisLower < table->size)
                    *upper = (unsigned int) thisLower - 1;
                auxnode = auxnode->younger;
            }
Alan Mishchenko committed
649 650
        }
    } else {
651 652
        /* Normal case: All the variables of the group exist. */
        *upper = (unsigned int) high;
Alan Mishchenko committed
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
    }

#ifdef DD_DEBUG
    /* Make sure that all variables in group are contiguous. */
    assert(treenode->size >= *upper - *lower + 1);
#endif

    return;

} /* end of ddFindNodeHiLo */


/**Function********************************************************************

  Synopsis    [Comparison function used by qsort.]

  Description [Comparison function used by qsort to order the variables
  according to the number of keys in the subtables.  Returns the
  difference in number of keys between the two variables being
  compared.]

  SideEffects [None]

******************************************************************************/
static int
ddUniqueCompareGroup(
  int * ptrX,
  int * ptrY)
{
#if 0
    if (entry[*ptrY] == entry[*ptrX]) {
684
        return((*ptrX) - (*ptrY));
Alan Mishchenko committed
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    }
#endif
    return(entry[*ptrY] - entry[*ptrX]);

} /* end of ddUniqueCompareGroup */


/**Function********************************************************************

  Synopsis    [Sifts from treenode->low to treenode->high.]

  Description [Sifts from treenode->low to treenode->high. If
  croupcheck == CUDD_GROUP_CHECK7, it checks for group creation at the
  end of the initial sifting. If a group is created, it is then sifted
  again. After sifting one variable, the group that contains it is
  dissolved.  Returns 1 in case of success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddGroupSifting(
  DdManager * table,
  int  lower,
  int  upper,
710
  DD_CHKFP checkFunction,
Alan Mishchenko committed
711 712
  int lazyFlag)
{
713 714 715 716 717 718 719 720
    int         *var;
    int         i,j,x,xInit;
    int         nvars;
    int         classes;
    int         result;
    int         *sifted;
    int         merged;
    int         dissolve;
Alan Mishchenko committed
721 722 723
#ifdef DD_STATS
    unsigned    previousSize;
#endif
724
    int         xindex;
Alan Mishchenko committed
725 726 727 728 729 730

    nvars = table->size;

    /* Order variables to sift. */
    entry = NULL;
    sifted = NULL;
Alan Mishchenko committed
731
    var = ABC_ALLOC(int,nvars);
Alan Mishchenko committed
732
    if (var == NULL) {
733 734
        table->errorCode = CUDD_MEMORY_OUT;
        goto ddGroupSiftingOutOfMem;
Alan Mishchenko committed
735
    }
Alan Mishchenko committed
736
    entry = ABC_ALLOC(int,nvars);
Alan Mishchenko committed
737
    if (entry == NULL) {
738 739
        table->errorCode = CUDD_MEMORY_OUT;
        goto ddGroupSiftingOutOfMem;
Alan Mishchenko committed
740
    }
Alan Mishchenko committed
741
    sifted = ABC_ALLOC(int,nvars);
Alan Mishchenko committed
742
    if (sifted == NULL) {
743 744
        table->errorCode = CUDD_MEMORY_OUT;
        goto ddGroupSiftingOutOfMem;
Alan Mishchenko committed
745 746 747 748
    }

    /* Here we consider only one representative for each group. */
    for (i = 0, classes = 0; i < nvars; i++) {
749 750 751 752 753 754 755
        sifted[i] = 0;
        x = table->perm[i];
        if ((unsigned) x >= table->subtables[x].next) {
            entry[i] = table->subtables[x].keys;
            var[classes] = i;
            classes++;
        }
Alan Mishchenko committed
756 757 758
    }

    qsort((void *)var,classes,sizeof(int),
759
          (DD_QSFP) ddUniqueCompareGroup);
Alan Mishchenko committed
760 761

    if (lazyFlag) {
762 763 764
        for (i = 0; i < nvars; i ++) {
            ddResetVarHandled(table, i);
        }
Alan Mishchenko committed
765 766 767 768
    }

    /* Now sift. */
    for (i = 0; i < ddMin(table->siftMaxVar,classes); i++) {
769 770 771 772 773
        if (ddTotalNumberSwapping >= table->siftMaxSwap)
            break;
        xindex = var[i];
        if (sifted[xindex] == 1) /* variable already sifted as part of group */
            continue;
Alan Mishchenko committed
774 775
        x = table->perm[xindex]; /* find current level of this variable */

776 777
        if (x < lower || x > upper || table->subtables[x].bindVar == 1)
            continue;
Alan Mishchenko committed
778
#ifdef DD_STATS
779
        previousSize = table->keys - table->isolated;
Alan Mishchenko committed
780 781
#endif
#ifdef DD_DEBUG
782
        /* x is bottom of group */
Alan Mishchenko committed
783 784
        assert((unsigned) x >= table->subtables[x].next);
#endif
785 786 787 788 789 790 791
        if ((unsigned) x == table->subtables[x].next) {
            dissolve = 1;
            result = ddGroupSiftingAux(table,x,lower,upper,checkFunction,
                                        lazyFlag);
        } else {
            dissolve = 0;
            result = ddGroupSiftingAux(table,x,lower,upper,ddNoCheck,lazyFlag);
Alan Mishchenko committed
792
        }
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
        if (!result) goto ddGroupSiftingOutOfMem;

        /* check for aggregation */
        merged = 0;
        if (lazyFlag == 0 && table->groupcheck == CUDD_GROUP_CHECK7) {
            x = table->perm[xindex]; /* find current level */
            if ((unsigned) x == table->subtables[x].next) { /* not part of a group */
                if (x != upper && sifted[table->invperm[x+1]] == 0 &&
                (unsigned) x+1 == table->subtables[x+1].next) {
                    if (ddSecDiffCheck(table,x,x+1)) {
                        merged =1;
                        ddCreateGroup(table,x,x+1);
                    }
                }
                if (x != lower && sifted[table->invperm[x-1]] == 0 &&
                (unsigned) x-1 == table->subtables[x-1].next) {
                    if (ddSecDiffCheck(table,x-1,x)) {
                        merged =1;
                        ddCreateGroup(table,x-1,x);
                    }
                }
Alan Mishchenko committed
814 815 816
            }
        }

817 818 819 820 821 822 823
        if (merged) { /* a group was created */
            /* move x to bottom of group */
            while ((unsigned) x < table->subtables[x].next)
                x = table->subtables[x].next;
            /* sift */
            result = ddGroupSiftingAux(table,x,lower,upper,ddNoCheck,lazyFlag);
            if (!result) goto ddGroupSiftingOutOfMem;
Alan Mishchenko committed
824
#ifdef DD_STATS
825 826 827 828 829 830 831 832
            if (table->keys < previousSize + table->isolated) {
                (void) fprintf(table->out,"_");
            } else if (table->keys > previousSize + table->isolated) {
                (void) fprintf(table->out,"^");
            } else {
                (void) fprintf(table->out,"*");
            }
            fflush(table->out);
Alan Mishchenko committed
833
        } else {
834 835 836 837 838 839 840 841
            if (table->keys < previousSize + table->isolated) {
                (void) fprintf(table->out,"-");
            } else if (table->keys > previousSize + table->isolated) {
                (void) fprintf(table->out,"+");
            } else {
                (void) fprintf(table->out,"=");
            }
            fflush(table->out);
Alan Mishchenko committed
842
#endif
843
        }
Alan Mishchenko committed
844

845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
        /* Mark variables in the group just sifted. */
        x = table->perm[xindex];
        if ((unsigned) x != table->subtables[x].next) {
            xInit = x;
            do {
                j = table->invperm[x];
                sifted[j] = 1;
                x = table->subtables[x].next;
            } while (x != xInit);

            /* Dissolve the group if it was created. */
            if (lazyFlag == 0 && dissolve) {
                do {
                    j = table->subtables[x].next;
                    table->subtables[x].next = x;
                    x = j;
                } while (x != xInit);
            }
Alan Mishchenko committed
863 864 865
        }

#ifdef DD_DEBUG
866
        if (pr > 0) (void) fprintf(table->out,"ddGroupSifting:");
Alan Mishchenko committed
867 868 869 870 871
#endif

      if (lazyFlag) ddSetVarHandled(table, xindex);
    } /* for */

Alan Mishchenko committed
872 873 874
    ABC_FREE(sifted);
    ABC_FREE(var);
    ABC_FREE(entry);
Alan Mishchenko committed
875 876 877 878

    return(1);

ddGroupSiftingOutOfMem:
879
    if (entry != NULL)  ABC_FREE(entry);
Alan Mishchenko committed
880
    if (var != NULL)    ABC_FREE(var);
881
    if (sifted != NULL) ABC_FREE(sifted);
Alan Mishchenko committed
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914

    return(0);

} /* end of ddGroupSifting */


/**Function********************************************************************

  Synopsis    [Creates a group encompassing variables from x to y in the
  DD table.]

  Description [Creates a group encompassing variables from x to y in the
  DD table. In the current implementation it must be y == x+1.
  Returns 1 in case of success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static void
ddCreateGroup(
  DdManager * table,
  int  x,
  int  y)
{
    int  gybot;

#ifdef DD_DEBUG
    assert(y == x+1);
#endif

    /* Find bottom of second group. */
    gybot = y;
    while ((unsigned) gybot < table->subtables[gybot].next)
915
        gybot = table->subtables[gybot].next;
Alan Mishchenko committed
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946

    /* Link groups. */
    table->subtables[x].next = y;
    table->subtables[gybot].next = x;

    return;

} /* ddCreateGroup */


/**Function********************************************************************

  Synopsis    [Sifts one variable up and down until it has taken all
  positions. Checks for aggregation.]

  Description [Sifts one variable up and down until it has taken all
  positions. Checks for aggregation. There may be at most two sweeps,
  even if the group grows.  Assumes that x is either an isolated
  variable, or it is the bottom of a group. All groups may not have
  been found. The variable being moved is returned to the best position
  seen during sifting.  Returns 1 in case of success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddGroupSiftingAux(
  DdManager * table,
  int  x,
  int  xLow,
  int  xHigh,
947
  DD_CHKFP checkFunction,
Alan Mishchenko committed
948 949 950
  int lazyFlag)
{
    Move *move;
951
    Move *moves;        /* list of moves */
Alan Mishchenko committed
952 953 954 955 956 957 958
    int  initialSize;
    int  result;
    int  y;
    int  topbot;

#ifdef DD_DEBUG
    if (pr > 0) (void) fprintf(table->out,
959
                               "ddGroupSiftingAux from %d to %d\n",xLow,xHigh);
Alan Mishchenko committed
960 961 962 963 964 965
    assert((unsigned) x >= table->subtables[x].next); /* x is bottom of group */
#endif

    initialSize = table->keys - table->isolated;
    moves = NULL;

966
    originalSize = initialSize;         /* for lazy sifting */
Alan Mishchenko committed
967 968 969 970 971

    /* If we have a singleton, we check for aggregation in both
    ** directions before we sift.
    */
    if ((unsigned) x == table->subtables[x].next) {
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997
        /* Will go down first, unless x == xHigh:
        ** Look for aggregation above x.
        */
        for (y = x; y > xLow; y--) {
            if (!checkFunction(table,y-1,y))
                break;
            topbot = table->subtables[y-1].next; /* find top of y-1's group */
            table->subtables[y-1].next = y;
            table->subtables[x].next = topbot; /* x is bottom of group so its */
                                               /* next is top of y-1's group */
            y = topbot + 1; /* add 1 for y--; new y is top of group */
        }
        /* Will go up first unless x == xlow:
        ** Look for aggregation below x.
        */
        for (y = x; y < xHigh; y++) {
            if (!checkFunction(table,y,y+1))
                break;
            /* find bottom of y+1's group */
            topbot = y + 1;
            while ((unsigned) topbot < table->subtables[topbot].next) {
                topbot = table->subtables[topbot].next;
            }
            table->subtables[topbot].next = table->subtables[y].next;
            table->subtables[y].next = y + 1;
            y = topbot - 1; /* subtract 1 for y++; new y is bottom of group */
Alan Mishchenko committed
998 999 1000 1001 1002 1003 1004
        }
    }

    /* Now x may be in the middle of a group.
    ** Find bottom of x's group.
    */
    while ((unsigned) x < table->subtables[x].next)
1005
        x = table->subtables[x].next;
Alan Mishchenko committed
1006 1007 1008

    if (x == xLow) { /* Sift down */
#ifdef DD_DEBUG
1009 1010
        /* x must be a singleton */
        assert((unsigned) x == table->subtables[x].next);
Alan Mishchenko committed
1011
#endif
1012
        if (x == xHigh) return(1);      /* just one variable */
Alan Mishchenko committed
1013 1014 1015

        if (!ddGroupSiftingDown(table,x,xHigh,checkFunction,&moves))
            goto ddGroupSiftingAuxOutOfMem;
1016
        /* at this point x == xHigh, unless early term */
Alan Mishchenko committed
1017

1018 1019 1020
        /* move backward and stop at best position */
        result = ddGroupSiftingBackward(table,moves,initialSize,
                                        DD_SIFT_DOWN,lazyFlag);
Alan Mishchenko committed
1021
#ifdef DD_DEBUG
1022
        assert(table->keys - table->isolated <= (unsigned) initialSize);
Alan Mishchenko committed
1023 1024 1025 1026 1027
#endif
        if (!result) goto ddGroupSiftingAuxOutOfMem;

    } else if (cuddNextHigh(table,x) > xHigh) { /* Sift up */
#ifdef DD_DEBUG
1028
        /* x is bottom of group */
Alan Mishchenko committed
1029 1030 1031 1032 1033 1034 1035
        assert((unsigned) x >= table->subtables[x].next);
#endif
        /* Find top of x's group */
        x = table->subtables[x].next;

        if (!ddGroupSiftingUp(table,x,xLow,checkFunction,&moves))
            goto ddGroupSiftingAuxOutOfMem;
1036
        /* at this point x == xLow, unless early term */
Alan Mishchenko committed
1037

1038 1039 1040
        /* move backward and stop at best position */
        result = ddGroupSiftingBackward(table,moves,initialSize,
                                        DD_SIFT_UP,lazyFlag);
Alan Mishchenko committed
1041
#ifdef DD_DEBUG
1042
        assert(table->keys - table->isolated <= (unsigned) initialSize);
Alan Mishchenko committed
1043 1044 1045 1046 1047 1048
#endif
        if (!result) goto ddGroupSiftingAuxOutOfMem;

    } else if (x - xLow > xHigh - x) { /* must go down first: shorter */
        if (!ddGroupSiftingDown(table,x,xHigh,checkFunction,&moves))
            goto ddGroupSiftingAuxOutOfMem;
1049
        /* at this point x == xHigh, unless early term */
Alan Mishchenko committed
1050 1051

        /* Find top of group */
1052 1053 1054 1055 1056
        if (moves) {
            x = moves->y;
        }
        while ((unsigned) x < table->subtables[x].next)
            x = table->subtables[x].next;
Alan Mishchenko committed
1057 1058 1059 1060 1061 1062 1063 1064 1065
        x = table->subtables[x].next;
#ifdef DD_DEBUG
        /* x should be the top of a group */
        assert((unsigned) x <= table->subtables[x].next);
#endif

        if (!ddGroupSiftingUp(table,x,xLow,checkFunction,&moves))
            goto ddGroupSiftingAuxOutOfMem;

1066 1067 1068
        /* move backward and stop at best position */
        result = ddGroupSiftingBackward(table,moves,initialSize,
                                        DD_SIFT_UP,lazyFlag);
Alan Mishchenko committed
1069
#ifdef DD_DEBUG
1070
        assert(table->keys - table->isolated <= (unsigned) initialSize);
Alan Mishchenko committed
1071 1072 1073 1074 1075 1076 1077 1078 1079
#endif
        if (!result) goto ddGroupSiftingAuxOutOfMem;

    } else { /* moving up first: shorter */
        /* Find top of x's group */
        x = table->subtables[x].next;

        if (!ddGroupSiftingUp(table,x,xLow,checkFunction,&moves))
            goto ddGroupSiftingAuxOutOfMem;
1080
        /* at this point x == xHigh, unless early term */
Alan Mishchenko committed
1081 1082

        if (moves) {
1083 1084 1085 1086
            x = moves->x;
        }
        while ((unsigned) x < table->subtables[x].next)
            x = table->subtables[x].next;
Alan Mishchenko committed
1087 1088 1089 1090 1091 1092 1093 1094
#ifdef DD_DEBUG
        /* x is bottom of a group */
        assert((unsigned) x >= table->subtables[x].next);
#endif

        if (!ddGroupSiftingDown(table,x,xHigh,checkFunction,&moves))
            goto ddGroupSiftingAuxOutOfMem;

1095 1096 1097
        /* move backward and stop at best position */
        result = ddGroupSiftingBackward(table,moves,initialSize,
                                        DD_SIFT_DOWN,lazyFlag);
Alan Mishchenko committed
1098
#ifdef DD_DEBUG
1099
        assert(table->keys - table->isolated <= (unsigned) initialSize);
Alan Mishchenko committed
1100 1101 1102 1103 1104 1105
#endif
        if (!result) goto ddGroupSiftingAuxOutOfMem;
    }

    while (moves != NULL) {
        move = moves->next;
1106
        cuddDeallocMove(table, moves);
Alan Mishchenko committed
1107 1108 1109 1110 1111 1112 1113 1114
        moves = move;
    }

    return(1);

ddGroupSiftingAuxOutOfMem:
    while (moves != NULL) {
        move = moves->next;
1115
        cuddDeallocMove(table, moves);
Alan Mishchenko committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
        moves = move;
    }

    return(0);

} /* end of ddGroupSiftingAux */


/**Function********************************************************************

  Synopsis    [Sifts up a variable until either it reaches position xLow
  or the size of the DD heap increases too much.]

  Description [Sifts up a variable until either it reaches position
  xLow or the size of the DD heap increases too much. Assumes that y is
  the top of a group (or a singleton).  Checks y for aggregation to the
  adjacent variables. Records all the moves that are appended to the
  list of moves received as input and returned as a side effect.
  Returns 1 in case of success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddGroupSiftingUp(
  DdManager * table,
  int  y,
  int  xLow,
1144
  DD_CHKFP checkFunction,
Alan Mishchenko committed
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
  Move ** moves)
{
    Move *move;
    int  x;
    int  size;
    int  i;
    int  gxtop,gybot;
    int  limitSize;
    int  xindex, yindex;
    int  zindex;
    int  z;
    int  isolated;
1157
    int  L;     /* lower bound on DD size */
Alan Mishchenko committed
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
#ifdef DD_DEBUG
    int  checkL;
#endif

    yindex = table->invperm[y];

    /* Initialize the lower bound.
    ** The part of the DD below the bottom of y's group will not change.
    ** The part of the DD above y that does not interact with any
    ** variable of y's group will not change.
    ** The rest may vanish in the best case, except for
    ** the nodes at level xLow, which will not vanish, regardless.
    ** What we use here is not really a lower bound, because we ignore
    ** the interactions with all variables except y.
    */
    limitSize = L = table->keys - table->isolated;
    gybot = y;
    while ((unsigned) gybot < table->subtables[gybot].next)
1176
        gybot = table->subtables[gybot].next;
Alan Mishchenko committed
1177
    for (z = xLow + 1; z <= gybot; z++) {
1178 1179 1180 1181 1182
        zindex = table->invperm[z];
        if (zindex == yindex || cuddTestInteract(table,zindex,yindex)) {
            isolated = table->vars[zindex]->ref == 1;
            L -= table->subtables[z].keys - isolated;
        }
Alan Mishchenko committed
1183 1184 1185 1186 1187
    }

    x = cuddNextLow(table,y);
    while (x >= xLow && L <= limitSize) {
#ifdef DD_DEBUG
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
        gybot = y;
        while ((unsigned) gybot < table->subtables[gybot].next)
            gybot = table->subtables[gybot].next;
        checkL = table->keys - table->isolated;
        for (z = xLow + 1; z <= gybot; z++) {
            zindex = table->invperm[z];
            if (zindex == yindex || cuddTestInteract(table,zindex,yindex)) {
                isolated = table->vars[zindex]->ref == 1;
                checkL -= table->subtables[z].keys - isolated;
            }
        }
        if (pr > 0 && L != checkL) {
            (void) fprintf(table->out,
                           "Inaccurate lower bound: L = %d checkL = %d\n",
                           L, checkL);
Alan Mishchenko committed
1203 1204 1205 1206
        }
#endif
        gxtop = table->subtables[x].next;
        if (checkFunction(table,x,y)) {
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
            /* Group found, attach groups */
            table->subtables[x].next = y;
            i = table->subtables[y].next;
            while (table->subtables[i].next != (unsigned) y)
                i = table->subtables[i].next;
            table->subtables[i].next = gxtop;
            move = (Move *)cuddDynamicAllocNode(table);
            if (move == NULL) goto ddGroupSiftingUpOutOfMem;
            move->x = x;
            move->y = y;
            move->flags = MTR_NEWNODE;
            move->size = table->keys - table->isolated;
            move->next = *moves;
            *moves = move;
Alan Mishchenko committed
1221
        } else if (table->subtables[x].next == (unsigned) x &&
1222
                   table->subtables[y].next == (unsigned) y) {
Alan Mishchenko committed
1223
            /* x and y are self groups */
1224
            xindex = table->invperm[x];
Alan Mishchenko committed
1225 1226 1227 1228 1229 1230
            size = cuddSwapInPlace(table,x,y);
#ifdef DD_DEBUG
            assert(table->subtables[x].next == (unsigned) x);
            assert(table->subtables[y].next == (unsigned) y);
#endif
            if (size == 0) goto ddGroupSiftingUpOutOfMem;
1231 1232 1233 1234 1235
            /* Update the lower bound. */
            if (cuddTestInteract(table,xindex,yindex)) {
                isolated = table->vars[xindex]->ref == 1;
                L += table->subtables[y].keys - isolated;
            }
Alan Mishchenko committed
1236 1237 1238 1239
            move = (Move *)cuddDynamicAllocNode(table);
            if (move == NULL) goto ddGroupSiftingUpOutOfMem;
            move->x = x;
            move->y = y;
1240
            move->flags = MTR_DEFAULT;
Alan Mishchenko committed
1241 1242 1243 1244 1245
            move->size = size;
            move->next = *moves;
            *moves = move;

#ifdef DD_DEBUG
1246 1247
            if (pr > 0) (void) fprintf(table->out,
                                       "ddGroupSiftingUp (2 single groups):\n");
Alan Mishchenko committed
1248 1249
#endif
            if ((double) size > (double) limitSize * table->maxGrowth)
1250
                return(1);
Alan Mishchenko committed
1251 1252 1253
            if (size < limitSize) limitSize = size;
        } else { /* Group move */
            size = ddGroupMove(table,x,y,moves);
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
            if (size == 0) goto ddGroupSiftingUpOutOfMem;
            /* Update the lower bound. */
            z = (*moves)->y;
            do {
                zindex = table->invperm[z];
                if (cuddTestInteract(table,zindex,yindex)) {
                    isolated = table->vars[zindex]->ref == 1;
                    L += table->subtables[z].keys - isolated;
                }
                z = table->subtables[z].next;
            } while (z != (int) (*moves)->y);
Alan Mishchenko committed
1265
            if ((double) size > (double) limitSize * table->maxGrowth)
1266
                return(1);
Alan Mishchenko committed
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
            if (size < limitSize) limitSize = size;
        }
        y = gxtop;
        x = cuddNextLow(table,y);
    }

    return(1);

ddGroupSiftingUpOutOfMem:
    while (*moves != NULL) {
        move = (*moves)->next;
1278
        cuddDeallocMove(table, *moves);
Alan Mishchenko committed
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
        *moves = move;
    }
    return(0);

} /* end of ddGroupSiftingUp */


/**Function********************************************************************

  Synopsis    [Sifts down a variable until it reaches position xHigh.]

  Description [Sifts down a variable until it reaches position xHigh.
  Assumes that x is the bottom of a group (or a singleton).  Records
  all the moves.  Returns 1 in case of success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddGroupSiftingDown(
  DdManager * table,
  int  x,
  int  xHigh,
1302
  DD_CHKFP checkFunction,
Alan Mishchenko committed
1303 1304 1305 1306 1307 1308 1309
  Move ** moves)
{
    Move *move;
    int  y;
    int  size;
    int  limitSize;
    int  gxtop,gybot;
1310
    int  R;     /* upper bound on node decrease */
Alan Mishchenko committed
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326
    int  xindex, yindex;
    int  isolated, allVars;
    int  z;
    int  zindex;
#ifdef DD_DEBUG
    int  checkR;
#endif

    /* If the group consists of simple variables, there is no point in
    ** sifting it down. This check is redundant if the projection functions
    ** do not have external references, because the computation of the
    ** lower bound takes care of the problem.  It is necessary otherwise to
    ** prevent the sifting down of simple variables. */
    y = x;
    allVars = 1;
    do {
1327 1328 1329 1330 1331
        if (table->subtables[y].keys != 1) {
            allVars = 0;
            break;
        }
        y = table->subtables[y].next;
Alan Mishchenko committed
1332 1333
    } while (table->subtables[y].next != (unsigned) x);
    if (allVars)
1334 1335
        return(1);

Alan Mishchenko committed
1336 1337 1338 1339 1340 1341
    /* Initialize R. */
    xindex = table->invperm[x];
    gxtop = table->subtables[x].next;
    limitSize = size = table->keys - table->isolated;
    R = 0;
    for (z = xHigh; z > gxtop; z--) {
1342 1343 1344 1345 1346
        zindex = table->invperm[z];
        if (zindex == xindex || cuddTestInteract(table,xindex,zindex)) {
            isolated = table->vars[zindex]->ref == 1;
            R += table->subtables[z].keys - isolated;
        }
Alan Mishchenko committed
1347 1348 1349 1350 1351
    }

    y = cuddNextHigh(table,x);
    while (y <= xHigh && size - R < limitSize) {
#ifdef DD_DEBUG
1352 1353 1354 1355 1356 1357 1358 1359
        gxtop = table->subtables[x].next;
        checkR = 0;
        for (z = xHigh; z > gxtop; z--) {
            zindex = table->invperm[z];
            if (zindex == xindex || cuddTestInteract(table,xindex,zindex)) {
                isolated = table->vars[zindex]->ref == 1;
                checkR += table->subtables[z].keys - isolated;
            }
Alan Mishchenko committed
1360
        }
1361
        assert(R >= checkR);
Alan Mishchenko committed
1362
#endif
1363
        /* Find bottom of y group. */
Alan Mishchenko committed
1364 1365 1366 1367 1368
        gybot = table->subtables[y].next;
        while (table->subtables[gybot].next != (unsigned) y)
            gybot = table->subtables[gybot].next;

        if (checkFunction(table,x,y)) {
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
            /* Group found: attach groups and record move. */
            gxtop = table->subtables[x].next;
            table->subtables[x].next = y;
            table->subtables[gybot].next = gxtop;
            move = (Move *)cuddDynamicAllocNode(table);
            if (move == NULL) goto ddGroupSiftingDownOutOfMem;
            move->x = x;
            move->y = y;
            move->flags = MTR_NEWNODE;
            move->size = table->keys - table->isolated;
            move->next = *moves;
            *moves = move;
Alan Mishchenko committed
1381
        } else if (table->subtables[x].next == (unsigned) x &&
1382
                   table->subtables[y].next == (unsigned) y) {
Alan Mishchenko committed
1383
            /* x and y are self groups */
1384 1385 1386 1387 1388 1389
            /* Update upper bound on node decrease. */
            yindex = table->invperm[y];
            if (cuddTestInteract(table,xindex,yindex)) {
                isolated = table->vars[yindex]->ref == 1;
                R -= table->subtables[y].keys - isolated;
            }
Alan Mishchenko committed
1390 1391 1392 1393 1394 1395 1396
            size = cuddSwapInPlace(table,x,y);
#ifdef DD_DEBUG
            assert(table->subtables[x].next == (unsigned) x);
            assert(table->subtables[y].next == (unsigned) y);
#endif
            if (size == 0) goto ddGroupSiftingDownOutOfMem;

1397
            /* Record move. */
Alan Mishchenko committed
1398 1399 1400 1401
            move = (Move *) cuddDynamicAllocNode(table);
            if (move == NULL) goto ddGroupSiftingDownOutOfMem;
            move->x = x;
            move->y = y;
1402
            move->flags = MTR_DEFAULT;
Alan Mishchenko committed
1403 1404 1405 1406 1407 1408
            move->size = size;
            move->next = *moves;
            *moves = move;

#ifdef DD_DEBUG
            if (pr > 0) (void) fprintf(table->out,
1409
                                       "ddGroupSiftingDown (2 single groups):\n");
Alan Mishchenko committed
1410 1411 1412 1413 1414 1415 1416 1417
#endif
            if ((double) size > (double) limitSize * table->maxGrowth)
                return(1);
            if (size < limitSize) limitSize = size;

            x = y;
            y = cuddNextHigh(table,x);
        } else { /* Group move */
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
            /* Update upper bound on node decrease: first phase. */
            gxtop = table->subtables[x].next;
            z = gxtop + 1;
            do {
                zindex = table->invperm[z];
                if (zindex == xindex || cuddTestInteract(table,xindex,zindex)) {
                    isolated = table->vars[zindex]->ref == 1;
                    R -= table->subtables[z].keys - isolated;
                }
                z++;
            } while (z <= gybot);
Alan Mishchenko committed
1429 1430 1431
            size = ddGroupMove(table,x,y,moves);
            if (size == 0) goto ddGroupSiftingDownOutOfMem;
            if ((double) size > (double) limitSize * table->maxGrowth)
1432
                return(1);
Alan Mishchenko committed
1433 1434
            if (size < limitSize) limitSize = size;

1435 1436 1437 1438 1439 1440 1441 1442 1443
            /* Update upper bound on node decrease: second phase. */
            gxtop = table->subtables[gybot].next;
            for (z = gxtop + 1; z <= gybot; z++) {
                zindex = table->invperm[z];
                if (zindex == xindex || cuddTestInteract(table,xindex,zindex)) {
                    isolated = table->vars[zindex]->ref == 1;
                    R += table->subtables[z].keys - isolated;
                }
            }
Alan Mishchenko committed
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453
        }
        x = gybot;
        y = cuddNextHigh(table,x);
    }

    return(1);

ddGroupSiftingDownOutOfMem:
    while (*moves != NULL) {
        move = (*moves)->next;
1454
        cuddDeallocMove(table, *moves);
Alan Mishchenko committed
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
        *moves = move;
    }

    return(0);

} /* end of ddGroupSiftingDown */


/**Function********************************************************************

  Synopsis    [Swaps two groups and records the move.]

  Description [Swaps two groups and records the move. Returns the
  number of keys in the DD table in case of success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddGroupMove(
  DdManager * table,
  int  x,
  int  y,
  Move ** moves)
{
    Move *move;
    int  size;
    int  i,j,xtop,xbot,xsize,ytop,ybot,ysize,newxtop;
1483
    int  swapx = -1,swapy = -1;
Alan Mishchenko committed
1484 1485 1486 1487
#if defined(DD_DEBUG) && defined(DD_VERBOSE)
    int  initialSize,bestSize;
#endif

1488
#ifdef DD_DEBUG
Alan Mishchenko committed
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
    /* We assume that x < y */
    assert(x < y);
#endif
    /* Find top, bottom, and size for the two groups. */
    xbot = x;
    xtop = table->subtables[x].next;
    xsize = xbot - xtop + 1;
    ybot = y;
    while ((unsigned) ybot < table->subtables[ybot].next)
        ybot = table->subtables[ybot].next;
    ytop = y;
    ysize = ybot - ytop + 1;

#if defined(DD_DEBUG) && defined(DD_VERBOSE)
    initialSize = bestSize = table->keys - table->isolated;
#endif
    /* Sift the variables of the second group up through the first group */
    for (i = 1; i <= ysize; i++) {
        for (j = 1; j <= xsize; j++) {
            size = cuddSwapInPlace(table,x,y);
            if (size == 0) goto ddGroupMoveOutOfMem;
#if defined(DD_DEBUG) && defined(DD_VERBOSE)
1511 1512
            if (size < bestSize)
                bestSize = size;
Alan Mishchenko committed
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
#endif
            swapx = x; swapy = y;
            y = x;
            x = cuddNextLow(table,y);
        }
        y = ytop + i;
        x = cuddNextLow(table,y);
    }
#if defined(DD_DEBUG) && defined(DD_VERBOSE)
    if ((bestSize < initialSize) && (bestSize < size))
1523
        (void) fprintf(table->out,"Missed local minimum: initialSize:%d  bestSize:%d  finalSize:%d\n",initialSize,bestSize,size);
Alan Mishchenko committed
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
#endif

    /* fix groups */
    y = xtop; /* ytop is now where xtop used to be */
    for (i = 0; i < ysize - 1; i++) {
        table->subtables[y].next = cuddNextHigh(table,y);
        y = cuddNextHigh(table,y);
    }
    table->subtables[y].next = xtop; /* y is bottom of its group, join */
                                    /* it to top of its group */
    x = cuddNextHigh(table,y);
    newxtop = x;
    for (i = 0; i < xsize - 1; i++) {
        table->subtables[x].next = cuddNextHigh(table,x);
        x = cuddNextHigh(table,x);
    }
    table->subtables[x].next = newxtop; /* x is bottom of its group, join */
                                    /* it to top of its group */
#ifdef DD_DEBUG
    if (pr > 0) (void) fprintf(table->out,"ddGroupMove:\n");
#endif

    /* Store group move */
    move = (Move *) cuddDynamicAllocNode(table);
    if (move == NULL) goto ddGroupMoveOutOfMem;
    move->x = swapx;
    move->y = swapy;
    move->flags = MTR_DEFAULT;
    move->size = table->keys - table->isolated;
    move->next = *moves;
    *moves = move;

    return(table->keys - table->isolated);

ddGroupMoveOutOfMem:
    while (*moves != NULL) {
        move = (*moves)->next;
1561
        cuddDeallocMove(table, *moves);
Alan Mishchenko committed
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
        *moves = move;
    }
    return(0);

} /* end of ddGroupMove */


/**Function********************************************************************

  Synopsis    [Undoes the swap two groups.]

  Description [Undoes the swap two groups.  Returns 1 in case of
  success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddGroupMoveBackward(
  DdManager * table,
  int  x,
  int  y)
{
    int size;
    int i,j,xtop,xbot,xsize,ytop,ybot,ysize,newxtop;


1589
#ifdef DD_DEBUG
Alan Mishchenko committed
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
    /* We assume that x < y */
    assert(x < y);
#endif

    /* Find top, bottom, and size for the two groups. */
    xbot = x;
    xtop = table->subtables[x].next;
    xsize = xbot - xtop + 1;
    ybot = y;
    while ((unsigned) ybot < table->subtables[ybot].next)
        ybot = table->subtables[ybot].next;
    ytop = y;
    ysize = ybot - ytop + 1;

    /* Sift the variables of the second group up through the first group */
    for (i = 1; i <= ysize; i++) {
        for (j = 1; j <= xsize; j++) {
            size = cuddSwapInPlace(table,x,y);
            if (size == 0)
                return(0);
            y = x;
            x = cuddNextLow(table,y);
        }
        y = ytop + i;
        x = cuddNextLow(table,y);
    }

    /* fix groups */
    y = xtop;
    for (i = 0; i < ysize - 1; i++) {
        table->subtables[y].next = cuddNextHigh(table,y);
        y = cuddNextHigh(table,y);
    }
    table->subtables[y].next = xtop; /* y is bottom of its group, join */
                                    /* to its top */
    x = cuddNextHigh(table,y);
    newxtop = x;
    for (i = 0; i < xsize - 1; i++) {
        table->subtables[x].next = cuddNextHigh(table,x);
        x = cuddNextHigh(table,x);
    }
    table->subtables[x].next = newxtop; /* x is bottom of its group, join */
                                    /* to its top */
#ifdef DD_DEBUG
    if (pr > 0) (void) fprintf(table->out,"ddGroupMoveBackward:\n");
#endif

    return(1);

} /* end of ddGroupMoveBackward */


/**Function********************************************************************

  Synopsis    [Determines the best position for a variables and returns
  it there.]

  Description [Determines the best position for a variables and returns
  it there.  Returns 1 in case of success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddGroupSiftingBackward(
  DdManager * table,
  Move * moves,
  int  size,
1658
  int  upFlag,
Alan Mishchenko committed
1659 1660 1661 1662
  int  lazyFlag)
{
    Move *move;
    int  res;
1663
    Move *end_move = NULL;
Alan Mishchenko committed
1664
    int diff, tmp_diff;
1665 1666
    int index;
    unsigned int pairlev;
Alan Mishchenko committed
1667 1668

    if (lazyFlag) {
1669
        end_move = NULL;
Alan Mishchenko committed
1670

1671
        /* Find the minimum size, and the earliest position at which it
Alan Mishchenko committed
1672 1673
        ** was achieved. */
        for (move = moves; move != NULL; move = move->next) {
1674 1675 1676 1677 1678
            if (move->size < size) {
                size = move->size;
                end_move = move;
            } else if (move->size == size) {
                if (end_move == NULL) end_move = move;
Alan Mishchenko committed
1679 1680
            }
        }
1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705

        /* Find among the moves that give minimum size the one that
        ** minimizes the distance from the corresponding variable. */
        if (moves != NULL) {
            diff = Cudd_ReadSize(table) + 1;
            index = (upFlag == 1) ?
                    table->invperm[moves->x] : table->invperm[moves->y];
            pairlev =
                (unsigned) table->perm[Cudd_bddReadPairIndex(table, index)];

            for (move = moves; move != NULL; move = move->next) {
                if (move->size == size) {
                    if (upFlag == 1) {
                        tmp_diff = (move->x > pairlev) ?
                                    move->x - pairlev : pairlev - move->x;
                    } else {
                        tmp_diff = (move->y > pairlev) ?
                                    move->y - pairlev : pairlev - move->y;
                    }
                    if (tmp_diff < diff) {
                        diff = tmp_diff;
                        end_move = move;
                    }
                }
            }
Alan Mishchenko committed
1706 1707
        }
    } else {
1708 1709 1710 1711 1712 1713
        /* Find the minimum size. */
        for (move = moves; move != NULL; move = move->next) {
            if (move->size < size) {
                size = move->size;
            }
        }
Alan Mishchenko committed
1714 1715 1716 1717 1718 1719
    }

    /* In case of lazy sifting, end_move identifies the position at
    ** which we want to stop.  Otherwise, we stop as soon as we meet
    ** the minimum size. */
    for (move = moves; move != NULL; move = move->next) {
1720 1721 1722 1723 1724
        if (lazyFlag) {
            if (move == end_move) return(1);
        } else {
            if (move->size == size) return(1);
        }
Alan Mishchenko committed
1725
        if ((table->subtables[move->x].next == move->x) &&
1726
        (table->subtables[move->y].next == move->y)) {
Alan Mishchenko committed
1727 1728 1729 1730 1731 1732 1733 1734
            res = cuddSwapInPlace(table,(int)move->x,(int)move->y);
            if (!res) return(0);
#ifdef DD_DEBUG
            if (pr > 0) (void) fprintf(table->out,"ddGroupSiftingBackward:\n");
            assert(table->subtables[move->x].next == move->x);
            assert(table->subtables[move->y].next == move->y);
#endif
        } else { /* Group move necessary */
1735 1736 1737 1738 1739 1740
            if (move->flags == MTR_NEWNODE) {
                ddDissolveGroup(table,(int)move->x,(int)move->y);
            } else {
                res = ddGroupMoveBackward(table,(int)move->x,(int)move->y);
                if (!res) return(0);
            }
Alan Mishchenko committed
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
        }

    }

    return(1);

} /* end of ddGroupSiftingBackward */


/**Function********************************************************************

  Synopsis    [Merges groups in the DD table.]

  Description [Creates a single group from low to high and adjusts the
  index field of the tree node.]

  SideEffects [None]

******************************************************************************/
static void
ddMergeGroups(
  DdManager * table,
  MtrNode * treenode,
  int  low,
  int  high)
{
    int i;
    MtrNode *auxnode;
    int saveindex;
    int newindex;

    /* Merge all variables from low to high in one group, unless
    ** this is the topmost group. In such a case we do not merge lest
    ** we lose the symmetry information. */
    if (treenode != table->tree) {
1776 1777 1778
        for (i = low; i < high; i++)
            table->subtables[i].next = i+1;
        table->subtables[high].next = low;
Alan Mishchenko committed
1779 1780 1781 1782 1783 1784 1785 1786
    }

    /* Adjust the index fields of the tree nodes. If a node is the
    ** first child of its parent, then the parent may also need adjustment. */
    saveindex = treenode->index;
    newindex = table->invperm[low];
    auxnode = treenode;
    do {
1787 1788 1789 1790 1791
        auxnode->index = newindex;
        if (auxnode->parent == NULL ||
                (int) auxnode->parent->index != saveindex)
            break;
        auxnode = auxnode->parent;
Alan Mishchenko committed
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
    } while (1);
    return;

} /* end of ddMergeGroups */


/**Function********************************************************************

  Synopsis    [Dissolves a group in the DD table.]

  Description [x and y are variables in a group to be cut in two. The cut
  is to pass between x and y.]

  SideEffects [None]

******************************************************************************/
static void
ddDissolveGroup(
  DdManager * table,
  int  x,
  int  y)
{
    int topx;
    int boty;

    /* find top and bottom of the two groups */
    boty = y;
    while ((unsigned) boty < table->subtables[boty].next)
1820 1821
        boty = table->subtables[boty].next;

Alan Mishchenko committed
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
    topx = table->subtables[boty].next;

    table->subtables[boty].next = y;
    table->subtables[x].next = topx;

    return;

} /* end of ddDissolveGroup */


/**Function********************************************************************

  Synopsis    [Pretends to check two variables for aggregation.]

  Description [Pretends to check two variables for aggregation. Always
  returns 0.]

  SideEffects [None]

******************************************************************************/
static int
ddNoCheck(
  DdManager * table,
  int  x,
  int  y)
{
    return(0);

} /* end of ddNoCheck */


/**Function********************************************************************

  Synopsis    [Checks two variables for aggregation.]

  Description [Checks two variables for aggregation. The check is based
  on the second difference of the number of nodes as a function of the
  layer. If the second difference is lower than a given threshold
  (typically negative) then the two variables should be aggregated.
  Returns 1 if the two variables pass the test; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddSecDiffCheck(
  DdManager * table,
  int  x,
  int  y)
{
    double Nx,Nx_1;
    double Sx;
    double threshold;
    int    xindex,yindex;

    if (x==0) return(0);

#ifdef DD_STATS
    secdiffcalls++;
#endif
    Nx = (double) table->subtables[x].keys;
    Nx_1 = (double) table->subtables[x-1].keys;
    Sx = (table->subtables[y].keys/Nx) - (Nx/Nx_1);

    threshold = table->recomb / 100.0;
    if (Sx < threshold) {
1888 1889 1890
        xindex = table->invperm[x];
        yindex = table->invperm[y];
        if (cuddTestInteract(table,xindex,yindex)) {
Alan Mishchenko committed
1891
#if defined(DD_DEBUG) && defined(DD_VERBOSE)
1892 1893 1894
            (void) fprintf(table->out,
                           "Second difference for %d = %g Pos(%d)\n",
                           table->invperm[x],Sx,x);
Alan Mishchenko committed
1895 1896
#endif
#ifdef DD_STATS
1897
            secdiff++;
Alan Mishchenko committed
1898
#endif
1899 1900
            return(1);
        } else {
Alan Mishchenko committed
1901
#ifdef DD_STATS
1902
            secdiffmisfire++;
Alan Mishchenko committed
1903
#endif
1904 1905
            return(0);
        }
Alan Mishchenko committed
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930

    }
    return(0);

} /* end of ddSecDiffCheck */


/**Function********************************************************************

  Synopsis    [Checks for extended symmetry of x and y.]

  Description [Checks for extended symmetry of x and y. Returns 1 in
  case of extended symmetry; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
ddExtSymmCheck(
  DdManager * table,
  int  x,
  int  y)
{
    DdNode *f,*f0,*f1,*f01,*f00,*f11,*f10;
    DdNode *one;
1931 1932 1933 1934 1935 1936 1937 1938
    unsigned comple;    /* f0 is complemented */
    int notproj;        /* f is not a projection function */
    int arccount;       /* number of arcs from layer x to layer y */
    int TotalRefCount;  /* total reference count of layer y minus 1 */
    int counter;        /* number of nodes of layer x that are allowed */
                        /* to violate extended symmetry conditions */
    int arccounter;     /* number of arcs into layer y that are allowed */
                        /* to come from layers other than x */
Alan Mishchenko committed
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
    int i;
    int xindex;
    int yindex;
    int res;
    int slots;
    DdNodePtr *list;
    DdNode *sentinel = &(table->sentinel);

    xindex = table->invperm[x];
    yindex = table->invperm[y];

    /* If the two variables do not interact, we do not want to merge them. */
    if (!cuddTestInteract(table,xindex,yindex))
1952
        return(0);
Alan Mishchenko committed
1953 1954 1955 1956 1957 1958 1959 1960

#ifdef DD_DEBUG
    /* Checks that x and y do not contain just the projection functions.
    ** With the test on interaction, these test become redundant,
    ** because an isolated projection function does not interact with
    ** any other variable.
    */
    if (table->subtables[x].keys == 1) {
1961
        assert(table->vars[xindex]->ref != 1);
Alan Mishchenko committed
1962 1963
    }
    if (table->subtables[y].keys == 1) {
1964
        assert(table->vars[yindex]->ref != 1);
Alan Mishchenko committed
1965 1966 1967 1968 1969 1970 1971 1972 1973
    }
#endif

#ifdef DD_STATS
    extsymmcalls++;
#endif

    arccount = 0;
    counter = (int) (table->subtables[x].keys *
1974
              (table->symmviolation/100.0) + 0.5);
Alan Mishchenko committed
1975 1976 1977 1978 1979
    one = DD_ONE(table);

    slots = table->subtables[x].slots;
    list = table->subtables[x].nodelist;
    for (i = 0; i < slots; i++) {
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
        f = list[i];
        while (f != sentinel) {
            /* Find f1, f0, f11, f10, f01, f00. */
            f1 = cuddT(f);
            f0 = Cudd_Regular(cuddE(f));
            comple = Cudd_IsComplement(cuddE(f));
            notproj = f1 != one || f0 != one || f->ref != (DdHalfWord) 1;
            if (f1->index == (unsigned) yindex) {
                arccount++;
                f11 = cuddT(f1); f10 = cuddE(f1);
            } else {
                if ((int) f0->index != yindex) {
                    /* If f is an isolated projection function it is
                    ** allowed to bypass layer y.
                    */
                    if (notproj) {
                        if (counter == 0)
                            return(0);
                        counter--; /* f bypasses layer y */
                    }
                }
                f11 = f10 = f1;
            }
            if ((int) f0->index == yindex) {
                arccount++;
                f01 = cuddT(f0); f00 = cuddE(f0);
            } else {
                f01 = f00 = f0;
            }
            if (comple) {
                f01 = Cudd_Not(f01);
                f00 = Cudd_Not(f00);
            }

            /* Unless we are looking at a projection function
            ** without external references except the one from the
            ** table, we insist that f01 == f10 or f11 == f00
Alan Mishchenko committed
2017 2018
            */
            if (notproj) {
2019 2020 2021 2022 2023
                if (f01 != f10 && f11 != f00) {
                    if (counter == 0)
                        return(0);
                    counter--;
                }
Alan Mishchenko committed
2024 2025
            }

2026 2027
            f = f->next;
        } /* while */
Alan Mishchenko committed
2028 2029 2030
    } /* for */

    /* Calculate the total reference counts of y */
2031
    TotalRefCount = -1; /* -1 for projection function */
Alan Mishchenko committed
2032 2033 2034
    slots = table->subtables[y].slots;
    list = table->subtables[y].nodelist;
    for (i = 0; i < slots; i++) {
2035 2036 2037 2038 2039
        f = list[i];
        while (f != sentinel) {
            TotalRefCount += f->ref;
            f = f->next;
        }
Alan Mishchenko committed
2040 2041 2042
    }

    arccounter = (int) (table->subtables[y].keys *
2043
                 (table->arcviolation/100.0) + 0.5);
Alan Mishchenko committed
2044 2045 2046 2047
    res = arccount >= TotalRefCount - arccounter;

#if defined(DD_DEBUG) && defined(DD_VERBOSE)
    if (res) {
2048 2049 2050
        (void) fprintf(table->out,
                       "Found extended symmetry! x = %d\ty = %d\tPos(%d,%d)\n",
                       xindex,yindex,x,y);
Alan Mishchenko committed
2051 2052 2053 2054 2055
    }
#endif

#ifdef DD_STATS
    if (res)
2056
        extsymm++;
Alan Mishchenko committed
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
#endif
    return(res);

} /* end ddExtSymmCheck */


/**Function********************************************************************

  Synopsis    [Checks for grouping of x and y.]

  Description [Checks for grouping of x and y. Returns 1 in
  case of grouping; 0 otherwise. This function is used for lazy sifting.]

  SideEffects [None]

******************************************************************************/
static int
ddVarGroupCheck(
  DdManager * table,
  int x,
  int y)
{
    int xindex = table->invperm[x];
    int yindex = table->invperm[y];

    if (Cudd_bddIsVarToBeUngrouped(table, xindex)) return(0);

    if (Cudd_bddReadPairIndex(table, xindex) == yindex) {
2085 2086 2087 2088 2089 2090 2091 2092
        if (ddIsVarHandled(table, xindex) ||
            ddIsVarHandled(table, yindex)) {
            if (Cudd_bddIsVarToBeGrouped(table, xindex) ||
                Cudd_bddIsVarToBeGrouped(table, yindex) ) {
                if (table->keys - table->isolated <= originalSize) {
                    return(1);
                }
            }
Alan Mishchenko committed
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
        }
    }

    return(0);

} /* end of ddVarGroupCheck */


/**Function********************************************************************

  Synopsis    [Sets a variable to already handled.]

  Description [Sets a variable to already handled. This function is used
  for lazy sifting.]

  SideEffects [none]

  SeeAlso     []

******************************************************************************/
static int
ddSetVarHandled(
  DdManager *dd,
  int index)
{
    if (index >= dd->size || index < 0) return(0);
    dd->subtables[dd->perm[index]].varHandled = 1;
    return(1);

} /* end of ddSetVarHandled */


/**Function********************************************************************

  Synopsis    [Resets a variable to be processed.]

  Description [Resets a variable to be processed. This function is used
  for lazy sifting.]

  SideEffects [none]

  SeeAlso     []

******************************************************************************/
static int
ddResetVarHandled(
  DdManager *dd,
  int index)
{
    if (index >= dd->size || index < 0) return(0);
    dd->subtables[dd->perm[index]].varHandled = 0;
    return(1);

} /* end of ddResetVarHandled */


/**Function********************************************************************

  Synopsis    [Checks whether a variables is already handled.]

  Description [Checks whether a variables is already handled. This
  function is used for lazy sifting.]

  SideEffects [none]

  SeeAlso     []

******************************************************************************/
static int
ddIsVarHandled(
  DdManager *dd,
  int index)
{
    if (index >= dd->size || index < 0) return(-1);
    return dd->subtables[dd->perm[index]].varHandled;

} /* end of ddIsVarHandled */
2170 2171


2172 2173
ABC_NAMESPACE_IMPL_END