Exemplo n.º 1
0
def _do_espresso(fname):
    fpath = os.path.join('thirdparty', 'espresso', 'test', 'bb_all', fname)
    with open(fpath) as fin:
        d = pla.parse(fin.read())
    return espresso.espresso(d['ninputs'],
                             d['noutputs'],
                             d['cover'],
                             intype=d['intype'])
Exemplo n.º 2
0
def test_basic():
    d = parse(BASIC)
    assert d == {
        'ninputs': 4,
        'noutputs': 2,
        'input_labels': ['x', 'y', 'z'],
        'output_labels': ['f', 'g'],
        'intype': FTYPE | RTYPE,
        'cover': {((1, 1, 1, 2), (0, 0)), ((1, 1, 2, 1), (0, 1)),
                  ((1, 2, 1, 1), (1, 0)), ((2, 1, 1, 1), (1, 1))},
    }
Exemplo n.º 3
0
def test_basic():
    d = parse(BASIC)
    assert d == {
        'ninputs': 4,
        'noutputs': 2,
        'input_labels': ['x', 'y', 'z'],
        'output_labels': ['f', 'g'],
        'intype': FTYPE | RTYPE,
        'cover': {
            ((1, 1, 1, 2), (0, 0)),
            ((1, 1, 2, 1), (0, 1)),
            ((1, 2, 1, 1), (1, 0)),
            ((2, 1, 1, 1), (1, 1))
        },
    }
Exemplo n.º 4
0
def main(fin, fout):
    opts = PARSER.parse_args()

    espresso.set_config(
        single_expand=opts.fast,
        remove_essential=opts.ess,
        force_irredundant=opts.irr,
        unwrap_onset=opts.unwrap,
        recompute_onset=opts.onset,
        use_super_gasp=opts.strong,
    )

    try:
        f = open(fin, "r")
        d = pla.parse(f.read())
        f.close()
    except pla.Error as exc:
        print("error parsing file:", opts.file.name)
        print(exc)
        return 1

    try:
        cover = espresso.espresso(d['ninputs'], d['noutputs'],
                                  d['cover'], intype=d['intype'])
    except espresso.Error as exc:
        print("espresso failed:", exc)
        return 1

    f = open(fout, "w")
    print(".i", d['ninputs'], file=f)
    print(".o", d['noutputs'], file=f)
    if d['input_labels']:
        print(".ilb", " ".join(d['input_labels']), file=f)
    if d['output_labels']:
        print(".ob", " ".join(d['output_labels']), file=f)
    print(".p", len(cover), file=f)
    for invec, outvec in cover:
        print("".join({1: '0', 2: '1', 3: '-'}[n] for n in invec),
              "".join({0: '0', 1: '1', 2: '-'}[n] for n in outvec), file=f)
    print(".e", file=f)
    f.close()
    return 0
Exemplo n.º 5
0
def _do_espresso(fname):
    fpath = os.path.join('thirdparty', 'espresso', 'test', 'bb_all', fname)
    with open(fpath) as fin:
        d = pla.parse(fin.read())
    return espresso.espresso(d['ninputs'], d['noutputs'], d['cover'], intype=d['intype'])
Exemplo n.º 6
0
def main():
    parser = argparse.ArgumentParser(description='Minterm reduction with ASP')
    parser.add_argument('file',
                        nargs='?',
                        type=argparse.FileType('r'),
                        default=sys.stdin,
                        help="PLA file (default: stdin)")
    parser.add_argument('-m',
                        '--minmode',
                        default="terms",
                        choices=['atoms', 'terms'],
                        help='formulae minimization method')
    args = parser.parse_args()

    try:
        input_dict = pla.parse(args.file.read())
    except pla.Error as exc:
        print("error parsing file:", args.file.name)
        print(exc)
        return 1

    # Turn minterms into ASP facts
    input_facts = input_to_asp(input_dict)

    # Create the prime implicates
    outputs = []
    for outno in range(input_dict['noutputs']):
        primpl_syms = solve_iter("pair-maker-onoff", [input_facts[outno]])
        primpl_facts = symbols_to_facts(primpl_syms)

        # Perform minimal coverage for the prime implicates
        mincover_syms = solve_iter("min-cover", [primpl_facts])
        mincover_facts = symbols_to_facts(mincover_syms)

        essndict, finaldicts = {}, []
        essndict = implicates_to_dict(mincover_syms, "essn")
        # If the minimal coverage doesn't cover all minterms, petrick it
        if any(sym.name == "fullcover" for sym in mincover_syms):
            finaldicts += [essndict]
        else:
            petrick_solutions = solve("petrick", [mincover_facts], ["0"])
            for idx, petrick_syms in enumerate(petrick_solutions):
                petrick_facts = symbols_to_facts(petrick_syms)
                if any(sym.name == "selectimplid" for sym in petrick_syms):
                    secdict = implicates_to_dict(petrick_syms, "select")
                    finaldictasy = {**essndict, **secdict}
                    finaldicts += [finaldictasy]

        # If more than one possible solution, obtain minimal formulae
        # Depends on the specified minimization mode, some of them require an asprin call
        if len(finaldicts) == 1:
            outputs += [essndict]
        else:
            optmode, asprin, minimal_solutions = "", False, []
            if args.minmode == "atoms":
                optmode = "less-atoms"
            elif args.minmode == "terms":
                optmode = "less-terms"

            minimize_facts = ""
            for idx, impdict in enumerate(finaldicts):
                asp = "solution({0}). ".format(idx)
                for impl in impdict.keys():
                    for v in impdict[impl].keys():
                        asp += "sol(impl({0},{1},{2}), {3}). ".format(
                            impl, v, impdict[impl][v], idx)
                minimize_facts += asp

            minimal_solutions = solve(optmode, [minimize_facts], [])
            mindict = implicates_to_dict(minimal_solutions[0], "select")
            outputs += [mindict]

    pladict = {}
    for idx, o in enumerate(outputs):
        for k, v in o.items():
            val = ""
            for kk in sorted(o[k]):
                val += str(o[k][kk]).replace('x', '-')
            print(val)
            if not val in pladict.keys():
                pladict.update({val: ["0"] * len(outputs)})
            pladict[val][idx] = "1"

    print(output_dict_pla(pladict, input_dict))