cuddGroup.c 69.1 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 108 109 110 111 112 113
#ifdef __cplusplus
extern "C" {
#endif
    typedef int (*DD_CHKFP)(DdManager *, int, int);
#ifdef __cplusplus
}
#endif

Alan Mishchenko committed
114 115 116 117 118
/*---------------------------------------------------------------------------*/
/* Variable declarations                                                     */
/*---------------------------------------------------------------------------*/

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

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

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

142 143 144 145
#ifdef __cplusplus
extern "C" {
#endif

Alan Mishchenko committed
146 147 148 149 150 151
/**AutomaticStart*************************************************************/

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

152
static int ddTreeSiftingAux (DdManager *table, MtrNode *treenode, Cudd_ReorderingType method);
Alan Mishchenko committed
153
#ifdef DD_STATS
154
static int ddCountInternalMtrNodes (DdManager *table, MtrNode *treenode);
Alan Mishchenko committed
155
#endif
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
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
176 177 178

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

179 180 181
#ifdef __cplusplus
}
#endif
Alan Mishchenko committed
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 210 211 212 213 214 215 216 217 218 219 220 221 222 223

/*---------------------------------------------------------------------------*/
/* 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)
224
        return(NULL);
Alan Mishchenko committed
225 226 227 228

    /* If the tree does not exist yet, create it. */
    tree = dd->tree;
    if (tree == NULL) {
229 230 231 232
        dd->tree = tree = Mtr_InitGroupTree(0, dd->size);
        if (tree == NULL)
            return(NULL);
        tree->index = dd->invperm[0];
Alan Mishchenko committed
233 234 235 236 237 238 239 240 241 242
    }

    /* 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)
243
        return(NULL);
Alan Mishchenko committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

    /* 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 */,
276
  Cudd_ReorderingType method /* reordering method for the groups of leaves */)
Alan Mishchenko committed
277 278 279 280 281 282 283 284 285 286 287 288
{
    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) {
289 290
        table->tree = Mtr_InitGroupTree(0,table->size);
        table->tree->index = table->invperm[0];
Alan Mishchenko committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    }
    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)
308 309
        (void) fprintf(table->out,"#:IM_NODES  %8d: group tree nodes\n",
                       ddCountInternalMtrNodes(table,table->tree));
Alan Mishchenko committed
310 311 312 313 314 315 316 317 318 319 320
#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. */
321
    result = ddTreeSiftingAux(table, table->tree, method);
Alan Mishchenko committed
322

323
#ifdef DD_STATS         /* print stats */
Alan Mishchenko committed
324
    if (!tempTree && method == CUDD_REORDER_GROUP_SIFT &&
325 326 327 328
        (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
329 330
    }
    if (!tempTree && method == CUDD_REORDER_GROUP_SIFT &&
331 332 333 334
        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
335 336 337 338
    }
#endif

    if (tempTree)
339
        Cudd_FreeTree(table);
Alan Mishchenko committed
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    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,
364
  Cudd_ReorderingType method)
Alan Mishchenko committed
365 366 367 368 369 370 371 372 373 374 375
{
    MtrNode  *auxnode;
    int res;
    Cudd_AggregationType saveCheck;

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

    auxnode = treenode;
    while (auxnode != NULL) {
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
        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
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    }

    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) {
424 425 426 427 428 429
        if (!(MTR_TEST(auxnode,MTR_TERMINAL))) {
            nodeCount++;
            count = ddCountInternalMtrNodes(table,auxnode->child);
            nodeCount += count;
        }
        auxnode = auxnode->younger;
Alan Mishchenko committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
    }

    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,
456
  Cudd_ReorderingType method)
Alan Mishchenko committed
457 458
{
    int lower;
459
    int upper = -1;
Alan Mishchenko committed
460 461 462 463 464 465
    int result;
    unsigned int initialSize;

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

    if (treenode->flags == MTR_FIXED) {
469
        result = 1;
Alan Mishchenko committed
470 471
    } else {
#ifdef DD_STATS
472
        (void) fprintf(table->out," ");
Alan Mishchenko committed
473
#endif
474 475 476 477
        switch (method) {
        case CUDD_REORDER_RANDOM:
        case CUDD_REORDER_RANDOM_PIVOT:
            result = cuddSwapping(table,lower,upper,method);
Alan Mishchenko committed
478
            break;
479 480 481 482 483 484 485 486 487
        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
488
#ifdef DD_STATS
489 490
                else
                    (void) fprintf(table->out,"\n");
Alan Mishchenko committed
491
#endif
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 519 520 521 522 523 524 525 526 527 528 529 530 531 532
            } 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
533
#ifdef DD_STATS
534
                (void) fprintf(table->out,"\n");
Alan Mishchenko committed
535
#endif
536 537 538 539
                result = cuddWindowReorder(table,lower,upper,
                                           CUDD_REORDER_WINDOW4);
                if (initialSize <= table->keys - table->isolated)
                    break;
Alan Mishchenko committed
540
#ifdef DD_STATS
541 542
                else
                    (void) fprintf(table->out,"\n");
Alan Mishchenko committed
543
#endif
544 545 546 547 548 549 550 551 552
            } 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
553
            break;
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
        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
569
#ifdef DD_STATS
570 571
                else
                    (void) fprintf(table->out,"\n");
Alan Mishchenko committed
572
#endif
573 574 575 576 577 578 579 580 581 582 583 584
            } 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
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 617 618 619 620 621 622 623 624 625 626 627 628 629 630
    }

    /* 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) {
631 632 633
        *lower = table->size;
        *upper = -1;
        return;
Alan Mishchenko committed
634 635 636 637 638 639
    }

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

    if (high >= table->size) {
640 641 642 643 644 645
        /* 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
646
        */
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
        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
663 664
        }
    } else {
665 666
        /* Normal case: All the variables of the group exist. */
        *upper = (unsigned int) high;
Alan Mishchenko committed
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
    }

#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]) {
698
        return((*ptrX) - (*ptrY));
Alan Mishchenko committed
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
    }
#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,
724
  DD_CHKFP checkFunction,
Alan Mishchenko committed
725 726
  int lazyFlag)
{
727 728 729 730 731 732 733 734
    int         *var;
    int         i,j,x,xInit;
    int         nvars;
    int         classes;
    int         result;
    int         *sifted;
    int         merged;
    int         dissolve;
Alan Mishchenko committed
735 736 737
#ifdef DD_STATS
    unsigned    previousSize;
#endif
738
    int         xindex;
Alan Mishchenko committed
739 740 741 742 743 744

    nvars = table->size;

    /* Order variables to sift. */
    entry = NULL;
    sifted = NULL;
Alan Mishchenko committed
745
    var = ABC_ALLOC(int,nvars);
Alan Mishchenko committed
746
    if (var == NULL) {
747 748
        table->errorCode = CUDD_MEMORY_OUT;
        goto ddGroupSiftingOutOfMem;
Alan Mishchenko committed
749
    }
Alan Mishchenko committed
750
    entry = ABC_ALLOC(int,nvars);
Alan Mishchenko committed
751
    if (entry == NULL) {
752 753
        table->errorCode = CUDD_MEMORY_OUT;
        goto ddGroupSiftingOutOfMem;
Alan Mishchenko committed
754
    }
Alan Mishchenko committed
755
    sifted = ABC_ALLOC(int,nvars);
Alan Mishchenko committed
756
    if (sifted == NULL) {
757 758
        table->errorCode = CUDD_MEMORY_OUT;
        goto ddGroupSiftingOutOfMem;
Alan Mishchenko committed
759 760 761 762
    }

    /* Here we consider only one representative for each group. */
    for (i = 0, classes = 0; i < nvars; i++) {
763 764 765 766 767 768 769
        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
770 771 772
    }

    qsort((void *)var,classes,sizeof(int),
773
          (DD_QSFP) ddUniqueCompareGroup);
Alan Mishchenko committed
774 775

    if (lazyFlag) {
776 777 778
        for (i = 0; i < nvars; i ++) {
            ddResetVarHandled(table, i);
        }
Alan Mishchenko committed
779 780 781 782
    }

    /* Now sift. */
    for (i = 0; i < ddMin(table->siftMaxVar,classes); i++) {
783 784 785 786 787
        if (ddTotalNumberSwapping >= table->siftMaxSwap)
            break;
        xindex = var[i];
        if (sifted[xindex] == 1) /* variable already sifted as part of group */
            continue;
Alan Mishchenko committed
788 789
        x = table->perm[xindex]; /* find current level of this variable */

790 791
        if (x < lower || x > upper || table->subtables[x].bindVar == 1)
            continue;
Alan Mishchenko committed
792
#ifdef DD_STATS
793
        previousSize = table->keys - table->isolated;
Alan Mishchenko committed
794 795
#endif
#ifdef DD_DEBUG
796
        /* x is bottom of group */
Alan Mishchenko committed
797 798
        assert((unsigned) x >= table->subtables[x].next);
#endif
799 800 801 802 803 804 805
        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
806
        }
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827
        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
828 829 830
            }
        }

831 832 833 834 835 836 837
        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
838
#ifdef DD_STATS
839 840 841 842 843 844 845 846
            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
847
        } else {
848 849 850 851 852 853 854 855
            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
856
#endif
857
        }
Alan Mishchenko committed
858

859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
        /* 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
877 878 879
        }

#ifdef DD_DEBUG
880
        if (pr > 0) (void) fprintf(table->out,"ddGroupSifting:");
Alan Mishchenko committed
881 882 883 884 885
#endif

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

Alan Mishchenko committed
886 887 888
    ABC_FREE(sifted);
    ABC_FREE(var);
    ABC_FREE(entry);
Alan Mishchenko committed
889 890 891 892

    return(1);

ddGroupSiftingOutOfMem:
893
    if (entry != NULL)  ABC_FREE(entry);
Alan Mishchenko committed
894
    if (var != NULL)    ABC_FREE(var);
895
    if (sifted != NULL) ABC_FREE(sifted);
Alan Mishchenko committed
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928

    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)
929
        gybot = table->subtables[gybot].next;
Alan Mishchenko committed
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960

    /* 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,
961
  DD_CHKFP checkFunction,
Alan Mishchenko committed
962 963 964
  int lazyFlag)
{
    Move *move;
965
    Move *moves;        /* list of moves */
Alan Mishchenko committed
966 967 968 969 970 971 972
    int  initialSize;
    int  result;
    int  y;
    int  topbot;

#ifdef DD_DEBUG
    if (pr > 0) (void) fprintf(table->out,
973
                               "ddGroupSiftingAux from %d to %d\n",xLow,xHigh);
Alan Mishchenko committed
974 975 976 977 978 979
    assert((unsigned) x >= table->subtables[x].next); /* x is bottom of group */
#endif

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

980
    originalSize = initialSize;         /* for lazy sifting */
Alan Mishchenko committed
981 982 983 984 985

    /* If we have a singleton, we check for aggregation in both
    ** directions before we sift.
    */
    if ((unsigned) x == table->subtables[x].next) {
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
        /* 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
1012 1013 1014 1015 1016 1017 1018
        }
    }

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

    if (x == xLow) { /* Sift down */
#ifdef DD_DEBUG
1023 1024
        /* x must be a singleton */
        assert((unsigned) x == table->subtables[x].next);
Alan Mishchenko committed
1025
#endif
1026
        if (x == xHigh) return(1);      /* just one variable */
Alan Mishchenko committed
1027 1028 1029

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

1032 1033 1034
        /* move backward and stop at best position */
        result = ddGroupSiftingBackward(table,moves,initialSize,
                                        DD_SIFT_DOWN,lazyFlag);
Alan Mishchenko committed
1035
#ifdef DD_DEBUG
1036
        assert(table->keys - table->isolated <= (unsigned) initialSize);
Alan Mishchenko committed
1037 1038 1039 1040 1041
#endif
        if (!result) goto ddGroupSiftingAuxOutOfMem;

    } else if (cuddNextHigh(table,x) > xHigh) { /* Sift up */
#ifdef DD_DEBUG
1042
        /* x is bottom of group */
Alan Mishchenko committed
1043 1044 1045 1046 1047 1048 1049
        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;
1050
        /* at this point x == xLow, unless early term */
Alan Mishchenko committed
1051

1052 1053 1054
        /* move backward and stop at best position */
        result = ddGroupSiftingBackward(table,moves,initialSize,
                                        DD_SIFT_UP,lazyFlag);
Alan Mishchenko committed
1055
#ifdef DD_DEBUG
1056
        assert(table->keys - table->isolated <= (unsigned) initialSize);
Alan Mishchenko committed
1057 1058 1059 1060 1061 1062
#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;
1063
        /* at this point x == xHigh, unless early term */
Alan Mishchenko committed
1064 1065

        /* Find top of group */
1066 1067 1068 1069 1070
        if (moves) {
            x = moves->y;
        }
        while ((unsigned) x < table->subtables[x].next)
            x = table->subtables[x].next;
Alan Mishchenko committed
1071 1072 1073 1074 1075 1076 1077 1078 1079
        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;

1080 1081 1082
        /* move backward and stop at best position */
        result = ddGroupSiftingBackward(table,moves,initialSize,
                                        DD_SIFT_UP,lazyFlag);
Alan Mishchenko committed
1083
#ifdef DD_DEBUG
1084
        assert(table->keys - table->isolated <= (unsigned) initialSize);
Alan Mishchenko committed
1085 1086 1087 1088 1089 1090 1091 1092 1093
#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;
1094
        /* at this point x == xHigh, unless early term */
Alan Mishchenko committed
1095 1096

        if (moves) {
1097 1098 1099 1100
            x = moves->x;
        }
        while ((unsigned) x < table->subtables[x].next)
            x = table->subtables[x].next;
Alan Mishchenko committed
1101 1102 1103 1104 1105 1106 1107 1108
#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;

1109 1110 1111
        /* move backward and stop at best position */
        result = ddGroupSiftingBackward(table,moves,initialSize,
                                        DD_SIFT_DOWN,lazyFlag);
Alan Mishchenko committed
1112
#ifdef DD_DEBUG
1113
        assert(table->keys - table->isolated <= (unsigned) initialSize);
Alan Mishchenko committed
1114 1115 1116 1117 1118 1119
#endif
        if (!result) goto ddGroupSiftingAuxOutOfMem;
    }

    while (moves != NULL) {
        move = moves->next;
1120
        cuddDeallocMove(table, moves);
Alan Mishchenko committed
1121 1122 1123 1124 1125 1126 1127 1128
        moves = move;
    }

    return(1);

ddGroupSiftingAuxOutOfMem:
    while (moves != NULL) {
        move = moves->next;
1129
        cuddDeallocMove(table, moves);
Alan Mishchenko committed
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
        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,
1158
  DD_CHKFP checkFunction,
Alan Mishchenko committed
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
  Move ** moves)
{
    Move *move;
    int  x;
    int  size;
    int  i;
    int  gxtop,gybot;
    int  limitSize;
    int  xindex, yindex;
    int  zindex;
    int  z;
    int  isolated;
1171
    int  L;     /* lower bound on DD size */
Alan Mishchenko committed
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
#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)
1190
        gybot = table->subtables[gybot].next;
Alan Mishchenko committed
1191
    for (z = xLow + 1; z <= gybot; z++) {
1192 1193 1194 1195 1196
        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
1197 1198 1199 1200 1201
    }

    x = cuddNextLow(table,y);
    while (x >= xLow && L <= limitSize) {
#ifdef DD_DEBUG
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
        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
1217 1218 1219 1220
        }
#endif
        gxtop = table->subtables[x].next;
        if (checkFunction(table,x,y)) {
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
            /* 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
1235
        } else if (table->subtables[x].next == (unsigned) x &&
1236
                   table->subtables[y].next == (unsigned) y) {
Alan Mishchenko committed
1237
            /* x and y are self groups */
1238
            xindex = table->invperm[x];
Alan Mishchenko committed
1239 1240 1241 1242 1243 1244
            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;
1245 1246 1247 1248 1249
            /* Update the lower bound. */
            if (cuddTestInteract(table,xindex,yindex)) {
                isolated = table->vars[xindex]->ref == 1;
                L += table->subtables[y].keys - isolated;
            }
Alan Mishchenko committed
1250 1251 1252 1253
            move = (Move *)cuddDynamicAllocNode(table);
            if (move == NULL) goto ddGroupSiftingUpOutOfMem;
            move->x = x;
            move->y = y;
1254
            move->flags = MTR_DEFAULT;
Alan Mishchenko committed
1255 1256 1257 1258 1259
            move->size = size;
            move->next = *moves;
            *moves = move;

#ifdef DD_DEBUG
1260 1261
            if (pr > 0) (void) fprintf(table->out,
                                       "ddGroupSiftingUp (2 single groups):\n");
Alan Mishchenko committed
1262 1263
#endif
            if ((double) size > (double) limitSize * table->maxGrowth)
1264
                return(1);
Alan Mishchenko committed
1265 1266 1267
            if (size < limitSize) limitSize = size;
        } else { /* Group move */
            size = ddGroupMove(table,x,y,moves);
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
            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
1279
            if ((double) size > (double) limitSize * table->maxGrowth)
1280
                return(1);
Alan Mishchenko committed
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
            if (size < limitSize) limitSize = size;
        }
        y = gxtop;
        x = cuddNextLow(table,y);
    }

    return(1);

ddGroupSiftingUpOutOfMem:
    while (*moves != NULL) {
        move = (*moves)->next;
1292
        cuddDeallocMove(table, *moves);
Alan Mishchenko committed
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
        *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,
1316
  DD_CHKFP checkFunction,
Alan Mishchenko committed
1317 1318 1319 1320 1321 1322 1323
  Move ** moves)
{
    Move *move;
    int  y;
    int  size;
    int  limitSize;
    int  gxtop,gybot;
1324
    int  R;     /* upper bound on node decrease */
Alan Mishchenko committed
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    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 {
1341 1342 1343 1344 1345
        if (table->subtables[y].keys != 1) {
            allVars = 0;
            break;
        }
        y = table->subtables[y].next;
Alan Mishchenko committed
1346 1347
    } while (table->subtables[y].next != (unsigned) x);
    if (allVars)
1348 1349
        return(1);

Alan Mishchenko committed
1350 1351 1352 1353 1354 1355
    /* 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--) {
1356 1357 1358 1359 1360
        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
1361 1362 1363 1364 1365
    }

    y = cuddNextHigh(table,x);
    while (y <= xHigh && size - R < limitSize) {
#ifdef DD_DEBUG
1366 1367 1368 1369 1370 1371 1372 1373
        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
1374
        }
1375
        assert(R >= checkR);
Alan Mishchenko committed
1376
#endif
1377
        /* Find bottom of y group. */
Alan Mishchenko committed
1378 1379 1380 1381 1382
        gybot = table->subtables[y].next;
        while (table->subtables[gybot].next != (unsigned) y)
            gybot = table->subtables[gybot].next;

        if (checkFunction(table,x,y)) {
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
            /* 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
1395
        } else if (table->subtables[x].next == (unsigned) x &&
1396
                   table->subtables[y].next == (unsigned) y) {
Alan Mishchenko committed
1397
            /* x and y are self groups */
1398 1399 1400 1401 1402 1403
            /* 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
1404 1405 1406 1407 1408 1409 1410
            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;

1411
            /* Record move. */
Alan Mishchenko committed
1412 1413 1414 1415
            move = (Move *) cuddDynamicAllocNode(table);
            if (move == NULL) goto ddGroupSiftingDownOutOfMem;
            move->x = x;
            move->y = y;
1416
            move->flags = MTR_DEFAULT;
Alan Mishchenko committed
1417 1418 1419 1420 1421 1422
            move->size = size;
            move->next = *moves;
            *moves = move;

#ifdef DD_DEBUG
            if (pr > 0) (void) fprintf(table->out,
1423
                                       "ddGroupSiftingDown (2 single groups):\n");
Alan Mishchenko committed
1424 1425 1426 1427 1428 1429 1430 1431
#endif
            if ((double) size > (double) limitSize * table->maxGrowth)
                return(1);
            if (size < limitSize) limitSize = size;

            x = y;
            y = cuddNextHigh(table,x);
        } else { /* Group move */
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
            /* 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
1443 1444 1445
            size = ddGroupMove(table,x,y,moves);
            if (size == 0) goto ddGroupSiftingDownOutOfMem;
            if ((double) size > (double) limitSize * table->maxGrowth)
1446
                return(1);
Alan Mishchenko committed
1447 1448
            if (size < limitSize) limitSize = size;

1449 1450 1451 1452 1453 1454 1455 1456 1457
            /* 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
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
        }
        x = gybot;
        y = cuddNextHigh(table,x);
    }

    return(1);

ddGroupSiftingDownOutOfMem:
    while (*moves != NULL) {
        move = (*moves)->next;
1468
        cuddDeallocMove(table, *moves);
Alan Mishchenko committed
1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
        *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;
1497
    int  swapx = -1,swapy = -1;
Alan Mishchenko committed
1498 1499 1500 1501
#if defined(DD_DEBUG) && defined(DD_VERBOSE)
    int  initialSize,bestSize;
#endif

1502
#ifdef DD_DEBUG
Alan Mishchenko committed
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524
    /* 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)
1525 1526
            if (size < bestSize)
                bestSize = size;
Alan Mishchenko committed
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
#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))
1537
        (void) fprintf(table->out,"Missed local minimum: initialSize:%d  bestSize:%d  finalSize:%d\n",initialSize,bestSize,size);
Alan Mishchenko committed
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
#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;
1575
        cuddDeallocMove(table, *moves);
Alan Mishchenko committed
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
        *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;


1603
#ifdef DD_DEBUG
Alan Mishchenko committed
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 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
    /* 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,
1672
  int  upFlag,
Alan Mishchenko committed
1673 1674 1675 1676
  int  lazyFlag)
{
    Move *move;
    int  res;
1677
    Move *end_move = NULL;
Alan Mishchenko committed
1678
    int diff, tmp_diff;
1679 1680
    int index;
    unsigned int pairlev;
Alan Mishchenko committed
1681 1682

    if (lazyFlag) {
1683
        end_move = NULL;
Alan Mishchenko committed
1684

1685
        /* Find the minimum size, and the earliest position at which it
Alan Mishchenko committed
1686 1687
        ** was achieved. */
        for (move = moves; move != NULL; move = move->next) {
1688 1689 1690 1691 1692
            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
1693 1694
            }
        }
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719

        /* 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
1720 1721
        }
    } else {
1722 1723 1724 1725 1726 1727
        /* Find the minimum size. */
        for (move = moves; move != NULL; move = move->next) {
            if (move->size < size) {
                size = move->size;
            }
        }
Alan Mishchenko committed
1728 1729 1730 1731 1732 1733
    }

    /* 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) {
1734 1735 1736 1737 1738
        if (lazyFlag) {
            if (move == end_move) return(1);
        } else {
            if (move->size == size) return(1);
        }
Alan Mishchenko committed
1739
        if ((table->subtables[move->x].next == move->x) &&
1740
        (table->subtables[move->y].next == move->y)) {
Alan Mishchenko committed
1741 1742 1743 1744 1745 1746 1747 1748
            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 */
1749 1750 1751 1752 1753 1754
            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
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789
        }

    }

    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) {
1790 1791 1792
        for (i = low; i < high; i++)
            table->subtables[i].next = i+1;
        table->subtables[high].next = low;
Alan Mishchenko committed
1793 1794 1795 1796 1797 1798 1799 1800
    }

    /* 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 {
1801 1802 1803 1804 1805
        auxnode->index = newindex;
        if (auxnode->parent == NULL ||
                (int) auxnode->parent->index != saveindex)
            break;
        auxnode = auxnode->parent;
Alan Mishchenko committed
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
    } 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)
1834 1835
        boty = table->subtables[boty].next;

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

    }
    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;
1945 1946 1947 1948 1949 1950 1951 1952
    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
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
    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))
1966
        return(0);
Alan Mishchenko committed
1967 1968 1969 1970 1971 1972 1973 1974

#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) {
1975
        assert(table->vars[xindex]->ref != 1);
Alan Mishchenko committed
1976 1977
    }
    if (table->subtables[y].keys == 1) {
1978
        assert(table->vars[yindex]->ref != 1);
Alan Mishchenko committed
1979 1980 1981 1982 1983 1984 1985 1986 1987
    }
#endif

#ifdef DD_STATS
    extsymmcalls++;
#endif

    arccount = 0;
    counter = (int) (table->subtables[x].keys *
1988
              (table->symmviolation/100.0) + 0.5);
Alan Mishchenko committed
1989 1990 1991 1992 1993
    one = DD_ONE(table);

    slots = table->subtables[x].slots;
    list = table->subtables[x].nodelist;
    for (i = 0; i < slots; i++) {
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
        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
2031 2032
            */
            if (notproj) {
2033 2034 2035 2036 2037
                if (f01 != f10 && f11 != f00) {
                    if (counter == 0)
                        return(0);
                    counter--;
                }
Alan Mishchenko committed
2038 2039
            }

2040 2041
            f = f->next;
        } /* while */
Alan Mishchenko committed
2042 2043 2044
    } /* for */

    /* Calculate the total reference counts of y */
2045
    TotalRefCount = -1; /* -1 for projection function */
Alan Mishchenko committed
2046 2047 2048
    slots = table->subtables[y].slots;
    list = table->subtables[y].nodelist;
    for (i = 0; i < slots; i++) {
2049 2050 2051 2052 2053
        f = list[i];
        while (f != sentinel) {
            TotalRefCount += f->ref;
            f = f->next;
        }
Alan Mishchenko committed
2054 2055 2056
    }

    arccounter = (int) (table->subtables[y].keys *
2057
                 (table->arcviolation/100.0) + 0.5);
Alan Mishchenko committed
2058 2059 2060 2061
    res = arccount >= TotalRefCount - arccounter;

#if defined(DD_DEBUG) && defined(DD_VERBOSE)
    if (res) {
2062 2063 2064
        (void) fprintf(table->out,
                       "Found extended symmetry! x = %d\ty = %d\tPos(%d,%d)\n",
                       xindex,yindex,x,y);
Alan Mishchenko committed
2065 2066 2067 2068 2069
    }
#endif

#ifdef DD_STATS
    if (res)
2070
        extsymm++;
Alan Mishchenko committed
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098
#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) {
2099 2100 2101 2102 2103 2104 2105 2106
        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
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 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
        }
    }

    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 */
2184 2185


2186 2187
ABC_NAMESPACE_IMPL_END