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

  FileName    [cuddUtil.c]

  PackageName [cudd]

  Synopsis    [Utility functions.]

  Description [External procedures included in this module:
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 42 43 44 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
                <ul>
                <li> Cudd_PrintMinterm()
                <li> Cudd_bddPrintCover()
                <li> Cudd_PrintDebug()
                <li> Cudd_DagSize()
                <li> Cudd_EstimateCofactor()
                <li> Cudd_EstimateCofactorSimple()
                <li> Cudd_SharingSize()
                <li> Cudd_CountMinterm()
                <li> Cudd_EpdCountMinterm()
                <li> Cudd_CountPath()
                <li> Cudd_CountPathsToNonZero()
                <li> Cudd_Support()
                <li> Cudd_SupportIndex()
                <li> Cudd_SupportSize()
                <li> Cudd_VectorSupport()
                <li> Cudd_VectorSupportIndex()
                <li> Cudd_VectorSupportSize()
                <li> Cudd_ClassifySupport()
                <li> Cudd_CountLeaves()
                <li> Cudd_bddPickOneCube()
                <li> Cudd_bddPickOneMinterm()
                <li> Cudd_bddPickArbitraryMinterms()
                <li> Cudd_SubsetWithMaskVars()
                <li> Cudd_FirstCube()
                <li> Cudd_NextCube()
                <li> Cudd_bddComputeCube()
                <li> Cudd_addComputeCube()
                <li> Cudd_FirstNode()
                <li> Cudd_NextNode()
                <li> Cudd_GenFree()
                <li> Cudd_IsGenEmpty()
                <li> Cudd_IndicesToCube()
                <li> Cudd_PrintVersion()
                <li> Cudd_AverageDistance()
                <li> Cudd_Random()
                <li> Cudd_Srandom()
                <li> Cudd_Density()
                </ul>
        Internal procedures included in this module:
                <ul>
                <li> cuddP()
                <li> cuddStCountfree()
                <li> cuddCollectNodes()
                <li> cuddNodeArray()
                </ul>
        Static procedures included in this module:
                <ul>
                <li> dp2()
                <li> ddPrintMintermAux()
                <li> ddDagInt()
                <li> ddCountMintermAux()
                <li> ddEpdCountMintermAux()
                <li> ddCountPathAux()
                <li> ddSupportStep()
                <li> ddClearFlag()
                <li> ddLeavesInt()
                <li> ddPickArbitraryMinterms()
                <li> ddPickRepresentativeCube()
                <li> ddEpdFree()
                </ul>]
Alan Mishchenko committed
71 72 73

  Author      [Fabio Somenzi]

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
  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
105 106 107

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

108
#include "misc/util/util_hack.h"
Alan Mishchenko committed
109 110
#include "cuddInt.h"

111 112 113
ABC_NAMESPACE_IMPL_START


114

Alan Mishchenko committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
/*---------------------------------------------------------------------------*/
/* Constant declarations                                                     */
/*---------------------------------------------------------------------------*/

/* Random generator constants. */
#define MODULUS1 2147483563
#define LEQA1 40014
#define LEQQ1 53668
#define LEQR1 12211
#define MODULUS2 2147483399
#define LEQA2 40692
#define LEQQ2 52774
#define LEQR2 3791
#define STAB_SIZE 64
#define STAB_DIV (1 + (MODULUS1 - 1) / STAB_SIZE)

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

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


/*---------------------------------------------------------------------------*/
/* Variable declarations                                                     */
/*---------------------------------------------------------------------------*/

#ifndef lint
145
static char rcsid[] DD_UNUSED = "$Id: cuddUtil.c,v 1.81 2009/03/08 02:49:02 fabio Exp $";
Alan Mishchenko committed
146 147
#endif

148
static  DdNode  *background, *zero;
Alan Mishchenko committed
149

150 151 152 153
static  long cuddRand = 0;
static  long cuddRand2;
static  long shuffleSelect;
static  long shuffleTable[STAB_SIZE];
Alan Mishchenko committed
154 155 156 157 158

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

159 160 161 162 163
#define bang(f) ((Cudd_IsComplement(f)) ? '!' : ' ')

#ifdef __cplusplus
extern "C" {
#endif
Alan Mishchenko committed
164 165 166 167 168 169 170

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

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

171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
static int dp2 (DdManager *dd, DdNode *f, st_table *t);
static void ddPrintMintermAux (DdManager *dd, DdNode *node, int *list);
static int ddDagInt (DdNode *n);
static int cuddNodeArrayRecur (DdNode *f, DdNodePtr *table, int index);
static int cuddEstimateCofactor (DdManager *dd, st_table *table, DdNode * node, int i, int phase, DdNode ** ptr);
static DdNode * cuddUniqueLookup (DdManager * unique, int  index, DdNode * T, DdNode * E);
static int cuddEstimateCofactorSimple (DdNode * node, int i);
static double ddCountMintermAux (DdNode *node, double max, DdHashTable *table);
static int ddEpdCountMintermAux (DdNode *node, EpDouble *max, EpDouble *epd, st_table *table);
static double ddCountPathAux (DdNode *node, st_table *table);
static double ddCountPathsToNonZero (DdNode * N, st_table * table);
static void ddSupportStep (DdNode *f, int *support);
static void ddClearFlag (DdNode *f);
static int ddLeavesInt (DdNode *n);
static int ddPickArbitraryMinterms (DdManager *dd, DdNode *node, int nvars, int nminterms, char **string);
static int ddPickRepresentativeCube (DdManager *dd, DdNode *node, double *weight, char *string);
static enum st_retval ddEpdFree (char * key, char * value, char * arg);
Alan Mishchenko committed
188 189 190

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

191 192 193
#ifdef __cplusplus
}
#endif
Alan Mishchenko committed
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

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


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

  Synopsis    [Prints a disjoint sum of products.]

  Description [Prints a disjoint sum of product cover for the function
  rooted at node. Each product corresponds to a path from node to a
  leaf node different from the logical zero, and different from the
  background value. Uses the package default output file.  Returns 1
  if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_PrintDebug Cudd_bddPrintCover]

******************************************************************************/
int
Cudd_PrintMinterm(
  DdManager * manager,
  DdNode * node)
{
220
    int         i, *list;
Alan Mishchenko committed
221 222 223

    background = manager->background;
    zero = Cudd_Not(manager->one);
Alan Mishchenko committed
224
    list = ABC_ALLOC(int,manager->size);
Alan Mishchenko committed
225
    if (list == NULL) {
226 227
        manager->errorCode = CUDD_MEMORY_OUT;
        return(0);
Alan Mishchenko committed
228 229 230
    }
    for (i = 0; i < manager->size; i++) list[i] = 2;
    ddPrintMintermAux(manager,node,list);
Alan Mishchenko committed
231
    ABC_FREE(list);
Alan Mishchenko committed
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 262 263 264
    return(1);

} /* end of Cudd_PrintMinterm */


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

  Synopsis    [Prints a sum of prime implicants of a BDD.]

  Description [Prints a sum of product cover for an incompletely
  specified function given by a lower bound and an upper bound.  Each
  product is a prime implicant obtained by expanding the product
  corresponding to a path from node to the constant one.  Uses the
  package default output file.  Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_PrintMinterm]

******************************************************************************/
int
Cudd_bddPrintCover(
  DdManager *dd,
  DdNode *l,
  DdNode *u)
{
    int *array;
    int q, result;
    DdNode *lb;
#ifdef DD_DEBUG
    DdNode *cover;
#endif

Alan Mishchenko committed
265
    array = ABC_ALLOC(int, Cudd_ReadSize(dd));
Alan Mishchenko committed
266 267 268 269 270 271 272 273
    if (array == NULL) return(0);
    lb = l;
    cuddRef(lb);
#ifdef DD_DEBUG
    cover = Cudd_ReadLogicZero(dd);
    cuddRef(cover);
#endif
    while (lb != Cudd_ReadLogicZero(dd)) {
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
        DdNode *implicant, *prime, *tmp;
        int length;
        implicant = Cudd_LargestCube(dd,lb,&length);
        if (implicant == NULL) {
            Cudd_RecursiveDeref(dd,lb);
            ABC_FREE(array);
            return(0);
        }
        cuddRef(implicant);
        prime = Cudd_bddMakePrime(dd,implicant,u);
        if (prime == NULL) {
            Cudd_RecursiveDeref(dd,lb);
            Cudd_RecursiveDeref(dd,implicant);
            ABC_FREE(array);
            return(0);
        }
        cuddRef(prime);
Alan Mishchenko committed
291
        Cudd_RecursiveDeref(dd,implicant);
292 293 294 295 296 297 298 299
        tmp = Cudd_bddAnd(dd,lb,Cudd_Not(prime));
        if (tmp == NULL) {
            Cudd_RecursiveDeref(dd,lb);
            Cudd_RecursiveDeref(dd,prime);
            ABC_FREE(array);
            return(0);
        }
        cuddRef(tmp);
Alan Mishchenko committed
300
        Cudd_RecursiveDeref(dd,lb);
301 302 303 304 305 306 307
        lb = tmp;
        result = Cudd_BddToCubeArray(dd,prime,array);
        if (result == 0) {
            Cudd_RecursiveDeref(dd,lb);
            Cudd_RecursiveDeref(dd,prime);
            ABC_FREE(array);
            return(0);
Alan Mishchenko committed
308
        }
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        for (q = 0; q < dd->size; q++) {
            switch (array[q]) {
            case 0:
                (void) fprintf(dd->out, "0");
                break;
            case 1:
                (void) fprintf(dd->out, "1");
                break;
            case 2:
                (void) fprintf(dd->out, "-");
                break;
            default:
                (void) fprintf(dd->out, "?");
            }
        }
        (void) fprintf(dd->out, " 1\n");
Alan Mishchenko committed
325
#ifdef DD_DEBUG
326 327 328 329 330 331 332 333 334
        tmp = Cudd_bddOr(dd,prime,cover);
        if (tmp == NULL) {
            Cudd_RecursiveDeref(dd,cover);
            Cudd_RecursiveDeref(dd,lb);
            Cudd_RecursiveDeref(dd,prime);
            ABC_FREE(array);
            return(0);
        }
        cuddRef(tmp);
Alan Mishchenko committed
335
        Cudd_RecursiveDeref(dd,cover);
336
        cover = tmp;
Alan Mishchenko committed
337
#endif
338
        Cudd_RecursiveDeref(dd,prime);
Alan Mishchenko committed
339 340 341
    }
    (void) fprintf(dd->out, "\n");
    Cudd_RecursiveDeref(dd,lb);
Alan Mishchenko committed
342
    ABC_FREE(array);
Alan Mishchenko committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
#ifdef DD_DEBUG
    if (!Cudd_bddLeq(dd,cover,u) || !Cudd_bddLeq(dd,l,cover)) {
        Cudd_RecursiveDeref(dd,cover);
        return(0);
    }
    Cudd_RecursiveDeref(dd,cover);
#endif
    return(1);

} /* end of Cudd_bddPrintCover */


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

  Synopsis    [Prints to the standard output a DD and its statistics.]

  Description [Prints to the standard output a DD and its statistics.
  The statistics include the number of nodes, the number of leaves, and
  the number of minterms. (The number of minterms is the number of
  assignments to the variables that cause the function to be different
  from the logical zero (for BDDs) and from the background value (for
  ADDs.) The statistics are printed if pr &gt; 0. Specifically:
  <ul>
  <li> pr = 0 : prints nothing
  <li> pr = 1 : prints counts of nodes and minterms
  <li> pr = 2 : prints counts + disjoint sum of product
  <li> pr = 3 : prints counts + list of nodes
  <li> pr &gt; 3 : prints counts + disjoint sum of product + list of nodes
  </ul>
  For the purpose of counting the number of minterms, the function is
  supposed to depend on n variables. Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_DagSize Cudd_CountLeaves Cudd_CountMinterm
  Cudd_PrintMinterm]

******************************************************************************/
int
Cudd_PrintDebug(
  DdManager * dd,
  DdNode * f,
  int  n,
  int  pr)
{
    DdNode *azero, *bzero;
389 390
    int    nodes;
    int    leaves;
Alan Mishchenko committed
391 392 393 394
    double minterms;
    int    retval = 1;

    if (f == NULL) {
395 396 397
        (void) fprintf(dd->out,": is the NULL DD\n");
        (void) fflush(dd->out);
        return(0);
Alan Mishchenko committed
398 399 400 401 402 403 404 405 406
    }
    azero = DD_ZERO(dd);
    bzero = Cudd_Not(DD_ONE(dd));
    if ((f == azero || f == bzero) && pr > 0){
       (void) fprintf(dd->out,": is the zero DD\n");
       (void) fflush(dd->out);
       return(1);
    }
    if (pr > 0) {
407 408 409 410 411 412 413 414
        nodes = Cudd_DagSize(f);
        if (nodes == CUDD_OUT_OF_MEM) retval = 0;
        leaves = Cudd_CountLeaves(f);
        if (leaves == CUDD_OUT_OF_MEM) retval = 0;
        minterms = Cudd_CountMinterm(dd, f, n);
        if (minterms == (double)CUDD_OUT_OF_MEM) retval = 0;
        (void) fprintf(dd->out,": %d nodes %d leaves %g minterms\n",
                       nodes, leaves, minterms);
Alan Mishchenko committed
415
        if (pr > 2) {
416 417 418 419 420 421
            if (!cuddP(dd, f)) retval = 0;
        }
        if (pr == 2 || pr > 3) {
            if (!Cudd_PrintMinterm(dd,f)) retval = 0;
            (void) fprintf(dd->out,"\n");
        }
Alan Mishchenko committed
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
        (void) fflush(dd->out);
    }
    return(retval);

} /* end of Cudd_PrintDebug */


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

  Synopsis    [Counts the number of nodes in a DD.]

  Description [Counts the number of nodes in a DD. Returns the number
  of nodes in the graph rooted at node.]

  SideEffects [None]

  SeeAlso     [Cudd_SharingSize Cudd_PrintDebug]

******************************************************************************/
int
Cudd_DagSize(
  DdNode * node)
{
445
    int i;
Alan Mishchenko committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466

    i = ddDagInt(Cudd_Regular(node));
    ddClearFlag(Cudd_Regular(node));

    return(i);

} /* end of Cudd_DagSize */


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

  Synopsis    [Estimates the number of nodes in a cofactor of a DD.]

  Description [Estimates the number of nodes in a cofactor of a DD.
  Returns an estimate of the number of nodes in a cofactor of
  the graph rooted at node with respect to the variable whose index is i.
  In case of failure, returns CUDD_OUT_OF_MEM.
  This function uses a refinement of the algorithm of Cabodi et al.
  (ICCAD96). The refinement allows the procedure to account for part
  of the recombination that may occur in the part of the cofactor above
  the cofactoring variable. This procedure does no create any new node.
467
  It does keep a small table of results; therefore it may run out of memory.
Alan Mishchenko committed
468 469 470 471 472 473 474 475 476 477 478 479
  If this is a concern, one should use Cudd_EstimateCofactorSimple, which
  is faster, does not allocate any memory, but is less accurate.]

  SideEffects [None]

  SeeAlso     [Cudd_DagSize Cudd_EstimateCofactorSimple]

******************************************************************************/
int
Cudd_EstimateCofactor(
  DdManager *dd /* manager */,
  DdNode * f    /* function */,
480 481
  int i         /* index of variable */,
  int phase     /* 1: positive; 0: negative */
Alan Mishchenko committed
482 483
  )
{
484
    int val;
Alan Mishchenko committed
485 486 487
    DdNode *ptr;
    st_table *table;

488
    table = st_init_table(st_ptrcmp,st_ptrhash);
Alan Mishchenko committed
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 519 520
    if (table == NULL) return(CUDD_OUT_OF_MEM);
    val = cuddEstimateCofactor(dd,table,Cudd_Regular(f),i,phase,&ptr);
    ddClearFlag(Cudd_Regular(f));
    st_free_table(table);

    return(val);

} /* end of Cudd_EstimateCofactor */


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

  Synopsis    [Estimates the number of nodes in a cofactor of a DD.]

  Description [Estimates the number of nodes in a cofactor of a DD.
  Returns an estimate of the number of nodes in the positive cofactor of
  the graph rooted at node with respect to the variable whose index is i.
  This procedure implements with minor changes the algorithm of Cabodi et al.
  (ICCAD96). It does not allocate any memory, it does not change the
  state of the manager, and it is fast. However, it has been observed to
  overestimate the size of the cofactor by as much as a factor of 2.]

  SideEffects [None]

  SeeAlso     [Cudd_DagSize]

******************************************************************************/
int
Cudd_EstimateCofactorSimple(
  DdNode * node,
  int i)
{
521
    int val;
Alan Mishchenko committed
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547

    val = cuddEstimateCofactorSimple(Cudd_Regular(node),i);
    ddClearFlag(Cudd_Regular(node));

    return(val);

} /* end of Cudd_EstimateCofactorSimple */


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

  Synopsis    [Counts the number of nodes in an array of DDs.]

  Description [Counts the number of nodes in an array of DDs. Shared
  nodes are counted only once.  Returns the total number of nodes.]

  SideEffects [None]

  SeeAlso     [Cudd_DagSize]

******************************************************************************/
int
Cudd_SharingSize(
  DdNode ** nodeArray,
  int  n)
{
548
    int i,j;
Alan Mishchenko committed
549 550 551

    i = 0;
    for (j = 0; j < n; j++) {
552
        i += ddDagInt(Cudd_Regular(nodeArray[j]));
Alan Mishchenko committed
553 554
    }
    for (j = 0; j < n; j++) {
555
        ddClearFlag(Cudd_Regular(nodeArray[j]));
Alan Mishchenko committed
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
    }
    return(i);

} /* end of Cudd_SharingSize */


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

  Synopsis    [Counts the number of minterms of a DD.]

  Description [Counts the number of minterms of a DD. The function is
  assumed to depend on nvars variables. The minterm count is
  represented as a double, to allow for a larger number of variables.
  Returns the number of minterms of the function rooted at node if
  successful; (double) CUDD_OUT_OF_MEM otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_PrintDebug Cudd_CountPath]

******************************************************************************/
double
Cudd_CountMinterm(
  DdManager * manager,
  DdNode * node,
  int  nvars)
{
583 584 585
    double      max;
    DdHashTable *table;
    double      res;
Alan Mishchenko committed
586 587 588 589
    CUDD_VALUE_TYPE epsilon;

    background = manager->background;
    zero = Cudd_Not(manager->one);
590

Alan Mishchenko committed
591 592 593
    max = pow(2.0,(double)nvars);
    table = cuddHashTableInit(manager,1,2);
    if (table == NULL) {
594
        return((double)CUDD_OUT_OF_MEM);
Alan Mishchenko committed
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
    }
    epsilon = Cudd_ReadEpsilon(manager);
    Cudd_SetEpsilon(manager,(CUDD_VALUE_TYPE)0.0);
    res = ddCountMintermAux(node,max,table);
    cuddHashTableQuit(table);
    Cudd_SetEpsilon(manager,epsilon);

    return(res);

} /* end of Cudd_CountMinterm */


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

  Synopsis    [Counts the number of paths of a DD.]

  Description [Counts the number of paths of a DD.  Paths to all
  terminal nodes are counted. The path count is represented as a
  double, to allow for a larger number of variables.  Returns the
  number of paths of the function rooted at node if successful;
  (double) CUDD_OUT_OF_MEM otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_CountMinterm]

******************************************************************************/
double
Cudd_CountPath(
  DdNode * node)
{

    st_table    *table;
628
    double      i;
Alan Mishchenko committed
629

630
    table = st_init_table(st_ptrcmp,st_ptrhash);
Alan Mishchenko committed
631
    if (table == NULL) {
632
        return((double)CUDD_OUT_OF_MEM);
Alan Mishchenko committed
633 634
    }
    i = ddCountPathAux(Cudd_Regular(node),table);
635
    st_foreach(table, cuddStCountfree, NULL);
Alan Mishchenko committed
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
    st_free_table(table);
    return(i);

} /* end of Cudd_CountPath */


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

  Synopsis    [Counts the number of minterms of a DD with extended precision.]

  Description [Counts the number of minterms of a DD with extended precision.
  The function is assumed to depend on nvars variables. The minterm count is
  represented as an EpDouble, to allow any number of variables.
  Returns 0 if successful; CUDD_OUT_OF_MEM otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_PrintDebug Cudd_CountPath]

******************************************************************************/
int
Cudd_EpdCountMinterm(
  DdManager * manager,
  DdNode * node,
  int  nvars,
  EpDouble * epd)
{
    EpDouble    max, tmp;
    st_table    *table;
665
    int         status;
Alan Mishchenko committed
666 667 668

    background = manager->background;
    zero = Cudd_Not(manager->one);
669

Alan Mishchenko committed
670 671 672
    EpdPow2(nvars, &max);
    table = st_init_table(EpdCmp, st_ptrhash);
    if (table == NULL) {
673 674
        EpdMakeZero(epd, 0);
        return(CUDD_OUT_OF_MEM);
Alan Mishchenko committed
675 676
    }
    status = ddEpdCountMintermAux(Cudd_Regular(node),&max,epd,table);
677
    st_foreach(table, ddEpdFree, NULL);
Alan Mishchenko committed
678 679
    st_free_table(table);
    if (status == CUDD_OUT_OF_MEM) {
680 681
        EpdMakeZero(epd, 0);
        return(CUDD_OUT_OF_MEM);
Alan Mishchenko committed
682 683 684 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 710 711
    }
    if (Cudd_IsComplement(node)) {
        EpdSubtract3(&max, epd, &tmp);
        EpdCopy(&tmp, epd);
    }
    return(0);

} /* end of Cudd_EpdCountMinterm */


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

  Synopsis    [Counts the number of paths to a non-zero terminal of a DD.]

  Description [Counts the number of paths to a non-zero terminal of a
  DD.  The path count is
  represented as a double, to allow for a larger number of variables.
  Returns the number of paths of the function rooted at node.]

  SideEffects [None]

  SeeAlso     [Cudd_CountMinterm Cudd_CountPath]

******************************************************************************/
double
Cudd_CountPathsToNonZero(
  DdNode * node)
{

    st_table    *table;
712
    double      i;
Alan Mishchenko committed
713

714
    table = st_init_table(st_ptrcmp,st_ptrhash);
Alan Mishchenko committed
715
    if (table == NULL) {
716
        return((double)CUDD_OUT_OF_MEM);
Alan Mishchenko committed
717 718
    }
    i = ddCountPathsToNonZero(node,table);
719
    st_foreach(table, cuddStCountfree, NULL);
Alan Mishchenko committed
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
    st_free_table(table);
    return(i);

} /* end of Cudd_CountPathsToNonZero */


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

  Synopsis    [Finds the variables on which a DD depends.]

  Description [Finds the variables on which a DD depends.
  Returns a BDD consisting of the product of the variables if
  successful; NULL otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_VectorSupport Cudd_ClassifySupport]

******************************************************************************/
DdNode *
Cudd_Support(
  DdManager * dd /* manager */,
  DdNode * f /* DD whose support is sought */)
{
744
    int *support;
Alan Mishchenko committed
745
    DdNode *res, *tmp, *var;
746
    int i,j;
Alan Mishchenko committed
747 748 749 750
    int size;

    /* Allocate and initialize support array for ddSupportStep. */
    size = ddMax(dd->size, dd->sizeZ);
Alan Mishchenko committed
751
    support = ABC_ALLOC(int,size);
Alan Mishchenko committed
752
    if (support == NULL) {
753 754
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
Alan Mishchenko committed
755 756
    }
    for (i = 0; i < size; i++) {
757
        support[i] = 0;
Alan Mishchenko committed
758 759 760 761 762 763 764 765
    }

    /* Compute support and clean up markers. */
    ddSupportStep(Cudd_Regular(f),support);
    ddClearFlag(Cudd_Regular(f));

    /* Transform support from array to cube. */
    do {
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
        dd->reordered = 0;
        res = DD_ONE(dd);
        cuddRef(res);
        for (j = size - 1; j >= 0; j--) { /* for each level bottom-up */
            i = (j >= dd->size) ? j : dd->invperm[j];
            if (support[i] == 1) {
                /* The following call to cuddUniqueInter is guaranteed
                ** not to trigger reordering because the node we look up
                ** already exists. */
                var = cuddUniqueInter(dd,i,dd->one,Cudd_Not(dd->one));
                cuddRef(var);
                tmp = cuddBddAndRecur(dd,res,var);
                if (tmp == NULL) {
                    Cudd_RecursiveDeref(dd,res);
                    Cudd_RecursiveDeref(dd,var);
                    res = NULL;
                    break;
                }
                cuddRef(tmp);
                Cudd_RecursiveDeref(dd,res);
                Cudd_RecursiveDeref(dd,var);
                res = tmp;
            }
Alan Mishchenko committed
789 790 791
        }
    } while (dd->reordered == 1);

Alan Mishchenko committed
792
    ABC_FREE(support);
Alan Mishchenko committed
793 794 795 796 797 798 799 800 801 802
    if (res != NULL) cuddDeref(res);
    return(res);

} /* end of Cudd_Support */


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

  Synopsis    [Finds the variables on which a DD depends.]

803 804 805 806 807
  Description [Finds the variables on which a DD depends.  Returns an
  index array of the variables if successful; NULL otherwise.  The
  size of the array equals the number of variables in the manager.
  Each entry of the array is 1 if the corresponding variable is in the
  support of the DD and 0 otherwise.]
Alan Mishchenko committed
808 809 810 811 812 813 814 815 816 817 818

  SideEffects [None]

  SeeAlso     [Cudd_Support Cudd_VectorSupport Cudd_ClassifySupport]

******************************************************************************/
int *
Cudd_SupportIndex(
  DdManager * dd /* manager */,
  DdNode * f /* DD whose support is sought */)
{
819 820
    int *support;
    int i;
Alan Mishchenko committed
821 822 823 824
    int size;

    /* Allocate and initialize support array for ddSupportStep. */
    size = ddMax(dd->size, dd->sizeZ);
Alan Mishchenko committed
825
    support = ABC_ALLOC(int,size);
Alan Mishchenko committed
826
    if (support == NULL) {
827 828
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
Alan Mishchenko committed
829 830
    }
    for (i = 0; i < size; i++) {
831
        support[i] = 0;
Alan Mishchenko committed
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
    }

    /* Compute support and clean up markers. */
    ddSupportStep(Cudd_Regular(f),support);
    ddClearFlag(Cudd_Regular(f));

    return(support);

} /* end of Cudd_SupportIndex */


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

  Synopsis    [Counts the variables on which a DD depends.]

  Description [Counts the variables on which a DD depends.
  Returns the number of the variables if successful; CUDD_OUT_OF_MEM
  otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_Support]

******************************************************************************/
int
Cudd_SupportSize(
  DdManager * dd /* manager */,
  DdNode * f /* DD whose support size is sought */)
{
861 862
    int *support;
    int i;
Alan Mishchenko committed
863 864 865 866 867
    int size;
    int count;

    /* Allocate and initialize support array for ddSupportStep. */
    size = ddMax(dd->size, dd->sizeZ);
Alan Mishchenko committed
868
    support = ABC_ALLOC(int,size);
Alan Mishchenko committed
869
    if (support == NULL) {
870 871
        dd->errorCode = CUDD_MEMORY_OUT;
        return(CUDD_OUT_OF_MEM);
Alan Mishchenko committed
872 873
    }
    for (i = 0; i < size; i++) {
874
        support[i] = 0;
Alan Mishchenko committed
875 876 877 878 879 880 881 882 883
    }

    /* Compute support and clean up markers. */
    ddSupportStep(Cudd_Regular(f),support);
    ddClearFlag(Cudd_Regular(f));

    /* Count support variables. */
    count = 0;
    for (i = 0; i < size; i++) {
884
        if (support[i] == 1) count++;
Alan Mishchenko committed
885 886
    }

Alan Mishchenko committed
887
    ABC_FREE(support);
Alan Mishchenko committed
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
    return(count);

} /* end of Cudd_SupportSize */


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

  Synopsis    [Finds the variables on which a set of DDs depends.]

  Description [Finds the variables on which a set of DDs depends.
  The set must contain either BDDs and ADDs, or ZDDs.
  Returns a BDD consisting of the product of the variables if
  successful; NULL otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_Support Cudd_ClassifySupport]

******************************************************************************/
DdNode *
Cudd_VectorSupport(
  DdManager * dd /* manager */,
  DdNode ** F /* array of DDs whose support is sought */,
  int  n /* size of the array */)
{
913
    int *support;
Alan Mishchenko committed
914
    DdNode *res, *tmp, *var;
915
    int i,j;
Alan Mishchenko committed
916 917 918 919
    int size;

    /* Allocate and initialize support array for ddSupportStep. */
    size = ddMax(dd->size, dd->sizeZ);
Alan Mishchenko committed
920
    support = ABC_ALLOC(int,size);
Alan Mishchenko committed
921
    if (support == NULL) {
922 923
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
Alan Mishchenko committed
924 925
    }
    for (i = 0; i < size; i++) {
926
        support[i] = 0;
Alan Mishchenko committed
927 928 929 930
    }

    /* Compute support and clean up markers. */
    for (i = 0; i < n; i++) {
931
        ddSupportStep(Cudd_Regular(F[i]),support);
Alan Mishchenko committed
932 933
    }
    for (i = 0; i < n; i++) {
934
        ddClearFlag(Cudd_Regular(F[i]));
Alan Mishchenko committed
935 936 937 938 939 940
    }

    /* Transform support from array to cube. */
    res = DD_ONE(dd);
    cuddRef(res);
    for (j = size - 1; j >= 0; j--) { /* for each level bottom-up */
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
        i = (j >= dd->size) ? j : dd->invperm[j];
        if (support[i] == 1) {
            var = cuddUniqueInter(dd,i,dd->one,Cudd_Not(dd->one));
            cuddRef(var);
            tmp = Cudd_bddAnd(dd,res,var);
            if (tmp == NULL) {
                Cudd_RecursiveDeref(dd,res);
                Cudd_RecursiveDeref(dd,var);
                ABC_FREE(support);
                return(NULL);
            }
            cuddRef(tmp);
            Cudd_RecursiveDeref(dd,res);
            Cudd_RecursiveDeref(dd,var);
            res = tmp;
Alan Mishchenko committed
956 957 958
        }
    }

Alan Mishchenko committed
959
    ABC_FREE(support);
Alan Mishchenko committed
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    cuddDeref(res);
    return(res);

} /* end of Cudd_VectorSupport */


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

  Synopsis    [Finds the variables on which a set of DDs depends.]

  Description [Finds the variables on which a set of DDs depends.
  The set must contain either BDDs and ADDs, or ZDDs.
  Returns an index array of the variables if successful; NULL otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_SupportIndex Cudd_VectorSupport Cudd_ClassifySupport]

******************************************************************************/
int *
Cudd_VectorSupportIndex(
  DdManager * dd /* manager */,
  DdNode ** F /* array of DDs whose support is sought */,
  int  n /* size of the array */)
{
985 986
    int *support;
    int i;
Alan Mishchenko committed
987 988 989 990
    int size;

    /* Allocate and initialize support array for ddSupportStep. */
    size = ddMax(dd->size, dd->sizeZ);
Alan Mishchenko committed
991
    support = ABC_ALLOC(int,size);
Alan Mishchenko committed
992
    if (support == NULL) {
993 994
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
Alan Mishchenko committed
995 996
    }
    for (i = 0; i < size; i++) {
997
        support[i] = 0;
Alan Mishchenko committed
998 999 1000 1001
    }

    /* Compute support and clean up markers. */
    for (i = 0; i < n; i++) {
1002
        ddSupportStep(Cudd_Regular(F[i]),support);
Alan Mishchenko committed
1003 1004
    }
    for (i = 0; i < n; i++) {
1005
        ddClearFlag(Cudd_Regular(F[i]));
Alan Mishchenko committed
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    }

    return(support);

} /* end of Cudd_VectorSupportIndex */


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

  Synopsis    [Counts the variables on which a set of DDs depends.]

  Description [Counts the variables on which a set of DDs depends.
  The set must contain either BDDs and ADDs, or ZDDs.
  Returns the number of the variables if successful; CUDD_OUT_OF_MEM
  otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_VectorSupport Cudd_SupportSize]

******************************************************************************/
int
Cudd_VectorSupportSize(
  DdManager * dd /* manager */,
  DdNode ** F /* array of DDs whose support is sought */,
  int  n /* size of the array */)
{
1033 1034
    int *support;
    int i;
Alan Mishchenko committed
1035 1036 1037 1038 1039
    int size;
    int count;

    /* Allocate and initialize support array for ddSupportStep. */
    size = ddMax(dd->size, dd->sizeZ);
Alan Mishchenko committed
1040
    support = ABC_ALLOC(int,size);
Alan Mishchenko committed
1041
    if (support == NULL) {
1042 1043
        dd->errorCode = CUDD_MEMORY_OUT;
        return(CUDD_OUT_OF_MEM);
Alan Mishchenko committed
1044 1045
    }
    for (i = 0; i < size; i++) {
1046
        support[i] = 0;
Alan Mishchenko committed
1047 1048 1049 1050
    }

    /* Compute support and clean up markers. */
    for (i = 0; i < n; i++) {
1051
        ddSupportStep(Cudd_Regular(F[i]),support);
Alan Mishchenko committed
1052 1053
    }
    for (i = 0; i < n; i++) {
1054
        ddClearFlag(Cudd_Regular(F[i]));
Alan Mishchenko committed
1055 1056 1057 1058 1059
    }

    /* Count vriables in support. */
    count = 0;
    for (i = 0; i < size; i++) {
1060
        if (support[i] == 1) count++;
Alan Mishchenko committed
1061 1062
    }

Alan Mishchenko committed
1063
    ABC_FREE(support);
Alan Mishchenko committed
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
    return(count);

} /* end of Cudd_VectorSupportSize */


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

  Synopsis    [Classifies the variables in the support of two DDs.]

  Description [Classifies the variables in the support of two DDs
  <code>f</code> and <code>g</code>, depending on whther they appear
  in both DDs, only in <code>f</code>, or only in <code>g</code>.
  Returns 1 if successful; 0 otherwise.]

  SideEffects [The cubes of the three classes of variables are
  returned as side effects.]

  SeeAlso     [Cudd_Support Cudd_VectorSupport]

******************************************************************************/
int
Cudd_ClassifySupport(
  DdManager * dd /* manager */,
  DdNode * f /* first DD */,
  DdNode * g /* second DD */,
  DdNode ** common /* cube of shared variables */,
  DdNode ** onlyF /* cube of variables only in f */,
  DdNode ** onlyG /* cube of variables only in g */)
{
1093
    int *supportF, *supportG;
Alan Mishchenko committed
1094
    DdNode *tmp, *var;
1095
    int i,j;
Alan Mishchenko committed
1096 1097 1098 1099
    int size;

    /* Allocate and initialize support arrays for ddSupportStep. */
    size = ddMax(dd->size, dd->sizeZ);
Alan Mishchenko committed
1100
    supportF = ABC_ALLOC(int,size);
Alan Mishchenko committed
1101
    if (supportF == NULL) {
1102 1103
        dd->errorCode = CUDD_MEMORY_OUT;
        return(0);
Alan Mishchenko committed
1104
    }
Alan Mishchenko committed
1105
    supportG = ABC_ALLOC(int,size);
Alan Mishchenko committed
1106
    if (supportG == NULL) {
1107 1108 1109
        dd->errorCode = CUDD_MEMORY_OUT;
        ABC_FREE(supportF);
        return(0);
Alan Mishchenko committed
1110 1111
    }
    for (i = 0; i < size; i++) {
1112 1113
        supportF[i] = 0;
        supportG[i] = 0;
Alan Mishchenko committed
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    }

    /* Compute supports and clean up markers. */
    ddSupportStep(Cudd_Regular(f),supportF);
    ddClearFlag(Cudd_Regular(f));
    ddSupportStep(Cudd_Regular(g),supportG);
    ddClearFlag(Cudd_Regular(g));

    /* Classify variables and create cubes. */
    *common = *onlyF = *onlyG = DD_ONE(dd);
    cuddRef(*common); cuddRef(*onlyF); cuddRef(*onlyG);
    for (j = size - 1; j >= 0; j--) { /* for each level bottom-up */
1126 1127 1128 1129 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 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
        i = (j >= dd->size) ? j : dd->invperm[j];
        if (supportF[i] == 0 && supportG[i] == 0) continue;
        var = cuddUniqueInter(dd,i,dd->one,Cudd_Not(dd->one));
        cuddRef(var);
        if (supportG[i] == 0) {
            tmp = Cudd_bddAnd(dd,*onlyF,var);
            if (tmp == NULL) {
                Cudd_RecursiveDeref(dd,*common);
                Cudd_RecursiveDeref(dd,*onlyF);
                Cudd_RecursiveDeref(dd,*onlyG);
                Cudd_RecursiveDeref(dd,var);
                ABC_FREE(supportF); ABC_FREE(supportG);
                return(0);
            }
            cuddRef(tmp);
            Cudd_RecursiveDeref(dd,*onlyF);
            *onlyF = tmp;
        } else if (supportF[i] == 0) {
            tmp = Cudd_bddAnd(dd,*onlyG,var);
            if (tmp == NULL) {
                Cudd_RecursiveDeref(dd,*common);
                Cudd_RecursiveDeref(dd,*onlyF);
                Cudd_RecursiveDeref(dd,*onlyG);
                Cudd_RecursiveDeref(dd,var);
                ABC_FREE(supportF); ABC_FREE(supportG);
                return(0);
            }
            cuddRef(tmp);
            Cudd_RecursiveDeref(dd,*onlyG);
            *onlyG = tmp;
        } else {
            tmp = Cudd_bddAnd(dd,*common,var);
            if (tmp == NULL) {
                Cudd_RecursiveDeref(dd,*common);
                Cudd_RecursiveDeref(dd,*onlyF);
                Cudd_RecursiveDeref(dd,*onlyG);
                Cudd_RecursiveDeref(dd,var);
                ABC_FREE(supportF); ABC_FREE(supportG);
                return(0);
            }
            cuddRef(tmp);
            Cudd_RecursiveDeref(dd,*common);
            *common = tmp;
Alan Mishchenko committed
1169 1170 1171 1172
        }
        Cudd_RecursiveDeref(dd,var);
    }

Alan Mishchenko committed
1173
    ABC_FREE(supportF); ABC_FREE(supportG);
Alan Mishchenko committed
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    cuddDeref(*common); cuddDeref(*onlyF); cuddDeref(*onlyG);
    return(1);

} /* end of Cudd_ClassifySupport */


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

  Synopsis    [Counts the number of leaves in a DD.]

  Description [Counts the number of leaves in a DD. Returns the number
  of leaves in the DD rooted at node if successful; CUDD_OUT_OF_MEM
  otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_PrintDebug]

******************************************************************************/
int
Cudd_CountLeaves(
  DdNode * node)
{
1197
    int i;
Alan Mishchenko committed
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241

    i = ddLeavesInt(Cudd_Regular(node));
    ddClearFlag(Cudd_Regular(node));
    return(i);

} /* end of Cudd_CountLeaves */


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

  Synopsis    [Picks one on-set cube randomly from the given DD.]

  Description [Picks one on-set cube randomly from the given DD. The
  cube is written into an array of characters.  The array must have at
  least as many entries as there are variables. Returns 1 if
  successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_bddPickOneMinterm]

******************************************************************************/
int
Cudd_bddPickOneCube(
  DdManager * ddm,
  DdNode * node,
  char * string)
{
    DdNode *N, *T, *E;
    DdNode *one, *bzero;
    char   dir;
    int    i;

    if (string == NULL || node == NULL) return(0);

    /* The constant 0 function has no on-set cubes. */
    one = DD_ONE(ddm);
    bzero = Cudd_Not(one);
    if (node == bzero) return(0);

    for (i = 0; i < ddm->size; i++) string[i] = 2;

    for (;;) {

1242
        if (node == one) break;
Alan Mishchenko committed
1243

1244
        N = Cudd_Regular(node);
Alan Mishchenko committed
1245

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
        T = cuddT(N); E = cuddE(N);
        if (Cudd_IsComplement(node)) {
            T = Cudd_Not(T); E = Cudd_Not(E);
        }
        if (T == bzero) {
            string[N->index] = 0;
            node = E;
        } else if (E == bzero) {
            string[N->index] = 1;
            node = T;
        } else {
            dir = (char) ((Cudd_Random() & 0x2000) >> 13);
            string[N->index] = dir;
            node = dir ? T : E;
        }
Alan Mishchenko committed
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
    }
    return(1);

} /* end of Cudd_bddPickOneCube */


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

  Synopsis    [Picks one on-set minterm randomly from the given DD.]

  Description [Picks one on-set minterm randomly from the given
  DD. The minterm is in terms of <code>vars</code>. The array
  <code>vars</code> should contain at least all variables in the
  support of <code>f</code>; if this condition is not met the minterm
  built by this procedure may not be contained in
  <code>f</code>. Builds a BDD for the minterm and returns a pointer
  to it if successful; NULL otherwise. There are three reasons why the
  procedure may fail:
  <ul>
  <li> It may run out of memory;
  <li> the function <code>f</code> may be the constant 0;
  <li> the minterm may not be contained in <code>f</code>.
  </ul>]

  SideEffects [None]

  SeeAlso     [Cudd_bddPickOneCube]

******************************************************************************/
DdNode *
Cudd_bddPickOneMinterm(
  DdManager * dd /* manager */,
  DdNode * f /* function from which to pick one minterm */,
  DdNode ** vars /* array of variables */,
  int  n /* size of <code>vars</code> */)
{
    char *string;
    int i, size;
    int *indices;
    int result;
    DdNode *old, *neW;

    size = dd->size;
Alan Mishchenko committed
1304
    string = ABC_ALLOC(char, size);
Alan Mishchenko committed
1305
    if (string == NULL) {
1306 1307
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
Alan Mishchenko committed
1308
    }
Alan Mishchenko committed
1309
    indices = ABC_ALLOC(int,n);
Alan Mishchenko committed
1310
    if (indices == NULL) {
1311 1312 1313
        dd->errorCode = CUDD_MEMORY_OUT;
        ABC_FREE(string);
        return(NULL);
Alan Mishchenko committed
1314 1315 1316 1317 1318 1319 1320 1321
    }

    for (i = 0; i < n; i++) {
        indices[i] = vars[i]->index;
    }

    result = Cudd_bddPickOneCube(dd,f,string);
    if (result == 0) {
1322 1323 1324
        ABC_FREE(string);
        ABC_FREE(indices);
        return(NULL);
Alan Mishchenko committed
1325 1326 1327 1328
    }

    /* Randomize choice for don't cares. */
    for (i = 0; i < n; i++) {
1329 1330
        if (string[indices[i]] == 2)
            string[indices[i]] = (char) ((Cudd_Random() & 0x20) >> 5);
Alan Mishchenko committed
1331 1332 1333 1334 1335 1336 1337
    }

    /* Build result BDD. */
    old = Cudd_ReadOne(dd);
    cuddRef(old);

    for (i = n-1; i >= 0; i--) {
1338 1339 1340 1341 1342 1343 1344 1345
        neW = Cudd_bddAnd(dd,old,Cudd_NotCond(vars[i],string[indices[i]]==0));
        if (neW == NULL) {
            ABC_FREE(string);
            ABC_FREE(indices);
            Cudd_RecursiveDeref(dd,old);
            return(NULL);
        }
        cuddRef(neW);
Alan Mishchenko committed
1346
        Cudd_RecursiveDeref(dd,old);
1347
        old = neW;
Alan Mishchenko committed
1348 1349 1350 1351 1352
    }

#ifdef DD_DEBUG
    /* Test. */
    if (Cudd_bddLeq(dd,old,f)) {
1353
        cuddDeref(old);
Alan Mishchenko committed
1354
    } else {
1355 1356
        Cudd_RecursiveDeref(dd,old);
        old = NULL;
Alan Mishchenko committed
1357 1358 1359 1360 1361
    }
#else
    cuddDeref(old);
#endif

Alan Mishchenko committed
1362 1363
    ABC_FREE(string);
    ABC_FREE(indices);
Alan Mishchenko committed
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
    return(old);

}  /* end of Cudd_bddPickOneMinterm */


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

  Synopsis    [Picks k on-set minterms evenly distributed from given DD.]

  Description [Picks k on-set minterms evenly distributed from given DD.
  The minterms are in terms of <code>vars</code>. The array
  <code>vars</code> should contain at least all variables in the
  support of <code>f</code>; if this condition is not met the minterms
  built by this procedure may not be contained in
  <code>f</code>. Builds an array of BDDs for the minterms and returns a
  pointer to it if successful; NULL otherwise. There are three reasons
  why the procedure may fail:
  <ul>
  <li> It may run out of memory;
  <li> the function <code>f</code> may be the constant 0;
  <li> the minterms may not be contained in <code>f</code>.
  </ul>]

  SideEffects [None]

  SeeAlso     [Cudd_bddPickOneMinterm Cudd_bddPickOneCube]

******************************************************************************/
DdNode **
Cudd_bddPickArbitraryMinterms(
  DdManager * dd /* manager */,
  DdNode * f /* function from which to pick k minterms */,
  DdNode ** vars /* array of variables */,
  int  n /* size of <code>vars</code> */,
  int  k /* number of minterms to find */)
{
    char **string;
    int i, j, l, size;
    int *indices;
    int result;
    DdNode **old, *neW;
    double minterms;
    char *saveString;
1407
    int saveFlag, savePoint = -1, isSame;
Alan Mishchenko committed
1408 1409 1410

    minterms = Cudd_CountMinterm(dd,f,n);
    if ((double)k > minterms) {
1411
        return(NULL);
Alan Mishchenko committed
1412 1413 1414
    }

    size = dd->size;
Alan Mishchenko committed
1415
    string = ABC_ALLOC(char *, k);
Alan Mishchenko committed
1416 1417 1418 1419
    if (string == NULL) {
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
    }
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
    for (i = 0; i < k; i++) {
        string[i] = ABC_ALLOC(char, size + 1);
        if (string[i] == NULL) {
            for (j = 0; j < i; j++)
                ABC_FREE(string[i]);
            ABC_FREE(string);
            dd->errorCode = CUDD_MEMORY_OUT;
            return(NULL);
        }
        for (j = 0; j < size; j++) string[i][j] = '2';
        string[i][size] = '\0';
Alan Mishchenko committed
1431
    }
Alan Mishchenko committed
1432
    indices = ABC_ALLOC(int,n);
Alan Mishchenko committed
1433
    if (indices == NULL) {
1434 1435 1436 1437 1438
        dd->errorCode = CUDD_MEMORY_OUT;
        for (i = 0; i < k; i++)
            ABC_FREE(string[i]);
        ABC_FREE(string);
        return(NULL);
Alan Mishchenko committed
1439 1440 1441 1442 1443 1444 1445 1446
    }

    for (i = 0; i < n; i++) {
        indices[i] = vars[i]->index;
    }

    result = ddPickArbitraryMinterms(dd,f,n,k,string);
    if (result == 0) {
1447 1448 1449 1450 1451
        for (i = 0; i < k; i++)
            ABC_FREE(string[i]);
        ABC_FREE(string);
        ABC_FREE(indices);
        return(NULL);
Alan Mishchenko committed
1452 1453
    }

Alan Mishchenko committed
1454
    old = ABC_ALLOC(DdNode *, k);
Alan Mishchenko committed
1455
    if (old == NULL) {
1456 1457 1458 1459 1460 1461
        dd->errorCode = CUDD_MEMORY_OUT;
        for (i = 0; i < k; i++)
            ABC_FREE(string[i]);
        ABC_FREE(string);
        ABC_FREE(indices);
        return(NULL);
Alan Mishchenko committed
1462
    }
Alan Mishchenko committed
1463
    saveString = ABC_ALLOC(char, size + 1);
Alan Mishchenko committed
1464
    if (saveString == NULL) {
1465 1466 1467 1468 1469 1470 1471
        dd->errorCode = CUDD_MEMORY_OUT;
        for (i = 0; i < k; i++)
            ABC_FREE(string[i]);
        ABC_FREE(string);
        ABC_FREE(indices);
        ABC_FREE(old);
        return(NULL);
Alan Mishchenko committed
1472 1473 1474 1475 1476
    }
    saveFlag = 0;

    /* Build result BDD array. */
    for (i = 0; i < k; i++) {
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
        isSame = 0;
        if (!saveFlag) {
            for (j = i + 1; j < k; j++) {
                if (strcmp(string[i], string[j]) == 0) {
                    savePoint = i;
                    strcpy(saveString, string[i]);
                    saveFlag = 1;
                    break;
                }
            }
Alan Mishchenko committed
1487
        } else {
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
            if (strcmp(string[i], saveString) == 0) {
                isSame = 1;
            } else {
                saveFlag = 0;
                for (j = i + 1; j < k; j++) {
                    if (strcmp(string[i], string[j]) == 0) {
                        savePoint = i;
                        strcpy(saveString, string[i]);
                        saveFlag = 1;
                        break;
                    }
                }
Alan Mishchenko committed
1500 1501 1502 1503
            }
        }
        /* Randomize choice for don't cares. */
        for (j = 0; j < n; j++) {
1504 1505 1506
            if (string[i][indices[j]] == '2')
                string[i][indices[j]] =
                  (char) ((Cudd_Random() & 0x20) ? '1' : '0');
Alan Mishchenko committed
1507
        }
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525

        while (isSame) {
            isSame = 0;
            for (j = savePoint; j < i; j++) {
                if (strcmp(string[i], string[j]) == 0) {
                    isSame = 1;
                    break;
                }
            }
            if (isSame) {
                strcpy(string[i], saveString);
                /* Randomize choice for don't cares. */
                for (j = 0; j < n; j++) {
                    if (string[i][indices[j]] == '2')
                        string[i][indices[j]] =
                          (char) ((Cudd_Random() & 0x20) ? '1' : '0');
                }
            }
Alan Mishchenko committed
1526 1527
        }

1528 1529
        old[i] = Cudd_ReadOne(dd);
        cuddRef(old[i]);
Alan Mishchenko committed
1530

1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
        for (j = 0; j < n; j++) {
            if (string[i][indices[j]] == '0') {
                neW = Cudd_bddAnd(dd,old[i],Cudd_Not(vars[j]));
            } else {
                neW = Cudd_bddAnd(dd,old[i],vars[j]);
            }
            if (neW == NULL) {
                ABC_FREE(saveString);
                for (l = 0; l < k; l++)
                    ABC_FREE(string[l]);
                ABC_FREE(string);
                ABC_FREE(indices);
                for (l = 0; l <= i; l++)
                    Cudd_RecursiveDeref(dd,old[l]);
                ABC_FREE(old);
                return(NULL);
            }
            cuddRef(neW);
            Cudd_RecursiveDeref(dd,old[i]);
            old[i] = neW;
Alan Mishchenko committed
1551 1552
        }

1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
        /* Test. */
        if (!Cudd_bddLeq(dd,old[i],f)) {
            ABC_FREE(saveString);
            for (l = 0; l < k; l++)
                ABC_FREE(string[l]);
            ABC_FREE(string);
            ABC_FREE(indices);
            for (l = 0; l <= i; l++)
                Cudd_RecursiveDeref(dd,old[l]);
            ABC_FREE(old);
            return(NULL);
        }
Alan Mishchenko committed
1565 1566
    }

Alan Mishchenko committed
1567
    ABC_FREE(saveString);
Alan Mishchenko committed
1568
    for (i = 0; i < k; i++) {
1569 1570
        cuddDeref(old[i]);
        ABC_FREE(string[i]);
Alan Mishchenko committed
1571
    }
Alan Mishchenko committed
1572 1573
    ABC_FREE(string);
    ABC_FREE(indices);
Alan Mishchenko committed
1574 1575 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 1603 1604 1605 1606 1607 1608 1609
    return(old);

}  /* end of Cudd_bddPickArbitraryMinterms */


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

  Synopsis    [Extracts a subset from a BDD.]

  Description [Extracts a subset from a BDD in the following procedure.
  1. Compute the weight for each mask variable by counting the number of
     minterms for both positive and negative cofactors of the BDD with
     respect to each mask variable. (weight = #positive - #negative)
  2. Find a representative cube of the BDD by using the weight. From the
     top variable of the BDD, for each variable, if the weight is greater
     than 0.0, choose THEN branch, othereise ELSE branch, until meeting
     the constant 1.
  3. Quantify out the variables not in maskVars from the representative
     cube and if a variable in maskVars is don't care, replace the
     variable with a constant(1 or 0) depending on the weight.
  4. Make a subset of the BDD by multiplying with the modified cube.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
DdNode *
Cudd_SubsetWithMaskVars(
  DdManager * dd /* manager */,
  DdNode * f /* function from which to pick a cube */,
  DdNode ** vars /* array of variables */,
  int  nvars /* size of <code>vars</code> */,
  DdNode ** maskVars /* array of variables */,
  int  mvars /* size of <code>maskVars</code> */)
{
1610 1611 1612 1613 1614 1615 1616 1617 1618
    double      *weight;
    char        *string;
    int         i, size;
    int         *indices, *mask;
    int         result;
    DdNode      *zero, *cube, *newCube, *subset;
    DdNode      *cof;

    DdNode      *support;
Alan Mishchenko committed
1619 1620 1621 1622 1623 1624
    support = Cudd_Support(dd,f);
    cuddRef(support);
    Cudd_RecursiveDeref(dd,support);

    zero = Cudd_Not(dd->one);
    size = dd->size;
1625

Alan Mishchenko committed
1626
    weight = ABC_ALLOC(double,size);
Alan Mishchenko committed
1627
    if (weight == NULL) {
1628 1629
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
Alan Mishchenko committed
1630 1631 1632 1633 1634
    }
    for (i = 0; i < size; i++) {
        weight[i] = 0.0;
    }
    for (i = 0; i < mvars; i++) {
1635 1636 1637 1638
        cof = Cudd_Cofactor(dd, f, maskVars[i]);
        cuddRef(cof);
        weight[i] = Cudd_CountMinterm(dd, cof, nvars);
        Cudd_RecursiveDeref(dd,cof);
Alan Mishchenko committed
1639

1640 1641 1642 1643
        cof = Cudd_Cofactor(dd, f, Cudd_Not(maskVars[i]));
        cuddRef(cof);
        weight[i] -= Cudd_CountMinterm(dd, cof, nvars);
        Cudd_RecursiveDeref(dd,cof);
Alan Mishchenko committed
1644 1645
    }

Alan Mishchenko committed
1646
    string = ABC_ALLOC(char, size + 1);
Alan Mishchenko committed
1647
    if (string == NULL) {
1648 1649 1650
        dd->errorCode = CUDD_MEMORY_OUT;
        ABC_FREE(weight);
        return(NULL);
Alan Mishchenko committed
1651
    }
Alan Mishchenko committed
1652
    mask = ABC_ALLOC(int, size);
Alan Mishchenko committed
1653
    if (mask == NULL) {
1654 1655 1656 1657
        dd->errorCode = CUDD_MEMORY_OUT;
        ABC_FREE(weight);
        ABC_FREE(string);
        return(NULL);
Alan Mishchenko committed
1658 1659
    }
    for (i = 0; i < size; i++) {
1660 1661
        string[i] = '2';
        mask[i] = 0;
Alan Mishchenko committed
1662 1663
    }
    string[size] = '\0';
Alan Mishchenko committed
1664
    indices = ABC_ALLOC(int,nvars);
Alan Mishchenko committed
1665
    if (indices == NULL) {
1666 1667 1668 1669 1670
        dd->errorCode = CUDD_MEMORY_OUT;
        ABC_FREE(weight);
        ABC_FREE(string);
        ABC_FREE(mask);
        return(NULL);
Alan Mishchenko committed
1671 1672 1673 1674 1675
    }
    for (i = 0; i < nvars; i++) {
        indices[i] = vars[i]->index;
    }

1676
    result = ddPickRepresentativeCube(dd,f,weight,string);
Alan Mishchenko committed
1677
    if (result == 0) {
1678 1679 1680 1681 1682
        ABC_FREE(weight);
        ABC_FREE(string);
        ABC_FREE(mask);
        ABC_FREE(indices);
        return(NULL);
Alan Mishchenko committed
1683 1684 1685 1686 1687 1688
    }

    cube = Cudd_ReadOne(dd);
    cuddRef(cube);
    zero = Cudd_Not(Cudd_ReadOne(dd));
    for (i = 0; i < nvars; i++) {
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
        if (string[indices[i]] == '0') {
            newCube = Cudd_bddIte(dd,cube,Cudd_Not(vars[i]),zero);
        } else if (string[indices[i]] == '1') {
            newCube = Cudd_bddIte(dd,cube,vars[i],zero);
        } else
            continue;
        if (newCube == NULL) {
            ABC_FREE(weight);
            ABC_FREE(string);
            ABC_FREE(mask);
            ABC_FREE(indices);
            Cudd_RecursiveDeref(dd,cube);
            return(NULL);
        }
        cuddRef(newCube);
Alan Mishchenko committed
1704
        Cudd_RecursiveDeref(dd,cube);
1705
        cube = newCube;
Alan Mishchenko committed
1706 1707 1708 1709
    }
    Cudd_RecursiveDeref(dd,cube);

    for (i = 0; i < mvars; i++) {
1710
        mask[maskVars[i]->index] = 1;
Alan Mishchenko committed
1711 1712
    }
    for (i = 0; i < nvars; i++) {
1713 1714 1715 1716 1717 1718 1719 1720 1721
        if (mask[indices[i]]) {
            if (string[indices[i]] == '2') {
                if (weight[indices[i]] >= 0.0)
                    string[indices[i]] = '1';
                else
                    string[indices[i]] = '0';
            }
        } else {
            string[indices[i]] = '2';
Alan Mishchenko committed
1722 1723 1724 1725 1726 1727 1728 1729 1730
        }
    }

    cube = Cudd_ReadOne(dd);
    cuddRef(cube);
    zero = Cudd_Not(Cudd_ReadOne(dd));

    /* Build result BDD. */
    for (i = 0; i < nvars; i++) {
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
        if (string[indices[i]] == '0') {
            newCube = Cudd_bddIte(dd,cube,Cudd_Not(vars[i]),zero);
        } else if (string[indices[i]] == '1') {
            newCube = Cudd_bddIte(dd,cube,vars[i],zero);
        } else
            continue;
        if (newCube == NULL) {
            ABC_FREE(weight);
            ABC_FREE(string);
            ABC_FREE(mask);
            ABC_FREE(indices);
            Cudd_RecursiveDeref(dd,cube);
            return(NULL);
        }
        cuddRef(newCube);
Alan Mishchenko committed
1746
        Cudd_RecursiveDeref(dd,cube);
1747
        cube = newCube;
Alan Mishchenko committed
1748 1749 1750 1751 1752 1753 1754 1755
    }

    subset = Cudd_bddAnd(dd,f,cube);
    cuddRef(subset);
    Cudd_RecursiveDeref(dd,cube);

    /* Test. */
    if (Cudd_bddLeq(dd,subset,f)) {
1756
        cuddDeref(subset);
Alan Mishchenko committed
1757
    } else {
1758 1759
        Cudd_RecursiveDeref(dd,subset);
        subset = NULL;
Alan Mishchenko committed
1760 1761
    }

1762
    ABC_FREE(weight);
Alan Mishchenko committed
1763 1764 1765
    ABC_FREE(string);
    ABC_FREE(mask);
    ABC_FREE(indices);
Alan Mishchenko committed
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812
    return(subset);

} /* end of Cudd_SubsetWithMaskVars */


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

  Synopsis    [Finds the first cube of a decision diagram.]

  Description [Defines an iterator on the onset of a decision diagram
  and finds its first cube. Returns a generator that contains the
  information necessary to continue the enumeration if successful; NULL
  otherwise.<p>
  A cube is represented as an array of literals, which are integers in
  {0, 1, 2}; 0 represents a complemented literal, 1 represents an
  uncomplemented literal, and 2 stands for don't care. The enumeration
  produces a disjoint cover of the function associated with the diagram.
  The size of the array equals the number of variables in the manager at
  the time Cudd_FirstCube is called.<p>
  For each cube, a value is also returned. This value is always 1 for a
  BDD, while it may be different from 1 for an ADD.
  For BDDs, the offset is the set of cubes whose value is the logical zero.
  For ADDs, the offset is the set of cubes whose value is the
  background value. The cubes of the offset are not enumerated.]

  SideEffects [The first cube and its value are returned as side effects.]

  SeeAlso     [Cudd_ForeachCube Cudd_NextCube Cudd_GenFree Cudd_IsGenEmpty
  Cudd_FirstNode]

******************************************************************************/
DdGen *
Cudd_FirstCube(
  DdManager * dd,
  DdNode * f,
  int ** cube,
  CUDD_VALUE_TYPE * value)
{
    DdGen *gen;
    DdNode *top, *treg, *next, *nreg, *prev, *preg;
    int i;
    int nvars;

    /* Sanity Check. */
    if (dd == NULL || f == NULL) return(NULL);

    /* Allocate generator an initialize it. */
Alan Mishchenko committed
1813
    gen = ABC_ALLOC(DdGen,1);
Alan Mishchenko committed
1814
    if (gen == NULL) {
1815 1816
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
Alan Mishchenko committed
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828
    }

    gen->manager = dd;
    gen->type = CUDD_GEN_CUBES;
    gen->status = CUDD_GEN_EMPTY;
    gen->gen.cubes.cube = NULL;
    gen->gen.cubes.value = DD_ZERO_VAL;
    gen->stack.sp = 0;
    gen->stack.stack = NULL;
    gen->node = NULL;

    nvars = dd->size;
Alan Mishchenko committed
1829
    gen->gen.cubes.cube = ABC_ALLOC(int,nvars);
Alan Mishchenko committed
1830
    if (gen->gen.cubes.cube == NULL) {
1831 1832 1833
        dd->errorCode = CUDD_MEMORY_OUT;
        ABC_FREE(gen);
        return(NULL);
Alan Mishchenko committed
1834 1835 1836 1837 1838 1839 1840
    }
    for (i = 0; i < nvars; i++) gen->gen.cubes.cube[i] = 2;

    /* The maximum stack depth is one plus the number of variables.
    ** because a path may have nodes at all levels, including the
    ** constant level.
    */
1841
    gen->stack.stack = ABC_ALLOC(DdNodePtr, nvars+1);
Alan Mishchenko committed
1842
    if (gen->stack.stack == NULL) {
1843 1844 1845 1846
        dd->errorCode = CUDD_MEMORY_OUT;
        ABC_FREE(gen->gen.cubes.cube);
        ABC_FREE(gen);
        return(NULL);
Alan Mishchenko committed
1847 1848 1849 1850 1851 1852 1853 1854 1855
    }
    for (i = 0; i <= nvars; i++) gen->stack.stack[i] = NULL;

    /* Find the first cube of the onset. */
    gen->stack.stack[gen->stack.sp] = f; gen->stack.sp++;

    while (1) {
        top = gen->stack.stack[gen->stack.sp-1];
        treg = Cudd_Regular(top);
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
        if (!cuddIsConstant(treg)) {
            /* Take the else branch first. */
            gen->gen.cubes.cube[treg->index] = 0;
            next = cuddE(treg);
            if (top != treg) next = Cudd_Not(next);
            gen->stack.stack[gen->stack.sp] = next; gen->stack.sp++;
        } else if (top == Cudd_Not(DD_ONE(dd)) || top == dd->background) {
            /* Backtrack */
            while (1) {
                if (gen->stack.sp == 1) {
                    /* The current node has no predecessor. */
                    gen->status = CUDD_GEN_EMPTY;
                    gen->stack.sp--;
                    goto done;
                }
                prev = gen->stack.stack[gen->stack.sp-2];
                preg = Cudd_Regular(prev);
                nreg = cuddT(preg);
                if (prev != preg) {next = Cudd_Not(nreg);} else {next = nreg;}
                if (next != top) { /* follow the then branch next */
                    gen->gen.cubes.cube[preg->index] = 1;
                    gen->stack.stack[gen->stack.sp-1] = next;
                    break;
                }
                /* Pop the stack and try again. */
                gen->gen.cubes.cube[preg->index] = 2;
                gen->stack.sp--;
                top = gen->stack.stack[gen->stack.sp-1];
                treg = Cudd_Regular(top);
            }
        } else {
            gen->status = CUDD_GEN_NONEMPTY;
            gen->gen.cubes.value = cuddV(top);
            goto done;
Alan Mishchenko committed
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 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 1931 1932
        }
    }

done:
    *cube = gen->gen.cubes.cube;
    *value = gen->gen.cubes.value;
    return(gen);

} /* end of Cudd_FirstCube */


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

  Synopsis    [Generates the next cube of a decision diagram onset.]

  Description [Generates the next cube of a decision diagram onset,
  using generator gen. Returns 0 if the enumeration is completed; 1
  otherwise.]

  SideEffects [The cube and its value are returned as side effects. The
  generator is modified.]

  SeeAlso     [Cudd_ForeachCube Cudd_FirstCube Cudd_GenFree Cudd_IsGenEmpty
  Cudd_NextNode]

******************************************************************************/
int
Cudd_NextCube(
  DdGen * gen,
  int ** cube,
  CUDD_VALUE_TYPE * value)
{
    DdNode *top, *treg, *next, *nreg, *prev, *preg;
    DdManager *dd = gen->manager;

    /* Backtrack from previously reached terminal node. */
    while (1) {
        if (gen->stack.sp == 1) {
            /* The current node has no predecessor. */
            gen->status = CUDD_GEN_EMPTY;
            gen->stack.sp--;
            goto done;
        }
1933 1934
        top = gen->stack.stack[gen->stack.sp-1];
        treg = Cudd_Regular(top);
Alan Mishchenko committed
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
        prev = gen->stack.stack[gen->stack.sp-2];
        preg = Cudd_Regular(prev);
        nreg = cuddT(preg);
        if (prev != preg) {next = Cudd_Not(nreg);} else {next = nreg;}
        if (next != top) { /* follow the then branch next */
            gen->gen.cubes.cube[preg->index] = 1;
            gen->stack.stack[gen->stack.sp-1] = next;
            break;
        }
        /* Pop the stack and try again. */
        gen->gen.cubes.cube[preg->index] = 2;
        gen->stack.sp--;
1947 1948 1949
    }

    while (1) {
Alan Mishchenko committed
1950 1951
        top = gen->stack.stack[gen->stack.sp-1];
        treg = Cudd_Regular(top);
1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 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 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 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 2085 2086 2087 2088 2089 2090 2091 2092 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
        if (!cuddIsConstant(treg)) {
            /* Take the else branch first. */
            gen->gen.cubes.cube[treg->index] = 0;
            next = cuddE(treg);
            if (top != treg) next = Cudd_Not(next);
            gen->stack.stack[gen->stack.sp] = next; gen->stack.sp++;
        } else if (top == Cudd_Not(DD_ONE(dd)) || top == dd->background) {
            /* Backtrack */
            while (1) {
                if (gen->stack.sp == 1) {
                    /* The current node has no predecessor. */
                    gen->status = CUDD_GEN_EMPTY;
                    gen->stack.sp--;
                    goto done;
                }
                prev = gen->stack.stack[gen->stack.sp-2];
                preg = Cudd_Regular(prev);
                nreg = cuddT(preg);
                if (prev != preg) {next = Cudd_Not(nreg);} else {next = nreg;}
                if (next != top) { /* follow the then branch next */
                    gen->gen.cubes.cube[preg->index] = 1;
                    gen->stack.stack[gen->stack.sp-1] = next;
                    break;
                }
                /* Pop the stack and try again. */
                gen->gen.cubes.cube[preg->index] = 2;
                gen->stack.sp--;
                top = gen->stack.stack[gen->stack.sp-1];
                treg = Cudd_Regular(top);
            }
        } else {
            gen->status = CUDD_GEN_NONEMPTY;
            gen->gen.cubes.value = cuddV(top);
            goto done;
        }
    }

done:
    if (gen->status == CUDD_GEN_EMPTY) return(0);
    *cube = gen->gen.cubes.cube;
    *value = gen->gen.cubes.value;
    return(1);

} /* end of Cudd_NextCube */


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

  Synopsis    [Finds the first prime of a Boolean function.]

  Description [Defines an iterator on a pair of BDDs describing a
  (possibly incompletely specified) Boolean functions and finds the
  first cube of a cover of the function.  Returns a generator
  that contains the information necessary to continue the enumeration
  if successful; NULL otherwise.<p>

  The two argument BDDs are the lower and upper bounds of an interval.
  It is a mistake to call this function with a lower bound that is not
  less than or equal to the upper bound.<p>

  A cube is represented as an array of literals, which are integers in
  {0, 1, 2}; 0 represents a complemented literal, 1 represents an
  uncomplemented literal, and 2 stands for don't care. The enumeration
  produces a prime and irredundant cover of the function associated
  with the two BDDs.  The size of the array equals the number of
  variables in the manager at the time Cudd_FirstCube is called.<p>

  This iterator can only be used on BDDs.]

  SideEffects [The first cube is returned as side effect.]

  SeeAlso     [Cudd_ForeachPrime Cudd_NextPrime Cudd_GenFree Cudd_IsGenEmpty
  Cudd_FirstCube Cudd_FirstNode]

******************************************************************************/
DdGen *
Cudd_FirstPrime(
  DdManager *dd,
  DdNode *l,
  DdNode *u,
  int **cube)
{
    DdGen *gen;
    DdNode *implicant, *prime, *tmp;
    int length, result;

    /* Sanity Check. */
    if (dd == NULL || l == NULL || u == NULL) return(NULL);

    /* Allocate generator an initialize it. */
    gen = ABC_ALLOC(DdGen,1);
    if (gen == NULL) {
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
    }

    gen->manager = dd;
    gen->type = CUDD_GEN_PRIMES;
    gen->status = CUDD_GEN_EMPTY;
    gen->gen.primes.cube = NULL;
    gen->gen.primes.ub = u;
    gen->stack.sp = 0;
    gen->stack.stack = NULL;
    gen->node = l;
    cuddRef(l);

    gen->gen.primes.cube = ABC_ALLOC(int,dd->size);
    if (gen->gen.primes.cube == NULL) {
        dd->errorCode = CUDD_MEMORY_OUT;
        ABC_FREE(gen);
        return(NULL);
    }

    if (gen->node == Cudd_ReadLogicZero(dd)) {
        gen->status = CUDD_GEN_EMPTY;
    } else {
        implicant = Cudd_LargestCube(dd,gen->node,&length);
        if (implicant == NULL) {
            Cudd_RecursiveDeref(dd,gen->node);
            ABC_FREE(gen->gen.primes.cube);
            ABC_FREE(gen);
            return(NULL);
        }
        cuddRef(implicant);
        prime = Cudd_bddMakePrime(dd,implicant,gen->gen.primes.ub);
        if (prime == NULL) {
            Cudd_RecursiveDeref(dd,gen->node);
            Cudd_RecursiveDeref(dd,implicant);
            ABC_FREE(gen->gen.primes.cube);
            ABC_FREE(gen);
            return(NULL);
        }
        cuddRef(prime);
        Cudd_RecursiveDeref(dd,implicant);
        tmp = Cudd_bddAnd(dd,gen->node,Cudd_Not(prime));
        if (tmp == NULL) {
            Cudd_RecursiveDeref(dd,gen->node);
            Cudd_RecursiveDeref(dd,prime);
            ABC_FREE(gen->gen.primes.cube);
            ABC_FREE(gen);
            return(NULL);
        }
        cuddRef(tmp);
        Cudd_RecursiveDeref(dd,gen->node);
        gen->node = tmp;
        result = Cudd_BddToCubeArray(dd,prime,gen->gen.primes.cube);
        if (result == 0) {
            Cudd_RecursiveDeref(dd,gen->node);
            Cudd_RecursiveDeref(dd,prime);
            ABC_FREE(gen->gen.primes.cube);
            ABC_FREE(gen);
            return(NULL);
        }
        Cudd_RecursiveDeref(dd,prime);
        gen->status = CUDD_GEN_NONEMPTY;
    }
    *cube = gen->gen.primes.cube;
    return(gen);

} /* end of Cudd_FirstPrime */


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

  Synopsis    [Generates the next prime of a Boolean function.]

  Description [Generates the next cube of a Boolean function,
  using generator gen. Returns 0 if the enumeration is completed; 1
  otherwise.]

  SideEffects [The cube and is returned as side effects. The
  generator is modified.]

  SeeAlso     [Cudd_ForeachPrime Cudd_FirstPrime Cudd_GenFree Cudd_IsGenEmpty
  Cudd_NextCube Cudd_NextNode]

******************************************************************************/
int
Cudd_NextPrime(
  DdGen *gen,
  int **cube)
{
    DdNode *implicant, *prime, *tmp;
    DdManager *dd = gen->manager;
    int length, result;

    if (gen->node == Cudd_ReadLogicZero(dd)) {
        gen->status = CUDD_GEN_EMPTY;
    } else {
        implicant = Cudd_LargestCube(dd,gen->node,&length);
        if (implicant == NULL) {
            gen->status = CUDD_GEN_EMPTY;
            return(0);
        }
        cuddRef(implicant);
        prime = Cudd_bddMakePrime(dd,implicant,gen->gen.primes.ub);
        if (prime == NULL) {
            Cudd_RecursiveDeref(dd,implicant);
            gen->status = CUDD_GEN_EMPTY;
            return(0);
        }
        cuddRef(prime);
        Cudd_RecursiveDeref(dd,implicant);
        tmp = Cudd_bddAnd(dd,gen->node,Cudd_Not(prime));
        if (tmp == NULL) {
            Cudd_RecursiveDeref(dd,prime);
            gen->status = CUDD_GEN_EMPTY;
            return(0);
        }
        cuddRef(tmp);
        Cudd_RecursiveDeref(dd,gen->node);
        gen->node = tmp;
        result = Cudd_BddToCubeArray(dd,prime,gen->gen.primes.cube);
        if (result == 0) {
            Cudd_RecursiveDeref(dd,prime);
            gen->status = CUDD_GEN_EMPTY;
            return(0);
Alan Mishchenko committed
2169
        }
2170
        Cudd_RecursiveDeref(dd,prime);
Alan Mishchenko committed
2171 2172 2173
        gen->status = CUDD_GEN_NONEMPTY;
    }
    if (gen->status == CUDD_GEN_EMPTY) return(0);
2174
    *cube = gen->gen.primes.cube;
Alan Mishchenko committed
2175 2176
    return(1);

2177
} /* end of Cudd_NextPrime */
Alan Mishchenko committed
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201


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

  Synopsis    [Computes the cube of an array of BDD variables.]

  Description [Computes the cube of an array of BDD variables. If
  non-null, the phase argument indicates which literal of each
  variable should appear in the cube. If phase\[i\] is nonzero, then the
  positive literal is used. If phase is NULL, the cube is positive unate.
  Returns a pointer to the result if successful; NULL otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_addComputeCube Cudd_IndicesToCube Cudd_CubeArrayToBdd]

******************************************************************************/
DdNode *
Cudd_bddComputeCube(
  DdManager * dd,
  DdNode ** vars,
  int * phase,
  int  n)
{
2202 2203
    DdNode      *cube;
    DdNode      *fn;
Alan Mishchenko committed
2204 2205 2206 2207 2208 2209
    int         i;

    cube = DD_ONE(dd);
    cuddRef(cube);

    for (i = n - 1; i >= 0; i--) {
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
        if (phase == NULL || phase[i] != 0) {
            fn = Cudd_bddAnd(dd,vars[i],cube);
        } else {
            fn = Cudd_bddAnd(dd,Cudd_Not(vars[i]),cube);
        }
        if (fn == NULL) {
            Cudd_RecursiveDeref(dd,cube);
            return(NULL);
        }
        cuddRef(fn);
Alan Mishchenko committed
2220
        Cudd_RecursiveDeref(dd,cube);
2221
        cube = fn;
Alan Mishchenko committed
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
    }
    cuddDeref(cube);

    return(cube);

}  /* end of Cudd_bddComputeCube */


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

  Synopsis    [Computes the cube of an array of ADD variables.]

  Description [Computes the cube of an array of ADD variables.  If
  non-null, the phase argument indicates which literal of each
  variable should appear in the cube. If phase\[i\] is nonzero, then the
  positive literal is used. If phase is NULL, the cube is positive unate.
  Returns a pointer to the result if successful; NULL otherwise.]

  SideEffects [none]

  SeeAlso     [Cudd_bddComputeCube]

******************************************************************************/
DdNode *
Cudd_addComputeCube(
  DdManager * dd,
  DdNode ** vars,
  int * phase,
  int  n)
{
2252 2253
    DdNode      *cube, *zero;
    DdNode      *fn;
Alan Mishchenko committed
2254 2255 2256 2257 2258 2259 2260
    int         i;

    cube = DD_ONE(dd);
    cuddRef(cube);
    zero = DD_ZERO(dd);

    for (i = n - 1; i >= 0; i--) {
2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
        if (phase == NULL || phase[i] != 0) {
            fn = Cudd_addIte(dd,vars[i],cube,zero);
        } else {
            fn = Cudd_addIte(dd,vars[i],zero,cube);
        }
        if (fn == NULL) {
            Cudd_RecursiveDeref(dd,cube);
            return(NULL);
        }
        cuddRef(fn);
Alan Mishchenko committed
2271
        Cudd_RecursiveDeref(dd,cube);
2272
        cube = fn;
Alan Mishchenko committed
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
    }
    cuddDeref(cube);

    return(cube);

} /* end of Cudd_addComputeCube */


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

  Synopsis    [Builds the BDD of a cube from a positional array.]

  Description [Builds a cube from a positional array.  The array must
  have one integer entry for each BDD variable.  If the i-th entry is
  1, the variable of index i appears in true form in the cube; If the
  i-th entry is 0, the variable of index i appears complemented in the
  cube; otherwise the variable does not appear in the cube.  Returns a
  pointer to the BDD for the cube if successful; NULL otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_bddComputeCube Cudd_IndicesToCube Cudd_BddToCubeArray]

******************************************************************************/
DdNode *
Cudd_CubeArrayToBdd(
  DdManager *dd,
  int *array)
{
    DdNode *cube, *var, *tmp;
    int i;
    int size = Cudd_ReadSize(dd);

    cube = DD_ONE(dd);
    cuddRef(cube);
    for (i = size - 1; i >= 0; i--) {
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
        if ((array[i] & ~1) == 0) {
            var = Cudd_bddIthVar(dd,i);
            tmp = Cudd_bddAnd(dd,cube,Cudd_NotCond(var,array[i]==0));
            if (tmp == NULL) {
                Cudd_RecursiveDeref(dd,cube);
                return(NULL);
            }
            cuddRef(tmp);
            Cudd_RecursiveDeref(dd,cube);
            cube = tmp;
Alan Mishchenko committed
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
        }
    }
    cuddDeref(cube);
    return(cube);

} /* end of Cudd_CubeArrayToBdd */


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

  Synopsis    [Builds a positional array from the BDD of a cube.]

  Description [Builds a positional array from the BDD of a cube.
  Array must have one entry for each BDD variable.  The positional
  array has 1 in i-th position if the variable of index i appears in
  true form in the cube; it has 0 in i-th position if the variable of
  index i appears in complemented form in the cube; finally, it has 2
  in i-th position if the variable of index i does not appear in the
  cube.  Returns 1 if successful (the BDD is indeed a cube); 0
  otherwise.]

  SideEffects [The result is in the array passed by reference.]

  SeeAlso     [Cudd_CubeArrayToBdd]

******************************************************************************/
int
Cudd_BddToCubeArray(
  DdManager *dd,
  DdNode *cube,
  int *array)
{
    DdNode *scan, *t, *e;
    int i;
    int size = Cudd_ReadSize(dd);
    DdNode *zero = Cudd_Not(DD_ONE(dd));

    for (i = size-1; i >= 0; i--) {
2357
        array[i] = 2;
Alan Mishchenko committed
2358 2359 2360
    }
    scan = cube;
    while (!Cudd_IsConstant(scan)) {
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
        int index = Cudd_Regular(scan)->index;
        cuddGetBranches(scan,&t,&e);
        if (t == zero) {
            array[index] = 0;
            scan = e;
        } else if (e == zero) {
            array[index] = 1;
            scan = t;
        } else {
            return(0);  /* cube is not a cube */
        }
Alan Mishchenko committed
2372 2373
    }
    if (scan == zero) {
2374
        return(0);
Alan Mishchenko committed
2375
    } else {
2376
        return(1);
Alan Mishchenko committed
2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387
    }

} /* end of Cudd_BddToCubeArray */


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

  Synopsis    [Finds the first node of a decision diagram.]

  Description [Defines an iterator on the nodes of a decision diagram
  and finds its first node. Returns a generator that contains the
2388 2389 2390 2391
  information necessary to continue the enumeration if successful;
  NULL otherwise.  The nodes are enumerated in a reverse topological
  order, so that a node is always preceded in the enumeration by its
  descendants.]
Alan Mishchenko committed
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405

  SideEffects [The first node is returned as a side effect.]

  SeeAlso     [Cudd_ForeachNode Cudd_NextNode Cudd_GenFree Cudd_IsGenEmpty
  Cudd_FirstCube]

******************************************************************************/
DdGen *
Cudd_FirstNode(
  DdManager * dd,
  DdNode * f,
  DdNode ** node)
{
    DdGen *gen;
2406
    int size;
Alan Mishchenko committed
2407 2408 2409 2410 2411

    /* Sanity Check. */
    if (dd == NULL || f == NULL) return(NULL);

    /* Allocate generator an initialize it. */
Alan Mishchenko committed
2412
    gen = ABC_ALLOC(DdGen,1);
Alan Mishchenko committed
2413
    if (gen == NULL) {
2414 2415
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
Alan Mishchenko committed
2416 2417 2418 2419 2420 2421 2422 2423
    }

    gen->manager = dd;
    gen->type = CUDD_GEN_NODES;
    gen->status = CUDD_GEN_EMPTY;
    gen->stack.sp = 0;
    gen->node = NULL;

2424 2425 2426 2427 2428 2429
    /* Collect all the nodes on the generator stack for later perusal. */
    gen->stack.stack = cuddNodeArray(Cudd_Regular(f), &size);
    if (gen->stack.stack == NULL) {
        ABC_FREE(gen);
        dd->errorCode = CUDD_MEMORY_OUT;
        return(NULL);
Alan Mishchenko committed
2430
    }
2431
    gen->gen.nodes.size = size;
Alan Mishchenko committed
2432 2433

    /* Find the first node. */
2434 2435 2436 2437
    if (gen->stack.sp < gen->gen.nodes.size) {
        gen->status = CUDD_GEN_NONEMPTY;
        gen->node = gen->stack.stack[gen->stack.sp];
        *node = gen->node;
Alan Mishchenko committed
2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
    }

    return(gen);

} /* end of Cudd_FirstNode */


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

  Synopsis    [Finds the next node of a decision diagram.]

  Description [Finds the node of a decision diagram, using generator
  gen. Returns 0 if the enumeration is completed; 1 otherwise.]

  SideEffects [The next node is returned as a side effect.]

  SeeAlso     [Cudd_ForeachNode Cudd_FirstNode Cudd_GenFree Cudd_IsGenEmpty
  Cudd_NextCube]

******************************************************************************/
int
Cudd_NextNode(
  DdGen * gen,
  DdNode ** node)
{
    /* Find the next node. */
2464 2465 2466 2467 2468
    gen->stack.sp++;
    if (gen->stack.sp < gen->gen.nodes.size) {
        gen->node = gen->stack.stack[gen->stack.sp];
        *node = gen->node;
        return(1);
Alan Mishchenko committed
2469
    } else {
2470 2471
        gen->status = CUDD_GEN_EMPTY;
        return(0);
Alan Mishchenko committed
2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497
    }

} /* end of Cudd_NextNode */


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

  Synopsis    [Frees a CUDD generator.]

  Description [Frees a CUDD generator. Always returns 0, so that it can
  be used in mis-like foreach constructs.]

  SideEffects [None]

  SeeAlso     [Cudd_ForeachCube Cudd_ForeachNode Cudd_FirstCube Cudd_NextCube
  Cudd_FirstNode Cudd_NextNode Cudd_IsGenEmpty]

******************************************************************************/
int
Cudd_GenFree(
  DdGen * gen)
{
    if (gen == NULL) return(0);
    switch (gen->type) {
    case CUDD_GEN_CUBES:
    case CUDD_GEN_ZDD_PATHS:
2498 2499 2500 2501 2502 2503 2504
        ABC_FREE(gen->gen.cubes.cube);
        ABC_FREE(gen->stack.stack);
        break;
    case CUDD_GEN_PRIMES:
        ABC_FREE(gen->gen.primes.cube);
        Cudd_RecursiveDeref(gen->manager,gen->node);
        break;
Alan Mishchenko committed
2505
    case CUDD_GEN_NODES:
2506 2507
        ABC_FREE(gen->stack.stack);
        break;
Alan Mishchenko committed
2508
    default:
2509
        return(0);
Alan Mishchenko committed
2510
    }
Alan Mishchenko committed
2511
    ABC_FREE(gen);
Alan Mishchenko committed
2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563
    return(0);

} /* end of Cudd_GenFree */


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

  Synopsis    [Queries the status of a generator.]

  Description [Queries the status of a generator. Returns 1 if the
  generator is empty or NULL; 0 otherswise.]

  SideEffects [None]

  SeeAlso     [Cudd_ForeachCube Cudd_ForeachNode Cudd_FirstCube Cudd_NextCube
  Cudd_FirstNode Cudd_NextNode Cudd_GenFree]

******************************************************************************/
int
Cudd_IsGenEmpty(
  DdGen * gen)
{
    if (gen == NULL) return(1);
    return(gen->status == CUDD_GEN_EMPTY);

} /* end of Cudd_IsGenEmpty */


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

  Synopsis    [Builds a cube of BDD variables from an array of indices.]

  Description [Builds a cube of BDD variables from an array of indices.
  Returns a pointer to the result if successful; NULL otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_bddComputeCube Cudd_CubeArrayToBdd]

******************************************************************************/
DdNode *
Cudd_IndicesToCube(
  DdManager * dd,
  int * array,
  int  n)
{
    DdNode *cube, *tmp;
    int i;

    cube = DD_ONE(dd);
    cuddRef(cube);
    for (i = n - 1; i >= 0; i--) {
2564 2565 2566 2567 2568 2569
        tmp = Cudd_bddAnd(dd,Cudd_bddIthVar(dd,array[i]),cube);
        if (tmp == NULL) {
            Cudd_RecursiveDeref(dd,cube);
            return(NULL);
        }
        cuddRef(tmp);
Alan Mishchenko committed
2570
        Cudd_RecursiveDeref(dd,cube);
2571
        cube = tmp;
Alan Mishchenko committed
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637
    }

    cuddDeref(cube);
    return(cube);

} /* end of Cudd_IndicesToCube */


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

  Synopsis    [Prints the package version number.]

  Description []

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
void
Cudd_PrintVersion(
  FILE * fp)
{
    (void) fprintf(fp, "%s\n", CUDD_VERSION);

} /* end of Cudd_PrintVersion */


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

  Synopsis    [Computes the average distance between adjacent nodes.]

  Description [Computes the average distance between adjacent nodes in
  the manager. Adjacent nodes are node pairs such that the second node
  is the then child, else child, or next node in the collision list.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
double
Cudd_AverageDistance(
  DdManager * dd)
{
    double tetotal, nexttotal;
    double tesubtotal, nextsubtotal;
    double temeasured, nextmeasured;
    int i, j;
    int slots, nvars;
    long diff;
    DdNode *scan;
    DdNodePtr *nodelist;
    DdNode *sentinel = &(dd->sentinel);

    nvars = dd->size;
    if (nvars == 0) return(0.0);

    /* Initialize totals. */
    tetotal = 0.0;
    nexttotal = 0.0;
    temeasured = 0.0;
    nextmeasured = 0.0;

    /* Scan the variable subtables. */
    for (i = 0; i < nvars; i++) {
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656
        nodelist = dd->subtables[i].nodelist;
        tesubtotal = 0.0;
        nextsubtotal = 0.0;
        slots = dd->subtables[i].slots;
        for (j = 0; j < slots; j++) {
            scan = nodelist[j];
            while (scan != sentinel) {
                diff = (long) scan - (long) cuddT(scan);
                tesubtotal += (double) ddAbs(diff);
                diff = (long) scan - (long) Cudd_Regular(cuddE(scan));
                tesubtotal += (double) ddAbs(diff);
                temeasured += 2.0;
                if (scan->next != sentinel) {
                    diff = (long) scan - (long) scan->next;
                    nextsubtotal += (double) ddAbs(diff);
                    nextmeasured += 1.0;
                }
                scan = scan->next;
            }
Alan Mishchenko committed
2657
        }
2658 2659
        tetotal += tesubtotal;
        nexttotal += nextsubtotal;
Alan Mishchenko committed
2660 2661 2662 2663 2664 2665 2666
    }

    /* Scan the constant table. */
    nodelist = dd->constants.nodelist;
    nextsubtotal = 0.0;
    slots = dd->constants.slots;
    for (j = 0; j < slots; j++) {
2667 2668 2669 2670 2671 2672 2673 2674
        scan = nodelist[j];
        while (scan != NULL) {
            if (scan->next != NULL) {
                diff = (long) scan - (long) scan->next;
                nextsubtotal += (double) ddAbs(diff);
                nextmeasured += 1.0;
            }
            scan = scan->next;
Alan Mishchenko committed
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701
        }
    }
    nexttotal += nextsubtotal;

    return((tetotal + nexttotal) / (temeasured + nextmeasured));

} /* end of Cudd_AverageDistance */


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

  Synopsis    [Portable random number generator.]

  Description [Portable number generator based on ran2 from "Numerical
  Recipes in C." It is a long period (> 2 * 10^18) random number generator
  of L'Ecuyer with Bays-Durham shuffle. Returns a long integer uniformly
  distributed between 0 and 2147483561 (inclusive of the endpoint values).
  The random generator can be explicitly initialized by calling
  Cudd_Srandom. If no explicit initialization is performed, then the
  seed 1 is assumed.]

  SideEffects [None]

  SeeAlso     [Cudd_Srandom]

******************************************************************************/
long
2702
Cudd_Random(void)
Alan Mishchenko committed
2703
{
2704
    int i;      /* index in the shuffle table */
Alan Mishchenko committed
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774
    long int w; /* work variable */

    /* cuddRand == 0 if the geneartor has not been initialized yet. */
    if (cuddRand == 0) Cudd_Srandom(1);

    /* Compute cuddRand = (cuddRand * LEQA1) % MODULUS1 avoiding
    ** overflows by Schrage's method.
    */
    w          = cuddRand / LEQQ1;
    cuddRand   = LEQA1 * (cuddRand - w * LEQQ1) - w * LEQR1;
    cuddRand  += (cuddRand < 0) * MODULUS1;

    /* Compute cuddRand2 = (cuddRand2 * LEQA2) % MODULUS2 avoiding
    ** overflows by Schrage's method.
    */
    w          = cuddRand2 / LEQQ2;
    cuddRand2  = LEQA2 * (cuddRand2 - w * LEQQ2) - w * LEQR2;
    cuddRand2 += (cuddRand2 < 0) * MODULUS2;

    /* cuddRand is shuffled with the Bays-Durham algorithm.
    ** shuffleSelect and cuddRand2 are combined to generate the output.
    */

    /* Pick one element from the shuffle table; "i" will be in the range
    ** from 0 to STAB_SIZE-1.
    */
    i = (int) (shuffleSelect / STAB_DIV);
    /* Mix the element of the shuffle table with the current iterate of
    ** the second sub-generator, and replace the chosen element of the
    ** shuffle table with the current iterate of the first sub-generator.
    */
    shuffleSelect   = shuffleTable[i] - cuddRand2;
    shuffleTable[i] = cuddRand;
    shuffleSelect  += (shuffleSelect < 1) * (MODULUS1 - 1);
    /* Since shuffleSelect != 0, and we want to be able to return 0,
    ** here we subtract 1 before returning.
    */
    return(shuffleSelect - 1);

} /* end of Cudd_Random */


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

  Synopsis    [Initializer for the portable random number generator.]

  Description [Initializer for the portable number generator based on
  ran2 in "Numerical Recipes in C." The input is the seed for the
  generator. If it is negative, its absolute value is taken as seed.
  If it is 0, then 1 is taken as seed. The initialized sets up the two
  recurrences used to generate a long-period stream, and sets up the
  shuffle table.]

  SideEffects [None]

  SeeAlso     [Cudd_Random]

******************************************************************************/
void
Cudd_Srandom(
  long  seed)
{
    int i;

    if (seed < 0)       cuddRand = -seed;
    else if (seed == 0) cuddRand = 1;
    else                cuddRand = seed;
    cuddRand2 = cuddRand;
    /* Load the shuffle table (after 11 warm-ups). */
    for (i = 0; i < STAB_SIZE + 11; i++) {
2775 2776 2777 2778 2779
        long int w;
        w = cuddRand / LEQQ1;
        cuddRand = LEQA1 * (cuddRand - w * LEQQ1) - w * LEQR1;
        cuddRand += (cuddRand < 0) * MODULUS1;
        shuffleTable[i % STAB_SIZE] = cuddRand;
Alan Mishchenko committed
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
    }
    shuffleSelect = shuffleTable[1 % STAB_SIZE];

} /* end of Cudd_Srandom */


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

  Synopsis    [Computes the density of a BDD or ADD.]

  Description [Computes the density of a BDD or ADD. The density is
  the ratio of the number of minterms to the number of nodes. If 0 is
  passed as number of variables, the number of variables existing in
  the manager is used. Returns the density if successful; (double)
  CUDD_OUT_OF_MEM otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_CountMinterm Cudd_DagSize]

******************************************************************************/
double
Cudd_Density(
  DdManager * dd /* manager */,
  DdNode * f /* function whose density is sought */,
  int  nvars /* size of the support of f */)
{
    double minterms;
    int nodes;
    double density;

    if (nvars == 0) nvars = dd->size;
    minterms = Cudd_CountMinterm(dd,f,nvars);
    if (minterms == (double) CUDD_OUT_OF_MEM) return(minterms);
    nodes = Cudd_DagSize(f);
    density = minterms / (double) nodes;
    return(density);

} /* end of Cudd_Density */


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

  Synopsis    [Warns that a memory allocation failed.]

  Description [Warns that a memory allocation failed.
  This function can be used as replacement of MMout_of_memory to prevent
  the safe_mem functions of the util package from exiting when malloc
  returns NULL. One possible use is in case of discretionary allocations;
  for instance, the allocation of memory to enlarge the computed table.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
void
Cudd_OutOfMem(
  long size /* size of the allocation that failed */)
{
    (void) fflush(stdout);
    (void) fprintf(stderr, "\nunable to allocate %ld bytes\n", size);
    return;

} /* end of Cudd_OutOfMem */


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


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

  Synopsis    [Prints a DD to the standard output. One line per node is
  printed.]

  Description [Prints a DD to the standard output. One line per node is
  printed. Returns 1 if successful; 0 otherwise.]

  SideEffects [None]

  SeeAlso     [Cudd_PrintDebug]

******************************************************************************/
int
cuddP(
  DdManager * dd,
  DdNode * f)
{
    int retval;
2871
    st_table *table = st_init_table(st_ptrcmp,st_ptrhash);
Alan Mishchenko committed
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899

    if (table == NULL) return(0);

    retval = dp2(dd,f,table);
    st_free_table(table);
    (void) fputc('\n',dd->out);
    return(retval);

} /* end of cuddP */


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

  Synopsis [Frees the memory used to store the minterm counts recorded
  in the visited table.]

  Description [Frees the memory used to store the minterm counts
  recorded in the visited table. Returns ST_CONTINUE.]

  SideEffects [None]

******************************************************************************/
enum st_retval
cuddStCountfree(
  char * key,
  char * value,
  char * arg)
{
2900
    double      *d;
Alan Mishchenko committed
2901 2902

    d = (double *)value;
Alan Mishchenko committed
2903
    ABC_FREE(d);
Alan Mishchenko committed
2904 2905 2906 2907 2908 2909 2910 2911 2912 2913
    return(ST_CONTINUE);

} /* end of cuddStCountfree */


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

  Synopsis    [Recursively collects all the nodes of a DD in a symbol
  table.]

2914
  Description [Traverses the DD f and collects all its nodes in a
Alan Mishchenko committed
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928
  symbol table.  f is assumed to be a regular pointer and
  cuddCollectNodes guarantees this assumption in the recursive calls.
  Returns 1 in case of success; 0 otherwise.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
int
cuddCollectNodes(
  DdNode * f,
  st_table * visited)
{
2929 2930
    DdNode      *T, *E;
    int         retval;
Alan Mishchenko committed
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949

#ifdef DD_DEBUG
    assert(!Cudd_IsComplement(f));
#endif

    /* If already visited, nothing to do. */
    if (st_is_member(visited, (char *) f) == 1)
        return(1);

    /* Check for abnormal condition that should never happen. */
    if (f == NULL)
        return(0);

    /* Mark node as visited. */
    if (st_add_direct(visited, (char *) f, NULL) == ST_OUT_OF_MEM)
        return(0);

    /* Check terminal case. */
    if (cuddIsConstant(f))
2950
        return(1);
Alan Mishchenko committed
2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962

    /* Recursive calls. */
    T = cuddT(f);
    retval = cuddCollectNodes(T,visited);
    if (retval != 1) return(retval);
    E = Cudd_Regular(cuddE(f));
    retval = cuddCollectNodes(E,visited);
    return(retval);

} /* end of cuddCollectNodes */


2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001
/**Function********************************************************************

  Synopsis    [Recursively collects all the nodes of a DD in an array.]

  Description [Traverses the DD f and collects all its nodes in an array.
  The caller should free the array returned by cuddNodeArray.
  Returns a pointer to the array of nodes in case of success; NULL
  otherwise.  The nodes are collected in reverse topological order, so
  that a node is always preceded in the array by all its descendants.]

  SideEffects [The number of nodes is returned as a side effect.]

  SeeAlso     [Cudd_FirstNode]

******************************************************************************/
DdNodePtr *
cuddNodeArray(
  DdNode *f,
  int *n)
{
    DdNodePtr *table;
    int size, retval;

    size = ddDagInt(Cudd_Regular(f));
    table = ABC_ALLOC(DdNodePtr, size);
    if (table == NULL) {
        ddClearFlag(Cudd_Regular(f));
        return(NULL);
    }

    retval = cuddNodeArrayRecur(f, table, 0);
    assert(retval == size);

    *n = size;
    return(table);

} /* cuddNodeArray */


Alan Mishchenko committed
3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
/*---------------------------------------------------------------------------*/
/* Definition of static functions                                            */
/*---------------------------------------------------------------------------*/


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

  Synopsis    [Performs the recursive step of cuddP.]

  Description [Performs the recursive step of cuddP. Returns 1 in case
  of success; 0 otherwise.]

  SideEffects [None]

******************************************************************************/
static int
dp2(
  DdManager *dd,
  DdNode * f,
  st_table * t)
{
    DdNode *g, *n, *N;
    int T,E;
3025

Alan Mishchenko committed
3026 3027 3028 3029 3030 3031 3032
    if (f == NULL) {
        return(0);
    }
    g = Cudd_Regular(f);
    if (cuddIsConstant(g)) {
#if SIZEOF_VOID_P == 8
        (void) fprintf(dd->out,"ID = %c0x%lx\tvalue = %-9g\n", bang(f),
3033
                (ptruint) g / (ptruint) sizeof(DdNode),cuddV(g));
Alan Mishchenko committed
3034 3035
#else
        (void) fprintf(dd->out,"ID = %c0x%x\tvalue = %-9g\n", bang(f),
3036
                (ptruint) g / (ptruint) sizeof(DdNode),cuddV(g));
Alan Mishchenko committed
3037
#endif
3038
        return(1);
Alan Mishchenko committed
3039 3040 3041 3042 3043
    }
    if (st_is_member(t,(char *) g) == 1) {
        return(1);
    }
    if (st_add_direct(t,(char *) g,NULL) == ST_OUT_OF_MEM)
3044
        return(0);
Alan Mishchenko committed
3045 3046 3047
#ifdef DD_STATS
#if SIZEOF_VOID_P == 8
    (void) fprintf(dd->out,"ID = %c0x%lx\tindex = %d\tr = %d\t", bang(f),
3048
                (ptruint) g / (ptruint) sizeof(DdNode), g->index, g->ref);
Alan Mishchenko committed
3049 3050
#else
    (void) fprintf(dd->out,"ID = %c0x%x\tindex = %d\tr = %d\t", bang(f),
3051
                (ptruint) g / (ptruint) sizeof(DdNode),g->index,g->ref);
Alan Mishchenko committed
3052 3053 3054
#endif
#else
#if SIZEOF_VOID_P == 8
3055 3056
    (void) fprintf(dd->out,"ID = %c0x%lx\tindex = %u\t", bang(f),
                (ptruint) g / (ptruint) sizeof(DdNode),g->index);
Alan Mishchenko committed
3057
#else
3058 3059
    (void) fprintf(dd->out,"ID = %c0x%x\tindex = %hu\t", bang(f),
                (ptruint) g / (ptruint) sizeof(DdNode),g->index);
Alan Mishchenko committed
3060 3061 3062 3063 3064
#endif
#endif
    n = cuddT(g);
    if (cuddIsConstant(n)) {
        (void) fprintf(dd->out,"T = %-9g\t",cuddV(n));
3065
        T = 1;
Alan Mishchenko committed
3066 3067
    } else {
#if SIZEOF_VOID_P == 8
3068
        (void) fprintf(dd->out,"T = 0x%lx\t",(ptruint) n / (ptruint) sizeof(DdNode));
Alan Mishchenko committed
3069
#else
3070
        (void) fprintf(dd->out,"T = 0x%x\t",(ptruint) n / (ptruint) sizeof(DdNode));
Alan Mishchenko committed
3071
#endif
3072
        T = 0;
Alan Mishchenko committed
3073 3074 3075 3076 3077 3078
    }

    n = cuddE(g);
    N = Cudd_Regular(n);
    if (cuddIsConstant(N)) {
        (void) fprintf(dd->out,"E = %c%-9g\n",bang(n),cuddV(N));
3079
        E = 1;
Alan Mishchenko committed
3080 3081
    } else {
#if SIZEOF_VOID_P == 8
3082
        (void) fprintf(dd->out,"E = %c0x%lx\n", bang(n), (ptruint) N/(ptruint) sizeof(DdNode));
Alan Mishchenko committed
3083
#else
3084
        (void) fprintf(dd->out,"E = %c0x%x\n", bang(n), (ptruint) N/(ptruint) sizeof(DdNode));
Alan Mishchenko committed
3085
#endif
3086
        E = 0;
Alan Mishchenko committed
3087 3088 3089
    }
    if (E == 0) {
        if (dp2(dd,N,t) == 0)
3090
            return(0);
Alan Mishchenko committed
3091 3092 3093
    }
    if (T == 0) {
        if (dp2(dd,cuddT(g),t) == 0)
3094
            return(0);
Alan Mishchenko committed
3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115
    }
    return(1);

} /* end of dp2 */


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

  Synopsis    [Performs the recursive step of Cudd_PrintMinterm.]

  Description []

  SideEffects [None]

******************************************************************************/
static void
ddPrintMintermAux(
  DdManager * dd /* manager */,
  DdNode * node /* current node */,
  int * list /* current recursion path */)
{
3116 3117
    DdNode      *N,*Nv,*Nnv;
    int         i,v,index;
Alan Mishchenko committed
3118 3119 3120 3121

    N = Cudd_Regular(node);

    if (cuddIsConstant(N)) {
3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133
        /* Terminal case: Print one cube based on the current recursion
        ** path, unless we have reached the background value (ADDs) or
        ** the logical zero (BDDs).
        */
        if (node != background && node != zero) {
            for (i = 0; i < dd->size; i++) {
                v = list[i];
                if (v == 0) (void) fprintf(dd->out,"0");
                else if (v == 1) (void) fprintf(dd->out,"1");
                else (void) fprintf(dd->out,"-");
            }
            (void) fprintf(dd->out," % g\n", cuddV(node));
Alan Mishchenko committed
3134 3135
        }
    } else {
3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147
        Nv  = cuddT(N);
        Nnv = cuddE(N);
        if (Cudd_IsComplement(node)) {
            Nv  = Cudd_Not(Nv);
            Nnv = Cudd_Not(Nnv);
        }
        index = N->index;
        list[index] = 0;
        ddPrintMintermAux(dd,Nnv,list);
        list[index] = 1;
        ddPrintMintermAux(dd,Nv,list);
        list[index] = 2;
Alan Mishchenko committed
3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170
    }
    return;

} /* end of ddPrintMintermAux */


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

  Synopsis    [Performs the recursive step of Cudd_DagSize.]

  Description [Performs the recursive step of Cudd_DagSize. Returns the
  number of nodes in the graph rooted at n.]

  SideEffects [None]

******************************************************************************/
static int
ddDagInt(
  DdNode * n)
{
    int tval, eval;

    if (Cudd_IsComplement(n->next)) {
3171
        return(0);
Alan Mishchenko committed
3172 3173 3174
    }
    n->next = Cudd_Not(n->next);
    if (cuddIsConstant(n)) {
3175
        return(1);
Alan Mishchenko committed
3176 3177 3178 3179 3180 3181 3182 3183 3184 3185
    }
    tval = ddDagInt(cuddT(n));
    eval = ddDagInt(Cudd_Regular(cuddE(n)));
    return(1 + tval + eval);

} /* end of ddDagInt */


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

3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225
  Synopsis    [Performs the recursive step of cuddNodeArray.]

  Description [Performs the recursive step of cuddNodeArray.  Returns
  an the number of nodes in the DD.  Clear the least significant bit
  of the next field that was used as visited flag by
  cuddNodeArrayRecur when counting the nodes.  node is supposed to be
  regular; the invariant is maintained by this procedure.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
cuddNodeArrayRecur(
  DdNode *f,
  DdNodePtr *table,
  int index)
{
    int tindex, eindex;

    if (!Cudd_IsComplement(f->next)) {
        return(index);
    }
    /* Clear visited flag. */
    f->next = Cudd_Regular(f->next);
    if (cuddIsConstant(f)) {
        table[index] = f;
        return(index + 1);
    }
    tindex = cuddNodeArrayRecur(cuddT(f), table, index);
    eindex = cuddNodeArrayRecur(Cudd_Regular(cuddE(f)), table, tindex);
    table[eindex] = f;
    return(eindex + 1);

} /* end of cuddNodeArrayRecur */


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

Alan Mishchenko committed
3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
  Synopsis    [Performs the recursive step of Cudd_CofactorEstimate.]

  Description [Performs the recursive step of Cudd_CofactorEstimate.
  Returns an estimate of the number of nodes in the DD of a
  cofactor of node. Uses the least significant bit of the next field as
  visited flag. node is supposed to be regular; the invariant is maintained
  by this procedure.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
cuddEstimateCofactor(
  DdManager *dd,
  st_table *table,
  DdNode * node,
  int i,
  int phase,
  DdNode ** ptr)
{
    int tval, eval, val;
    DdNode *ptrT, *ptrE;

    if (Cudd_IsComplement(node->next)) {
3252 3253 3254 3255 3256 3257 3258
        if (!st_lookup(table,(char *)node,(char **)ptr)) {
            if (st_add_direct(table,(char *)node,(char *)node) ==
                ST_OUT_OF_MEM)
                return(CUDD_OUT_OF_MEM);
            *ptr = node;
        }
        return(0);
Alan Mishchenko committed
3259 3260 3261
    }
    node->next = Cudd_Not(node->next);
    if (cuddIsConstant(node)) {
3262 3263 3264 3265
        *ptr = node;
        if (st_add_direct(table,(char *)node,(char *)node) == ST_OUT_OF_MEM)
            return(CUDD_OUT_OF_MEM);
        return(1);
Alan Mishchenko committed
3266 3267
    }
    if ((int) node->index == i) {
3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280
        if (phase == 1) {
            *ptr = cuddT(node);
            val = ddDagInt(cuddT(node));
        } else {
            *ptr = cuddE(node);
            val = ddDagInt(Cudd_Regular(cuddE(node)));
        }
        if (node->ref > 1) {
            if (st_add_direct(table,(char *)node,(char *)*ptr) ==
                ST_OUT_OF_MEM)
                return(CUDD_OUT_OF_MEM);
        }
        return(val);
Alan Mishchenko committed
3281 3282
    }
    if (dd->perm[node->index] > dd->perm[i]) {
3283 3284 3285 3286 3287 3288 3289 3290 3291 3292
        *ptr = node;
        tval = ddDagInt(cuddT(node));
        eval = ddDagInt(Cudd_Regular(cuddE(node)));
        if (node->ref > 1) {
            if (st_add_direct(table,(char *)node,(char *)node) ==
                ST_OUT_OF_MEM)
                return(CUDD_OUT_OF_MEM);
        }
        val = 1 + tval + eval;
        return(val);
Alan Mishchenko committed
3293 3294 3295
    }
    tval = cuddEstimateCofactor(dd,table,cuddT(node),i,phase,&ptrT);
    eval = cuddEstimateCofactor(dd,table,Cudd_Regular(cuddE(node)),i,
3296
                                phase,&ptrE);
Alan Mishchenko committed
3297
    ptrE = Cudd_NotCond(ptrE,Cudd_IsComplement(cuddE(node)));
3298 3299 3300 3301 3302 3303 3304 3305
    if (ptrT == ptrE) {         /* recombination */
        *ptr = ptrT;
        val = tval;
        if (node->ref > 1) {
            if (st_add_direct(table,(char *)node,(char *)*ptr) ==
                    ST_OUT_OF_MEM)
                return(CUDD_OUT_OF_MEM);
        }
Alan Mishchenko committed
3306
    } else if ((ptrT != cuddT(node) || ptrE != cuddE(node)) &&
3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
               (*ptr = cuddUniqueLookup(dd,node->index,ptrT,ptrE)) != NULL) {
        if (Cudd_IsComplement((*ptr)->next)) {
            val = 0;
        } else {
            val = 1 + tval + eval;
        }
        if (node->ref > 1) {
            if (st_add_direct(table,(char *)node,(char *)*ptr) ==
                    ST_OUT_OF_MEM)
                return(CUDD_OUT_OF_MEM);
        }
Alan Mishchenko committed
3318
    } else {
3319
        *ptr = node;
Alan Mishchenko committed
3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352
        val = 1 + tval + eval;
    }
    return(val);

} /* end of cuddEstimateCofactor */


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

  Synopsis    [Checks the unique table for the existence of an internal node.]

  Description [Checks the unique table for the existence of an internal
  node. Returns a pointer to the node if it is in the table; NULL otherwise.]

  SideEffects [None]

  SeeAlso     [cuddUniqueInter]

******************************************************************************/
static DdNode *
cuddUniqueLookup(
  DdManager * unique,
  int  index,
  DdNode * T,
  DdNode * E)
{
    int posn;
    unsigned int level;
    DdNodePtr *nodelist;
    DdNode *looking;
    DdSubtable *subtable;

    if (index >= unique->size) {
3353
        return(NULL);
Alan Mishchenko committed
3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
    }

    level = unique->perm[index];
    subtable = &(unique->subtables[level]);

#ifdef DD_DEBUG
    assert(level < (unsigned) cuddI(unique,T->index));
    assert(level < (unsigned) cuddI(unique,Cudd_Regular(E)->index));
#endif

3364
    posn = ddHash(cuddF2L(T), cuddF2L(E), subtable->shift);
Alan Mishchenko committed
3365 3366 3367 3368
    nodelist = subtable->nodelist;
    looking = nodelist[posn];

    while (T < cuddT(looking)) {
3369
        looking = Cudd_Regular(looking->next);
Alan Mishchenko committed
3370 3371
    }
    while (T == cuddT(looking) && E < cuddE(looking)) {
3372
        looking = Cudd_Regular(looking->next);
Alan Mishchenko committed
3373 3374
    }
    if (cuddT(looking) == T && cuddE(looking) == E) {
3375
        return(looking);
Alan Mishchenko committed
3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405
    }

    return(NULL);

} /* end of cuddUniqueLookup */


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

  Synopsis    [Performs the recursive step of Cudd_CofactorEstimateSimple.]

  Description [Performs the recursive step of Cudd_CofactorEstimateSimple.
  Returns an estimate of the number of nodes in the DD of the positive
  cofactor of node. Uses the least significant bit of the next field as
  visited flag. node is supposed to be regular; the invariant is maintained
  by this procedure.]

  SideEffects [None]

  SeeAlso     []

******************************************************************************/
static int
cuddEstimateCofactorSimple(
  DdNode * node,
  int i)
{
    int tval, eval;

    if (Cudd_IsComplement(node->next)) {
3406
        return(0);
Alan Mishchenko committed
3407 3408 3409
    }
    node->next = Cudd_Not(node->next);
    if (cuddIsConstant(node)) {
3410
        return(1);
Alan Mishchenko committed
3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443
    }
    tval = cuddEstimateCofactorSimple(cuddT(node),i);
    if ((int) node->index == i) return(tval);
    eval = cuddEstimateCofactorSimple(Cudd_Regular(cuddE(node)),i);
    return(1 + tval + eval);

} /* end of cuddEstimateCofactorSimple */


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

  Synopsis    [Performs the recursive step of Cudd_CountMinterm.]

  Description [Performs the recursive step of Cudd_CountMinterm.
  It is based on the following identity. Let |f| be the
  number of minterms of f. Then:
  <xmp>
    |f| = (|f0|+|f1|)/2
  </xmp>
  where f0 and f1 are the two cofactors of f.  Does not use the
  identity |f'| = max - |f|, to minimize loss of accuracy due to
  roundoff.  Returns the number of minterms of the function rooted at
  node.]

  SideEffects [None]

******************************************************************************/
static double
ddCountMintermAux(
  DdNode * node,
  double  max,
  DdHashTable * table)
{
3444 3445 3446
    DdNode      *N, *Nt, *Ne;
    double      min, minT, minE;
    DdNode      *res;
Alan Mishchenko committed
3447 3448 3449 3450

    N = Cudd_Regular(node);

    if (cuddIsConstant(N)) {
3451 3452 3453 3454 3455
        if (node == background || node == zero) {
            return(0.0);
        } else {
            return(max);
        }
Alan Mishchenko committed
3456 3457
    }
    if (N->ref != 1 && (res = cuddHashTableLookup1(table,node)) != NULL) {
3458 3459 3460 3461 3462 3463
        min = cuddV(res);
        if (res->ref == 0) {
            table->manager->dead++;
            table->manager->constants.dead++;
        }
        return(min);
Alan Mishchenko committed
3464 3465 3466 3467
    }

    Nt = cuddT(N); Ne = cuddE(N);
    if (Cudd_IsComplement(node)) {
3468
        Nt = Cudd_Not(Nt); Ne = Cudd_Not(Ne);
Alan Mishchenko committed
3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479
    }

    minT = ddCountMintermAux(Nt,max,table);
    if (minT == (double)CUDD_OUT_OF_MEM) return((double)CUDD_OUT_OF_MEM);
    minT *= 0.5;
    minE = ddCountMintermAux(Ne,max,table);
    if (minE == (double)CUDD_OUT_OF_MEM) return((double)CUDD_OUT_OF_MEM);
    minE *= 0.5;
    min = minT + minE;

    if (N->ref != 1) {
3480 3481 3482 3483 3484 3485 3486
        ptrint fanout = (ptrint) N->ref;
        cuddSatDec(fanout);
        res = cuddUniqueConst(table->manager,min);
        if (!cuddHashTableInsert1(table,node,res,fanout)) {
            cuddRef(res); Cudd_RecursiveDeref(table->manager, res);
            return((double)CUDD_OUT_OF_MEM);
        }
Alan Mishchenko committed
3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516
    }

    return(min);

} /* end of ddCountMintermAux */


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

  Synopsis    [Performs the recursive step of Cudd_CountPath.]

  Description [Performs the recursive step of Cudd_CountPath.
  It is based on the following identity. Let |f| be the
  number of paths of f. Then:
  <xmp>
    |f| = |f0|+|f1|
  </xmp>
  where f0 and f1 are the two cofactors of f.  Uses the
  identity |f'| = |f|, to improve the utilization of the (local) cache.
  Returns the number of paths of the function rooted at node.]

  SideEffects [None]

******************************************************************************/
static double
ddCountPathAux(
  DdNode * node,
  st_table * table)
{

3517 3518 3519
    DdNode      *Nv, *Nnv;
    double      paths, *ppaths, paths1, paths2;
    double      *dummy;
Alan Mishchenko committed
3520 3521 3522


    if (cuddIsConstant(node)) {
3523
        return(1.0);
Alan Mishchenko committed
3524
    }
3525 3526 3527
    if (st_lookup(table, (const char *)node, (char **)&dummy)) {
        paths = *dummy;
        return(paths);
Alan Mishchenko committed
3528 3529 3530 3531 3532 3533 3534 3535 3536
    }

    Nv = cuddT(node); Nnv = cuddE(node);

    paths1 = ddCountPathAux(Nv,table);
    if (paths1 == (double)CUDD_OUT_OF_MEM) return((double)CUDD_OUT_OF_MEM);
    paths2 = ddCountPathAux(Cudd_Regular(Nnv),table);
    if (paths2 == (double)CUDD_OUT_OF_MEM) return((double)CUDD_OUT_OF_MEM);
    paths = paths1 + paths2;
3537

Alan Mishchenko committed
3538
    ppaths = ABC_ALLOC(double,1);
Alan Mishchenko committed
3539
    if (ppaths == NULL) {
3540
        return((double)CUDD_OUT_OF_MEM);
Alan Mishchenko committed
3541 3542 3543 3544 3545
    }

    *ppaths = paths;

    if (st_add_direct(table,(char *)node, (char *)ppaths) == ST_OUT_OF_MEM) {
3546 3547
        ABC_FREE(ppaths);
        return((double)CUDD_OUT_OF_MEM);
Alan Mishchenko committed
3548 3549 3550 3551 3552 3553 3554 3555
    }
    return(paths);

} /* end of ddCountPathAux */


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

3556
  Synopsis    [Performs the recursive step of Cudd_EpdCountMinterm.]
Alan Mishchenko committed
3557

3558
  Description [Performs the recursive step of Cudd_EpdCountMinterm.
Alan Mishchenko committed
3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578
  It is based on the following identity. Let |f| be the
  number of minterms of f. Then:
  <xmp>
    |f| = (|f0|+|f1|)/2
  </xmp>
  where f0 and f1 are the two cofactors of f.  Does not use the
  identity |f'| = max - |f|, to minimize loss of accuracy due to
  roundoff.  Returns the number of minterms of the function rooted at
  node.]

  SideEffects [None]

******************************************************************************/
static int
ddEpdCountMintermAux(
  DdNode * node,
  EpDouble * max,
  EpDouble * epd,
  st_table * table)
{
3579
    DdNode      *Nt, *Ne;
Alan Mishchenko committed
3580 3581
    EpDouble    *min, minT, minE;
    EpDouble    *res;
3582
    int         status;
Alan Mishchenko committed
3583

3584
    /* node is assumed to be regular */
Alan Mishchenko committed
3585
    if (cuddIsConstant(node)) {
3586 3587 3588 3589 3590 3591
        if (node == background || node == zero) {
            EpdMakeZero(epd, 0);
        } else {
            EpdCopy(max, epd);
        }
        return(0);
Alan Mishchenko committed
3592
    }
3593 3594 3595
    if (node->ref != 1 && st_lookup(table, (const char *)node, (char **)&res)) {
        EpdCopy(res, epd);
        return(0);
Alan Mishchenko committed
3596 3597 3598 3599 3600 3601 3602
    }

    Nt = cuddT(node); Ne = cuddE(node);

    status = ddEpdCountMintermAux(Nt,max,&minT,table);
    if (status == CUDD_OUT_OF_MEM) return(CUDD_OUT_OF_MEM);
    EpdMultiply(&minT, (double)0.5);
3603
    status = ddEpdCountMintermAux(Cudd_Regular(Ne),max,&minE,table);
Alan Mishchenko committed
3604 3605 3606 3607 3608 3609 3610 3611 3612
    if (status == CUDD_OUT_OF_MEM) return(CUDD_OUT_OF_MEM);
    if (Cudd_IsComplement(Ne)) {
        EpdSubtract3(max, &minE, epd);
        EpdCopy(epd, &minE);
    }
    EpdMultiply(&minE, (double)0.5);
    EpdAdd3(&minT, &minE, epd);

    if (node->ref > 1) {
3613 3614 3615 3616 3617 3618 3619 3620
        min = EpdAlloc();
        if (!min)
            return(CUDD_OUT_OF_MEM);
        EpdCopy(epd, min);
        if (st_insert(table, (char *)node, (char *)min) == ST_OUT_OF_MEM) {
            EpdFree(min);
            return(CUDD_OUT_OF_MEM);
        }
Alan Mishchenko committed
3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649
    }

    return(0);

} /* end of ddEpdCountMintermAux */


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

  Synopsis    [Performs the recursive step of Cudd_CountPathsToNonZero.]

  Description [Performs the recursive step of Cudd_CountPathsToNonZero.
  It is based on the following identity. Let |f| be the
  number of paths of f. Then:
  <xmp>
    |f| = |f0|+|f1|
  </xmp>
  where f0 and f1 are the two cofactors of f.  Returns the number of
  paths of the function rooted at node.]

  SideEffects [None]

******************************************************************************/
static double
ddCountPathsToNonZero(
  DdNode * N,
  st_table * table)
{

3650 3651 3652
    DdNode      *node, *Nt, *Ne;
    double      paths, *ppaths, paths1, paths2;
    double      *dummy;
Alan Mishchenko committed
3653 3654 3655

    node = Cudd_Regular(N);
    if (cuddIsConstant(node)) {
3656
        return((double) !(Cudd_IsComplement(N) || cuddV(node)==DD_ZERO_VAL));
Alan Mishchenko committed
3657
    }
3658 3659 3660
    if (st_lookup(table, (const char *)N, (char **)&dummy)) {
        paths = *dummy;
        return(paths);
Alan Mishchenko committed
3661 3662 3663 3664
    }

    Nt = cuddT(node); Ne = cuddE(node);
    if (node != N) {
3665
        Nt = Cudd_Not(Nt); Ne = Cudd_Not(Ne);
Alan Mishchenko committed
3666 3667 3668 3669 3670 3671 3672 3673
    }

    paths1 = ddCountPathsToNonZero(Nt,table);
    if (paths1 == (double)CUDD_OUT_OF_MEM) return((double)CUDD_OUT_OF_MEM);
    paths2 = ddCountPathsToNonZero(Ne,table);
    if (paths2 == (double)CUDD_OUT_OF_MEM) return((double)CUDD_OUT_OF_MEM);
    paths = paths1 + paths2;

Alan Mishchenko committed
3674
    ppaths = ABC_ALLOC(double,1);
Alan Mishchenko committed
3675
    if (ppaths == NULL) {
3676
        return((double)CUDD_OUT_OF_MEM);
Alan Mishchenko committed
3677 3678 3679 3680 3681
    }

    *ppaths = paths;

    if (st_add_direct(table,(char *)N, (char *)ppaths) == ST_OUT_OF_MEM) {
3682 3683
        ABC_FREE(ppaths);
        return((double)CUDD_OUT_OF_MEM);
Alan Mishchenko committed
3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708
    }
    return(paths);

} /* end of ddCountPathsToNonZero */


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

  Synopsis    [Performs the recursive step of Cudd_Support.]

  Description [Performs the recursive step of Cudd_Support. Performs a
  DFS from f. The support is accumulated in supp as a side effect. Uses
  the LSB of the then pointer as visited flag.]

  SideEffects [None]

  SeeAlso     [ddClearFlag]

******************************************************************************/
static void
ddSupportStep(
  DdNode * f,
  int * support)
{
    if (cuddIsConstant(f) || Cudd_IsComplement(f->next)) {
3709
        return;
Alan Mishchenko committed
3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738
    }

    support[f->index] = 1;
    ddSupportStep(cuddT(f),support);
    ddSupportStep(Cudd_Regular(cuddE(f)),support);
    /* Mark as visited. */
    f->next = Cudd_Not(f->next);
    return;

} /* end of ddSupportStep */


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

  Synopsis    [Performs a DFS from f, clearing the LSB of the next
  pointers.]

  Description []

  SideEffects [None]

  SeeAlso     [ddSupportStep ddDagInt]

******************************************************************************/
static void
ddClearFlag(
  DdNode * f)
{
    if (!Cudd_IsComplement(f->next)) {
3739
        return;
Alan Mishchenko committed
3740 3741 3742 3743
    }
    /* Clear visited flag. */
    f->next = Cudd_Regular(f->next);
    if (cuddIsConstant(f)) {
3744
        return;
Alan Mishchenko committed
3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771
    }
    ddClearFlag(cuddT(f));
    ddClearFlag(Cudd_Regular(cuddE(f)));
    return;

} /* end of ddClearFlag */


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

  Synopsis    [Performs the recursive step of Cudd_CountLeaves.]

  Description [Performs the recursive step of Cudd_CountLeaves. Returns
  the number of leaves in the DD rooted at n.]

  SideEffects [None]

  SeeAlso     [Cudd_CountLeaves]

******************************************************************************/
static int
ddLeavesInt(
  DdNode * n)
{
    int tval, eval;

    if (Cudd_IsComplement(n->next)) {
3772
        return(0);
Alan Mishchenko committed
3773 3774 3775
    }
    n->next = Cudd_Not(n->next);
    if (cuddIsConstant(n)) {
3776
        return(1);
Alan Mishchenko committed
3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816
    }
    tval = ddLeavesInt(cuddT(n));
    eval = ddLeavesInt(Cudd_Regular(cuddE(n)));
    return(tval + eval);

} /* end of ddLeavesInt */


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

  Synopsis    [Performs the recursive step of Cudd_bddPickArbitraryMinterms.]

  Description [Performs the recursive step of Cudd_bddPickArbitraryMinterms.
  Returns 1 if successful; 0 otherwise.]

  SideEffects [none]

  SeeAlso [Cudd_bddPickArbitraryMinterms]

******************************************************************************/
static int
ddPickArbitraryMinterms(
  DdManager *dd,
  DdNode *node,
  int nvars,
  int nminterms,
  char **string)
{
    DdNode *N, *T, *E;
    DdNode *one, *bzero;
    int    i, t, result;
    double min1, min2;

    if (string == NULL || node == NULL) return(0);

    /* The constant 0 function has no on-set cubes. */
    one = DD_ONE(dd);
    bzero = Cudd_Not(one);
    if (nminterms == 0 || node == bzero) return(1);
    if (node == one) {
3817
        return(1);
Alan Mishchenko committed
3818 3819 3820 3821 3822
    }

    N = Cudd_Regular(node);
    T = cuddT(N); E = cuddE(N);
    if (Cudd_IsComplement(node)) {
3823
        T = Cudd_Not(T); E = Cudd_Not(E);
Alan Mishchenko committed
3824 3825 3826 3827 3828 3829 3830 3831 3832
    }

    min1 = Cudd_CountMinterm(dd, T, nvars) / 2.0;
    if (min1 == (double)CUDD_OUT_OF_MEM) return(0);
    min2 = Cudd_CountMinterm(dd, E, nvars) / 2.0;
    if (min2 == (double)CUDD_OUT_OF_MEM) return(0);

    t = (int)((double)nminterms * min1 / (min1 + min2) + 0.5);
    for (i = 0; i < t; i++)
3833
        string[i][N->index] = '1';
Alan Mishchenko committed
3834
    for (i = t; i < nminterms; i++)
3835
        string[i][N->index] = '0';
Alan Mishchenko committed
3836 3837 3838

    result = ddPickArbitraryMinterms(dd,T,nvars,t,&string[0]);
    if (result == 0)
3839
        return(0);
Alan Mishchenko committed
3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877
    result = ddPickArbitraryMinterms(dd,E,nvars,nminterms-t,&string[t]);
    return(result);

} /* end of ddPickArbitraryMinterms */


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

  Synopsis    [Finds a representative cube of a BDD.]

  Description [Finds a representative cube of a BDD with the weight of
  each variable. From the top variable, if the weight is greater than or
  equal to 0.0, choose THEN branch unless the child is the constant 0.
  Otherwise, choose ELSE branch unless the child is the constant 0.]

  SideEffects [Cudd_SubsetWithMaskVars Cudd_bddPickOneCube]

******************************************************************************/
static int
ddPickRepresentativeCube(
  DdManager *dd,
  DdNode *node,
  double *weight,
  char *string)
{
    DdNode *N, *T, *E;
    DdNode *one, *bzero;

    if (string == NULL || node == NULL) return(0);

    /* The constant 0 function has no on-set cubes. */
    one = DD_ONE(dd);
    bzero = Cudd_Not(one);
    if (node == bzero) return(0);

    if (node == DD_ONE(dd)) return(1);

    for (;;) {
3878 3879 3880 3881 3882 3883 3884 3885
        N = Cudd_Regular(node);
        if (N == one)
            break;
        T = cuddT(N);
        E = cuddE(N);
        if (Cudd_IsComplement(node)) {
            T = Cudd_Not(T);
            E = Cudd_Not(E);
Alan Mishchenko committed
3886
        }
3887 3888 3889 3890 3891 3892 3893 3894
        if (weight[N->index] >= 0.0) {
            if (T == bzero) {
                node = E;
                string[N->index] = '0';
            } else {
                node = T;
                string[N->index] = '1';
            }
Alan Mishchenko committed
3895
        } else {
3896 3897 3898 3899 3900 3901 3902
            if (E == bzero) {
                node = T;
                string[N->index] = '1';
            } else {
                node = E;
                string[N->index] = '0';
            }
Alan Mishchenko committed
3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933
        }
    }
    return(1);

} /* end of ddPickRepresentativeCube */


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

  Synopsis [Frees the memory used to store the minterm counts recorded
  in the visited table.]

  Description [Frees the memory used to store the minterm counts
  recorded in the visited table. Returns ST_CONTINUE.]

  SideEffects [None]

******************************************************************************/
static enum st_retval
ddEpdFree(
  char * key,
  char * value,
  char * arg)
{
    EpDouble    *epd;

    epd = (EpDouble *) value;
    EpdFree(epd);
    return(ST_CONTINUE);

} /* end of ddEpdFree */
3934 3935


3936 3937
ABC_NAMESPACE_IMPL_END