コード例 #1
0
def mpe_maxsat(dag, verbose=0, solver=None):
    if dag.queries():
        print('%% WARNING: ignoring queries in file', file=sys.stderr)
        dag.clear_queries()

    logger = init_logger(verbose)
    logger.info('Ground program size: %s' % len(dag))

    cnf = CNF.createFrom(dag)

    for qn, qi in cnf.evidence():
        if not cnf.is_true(qi):
            cnf.add_constraint(TrueConstraint(qi))

    queries = list(cnf.labeled())

    logger.info('CNF size: %s' % cnf.clausecount)

    if not cnf.is_trivial():
        solver = get_solver(solver)

        with Timer('Solving'):
            result = frozenset(solver.evaluate(cnf))
        weights = cnf.extract_weights(SemiringProbability())
        output_facts = None
        prob = 1.0
        if result is not None:
            output_facts = []

            if queries:
                for qn, qi, ql in queries:
                    if qi in result:
                        output_facts.append(qn)
                    elif -qi in result:
                        output_facts.append(-qn)
            for i, n, t in dag:
                if t == 'atom':
                    if i in result:
                        if not queries:
                            output_facts.append(n.name)
                        prob *= weights[i][0]
                    elif -i in result:
                        if not queries:
                            output_facts.append(-n.name)
                        prob *= weights[i][1]
    else:
        prob = 1.0
        output_facts = []

    return prob, output_facts
コード例 #2
0
ファイル: mpe.py プロジェクト: PietroTotis/ArgProblog
def mpe_maxsat(dag, verbose=0, solver=None, minpe=False):
    logger = init_logger(verbose)
    logger.info("Ground program size: %s" % len(dag))

    cnf = CNF.createFrom(dag, force_atoms=True)
    for qn, qi in cnf.evidence():
        if not cnf.is_true(qi):
            cnf.add_constraint(TrueConstraint(qi))

    queries = list(cnf.labeled())

    logger.info("CNF size: %s" % cnf.clausecount)

    if not cnf.is_trivial():
        solver = get_solver(solver)

        with Timer("Solving"):
            result = frozenset(solver.evaluate(cnf, invert_weights=minpe))
        weights = cnf.extract_weights(SemiringProbability())
        output_facts = None
        prob = 1.0
        if result is not None:
            output_facts = []

            if queries:
                for qn, qi, ql in queries:
                    if qi in result:
                        output_facts.append(qn)
                    elif -qi in result:
                        output_facts.append(-qn)
            for i, n, t in dag:
                if t == "atom":
                    if i in result:
                        if not queries:
                            output_facts.append(n.name)
                        prob *= weights[i][0]
                    elif -i in result:
                        if not queries:
                            output_facts.append(-n.name)
                        prob *= weights[i][1]
    else:
        prob = 1.0
        output_facts = []

    return prob, output_facts
コード例 #3
0
def main(filename, output):

    model = PrologFile(filename)

    engine = DefaultEngine(label_all=True)

    with Timer("parsing"):
        db = engine.prepare(model)

    print("\n=== Database ===")
    print(db)

    print("\n=== Queries ===")
    queries = engine.query(db, Term("query", None))
    print("Queries:", ", ".join([str(q[0]) for q in queries]))

    print("\n=== Evidence ===")
    evidence = engine.query(db, Term("evidence", None, None))
    print("Evidence:", ", ".join(["%s=%s" % ev for ev in evidence]))

    print("\n=== Ground Program ===")
    with Timer("ground"):
        gp = engine.ground_all(db)
    print(gp)

    print("\n=== Acyclic Ground Program ===")
    with Timer("acyclic"):
        gp = LogicDAG.createFrom(gp)
    print(gp)

    print("\n=== Conversion to CNF ===")
    with Timer("convert to CNF"):
        cnf = CNF.createFrom(gp)

    with open(output, "w") as f:
        f.write(cnf.to_dimacs(weighted=False, names=True))
コード例 #4
0
ファイル: ground.py プロジェクト: PietroTotis/ArgProblog
def main(argv, result_handler=None):
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("filename",
                        metavar="MODEL",
                        type=str,
                        help="input ProbLog model")
    parser.add_argument(
        "--format",
        choices=("dot", "pl", "cnf", "svg", "internal"),
        default=None,
        help="output format",
    )
    parser.add_argument("--break-cycles",
                        action="store_true",
                        help="perform cycle breaking")
    parser.add_argument("--transform-nnf",
                        action="store_true",
                        help="transform to NNF")
    parser.add_argument("--keep-all",
                        action="store_true",
                        help="also output deterministic nodes")
    parser.add_argument(
        "--keep-duplicates",
        action="store_true",
        help="don't eliminate duplicate literals",
    )
    parser.add_argument("--any-order",
                        action="store_true",
                        help="allow reordering nodes")
    parser.add_argument(
        "--hide-builtins",
        action="store_true",
        help="hide deterministic part based on builtins",
    )
    parser.add_argument("--propagate-evidence",
                        action="store_true",
                        help="propagate evidence")
    parser.add_argument("--propagate-weights",
                        action="store_true",
                        help="propagate evidence")
    parser.add_argument(
        "--compact",
        action="store_true",
        help="allow compact model (may remove some predicates)",
    )
    parser.add_argument("--noninterpretable", action="store_true")
    parser.add_argument("--web", action="store_true", help=argparse.SUPPRESS)
    parser.add_argument("--verbose",
                        "-v",
                        action="count",
                        default=0,
                        help="Verbose output")
    parser.add_argument("-o",
                        "--output",
                        type=str,
                        help="output file",
                        default=None)
    parser.add_argument(
        "-a",
        "--arg",
        dest="args",
        action="append",
        help="Pass additional arguments to the cmd_args builtin.",
    )

    args = parser.parse_args(argv)

    outformat = args.format
    outfile = sys.stdout
    if args.output:
        outfile = open(args.output, "w")
        if outformat is None:
            outformat = os.path.splitext(args.output)[1][1:]

    if outformat == "cnf" and not args.break_cycles:
        print(
            "Warning: CNF output requires cycle-breaking; cycle breaking enabled.",
            file=sys.stderr,
        )

    if args.transform_nnf:
        target = LogicNNF
    elif args.break_cycles or outformat == "cnf":
        target = LogicDAG
    else:
        target = LogicFormula

    if args.propagate_weights:
        semiring = SemiringLogProbability()
    else:
        semiring = None

    if args.web:
        print_result = print_result_json
    else:
        print_result = print_result_standard

    try:
        gp = target.createFrom(
            PrologFile(args.filename,
                       parser=DefaultPrologParser(ExtendedPrologFactory())),
            label_all=not args.noninterpretable,
            avoid_name_clash=not args.compact,
            keep_order=not args.any_order,
            keep_all=args.keep_all,
            keep_duplicates=args.keep_duplicates,
            hide_builtins=args.hide_builtins,
            propagate_evidence=args.propagate_evidence,
            propagate_weights=semiring,
            args=args.args,
        )

        if outformat == "pl":
            rc = print_result((True, gp.to_prolog()), output=outfile)
        elif outformat == "dot":
            rc = print_result((True, gp.to_dot()), output=outfile)
        elif outformat == "svg":
            dot = gp.to_dot()
            tmpfile = mktempfile(".dot")
            with open(tmpfile, "w") as f:
                print(dot, file=f)
            svg = subprocess_check_output(["dot", tmpfile, "-Tsvg"])
            rc = print_result((True, svg), output=outfile)
        elif outformat == "cnf":
            cnfnames = args.verbose > 0
            rc = print_result(
                (True, CNF.createFrom(gp).to_dimacs(names=cnfnames)),
                output=outfile)
        elif outformat == "internal":
            rc = print_result((True, str(gp)), output=outfile)
        else:
            rc = print_result((True, gp.to_prolog()), output=outfile)
    except Exception as err:
        import traceback

        err.trace = traceback.format_exc()
        rc = print_result((False, err))

    if args.output:
        outfile.close()

    if rc:
        sys.exit(rc)
コード例 #5
0
ファイル: step-by-step.py プロジェクト: Nicolas-Boltz/problog
def main(filename, with_dot, knowledge):

    dotprefix = None
    if with_dot:
        dotprefix = os.path.splitext(filename)[0] + "_"

    model = PrologFile(filename)

    engine = DefaultEngine(label_all=True)

    with Timer("parsing"):
        db = engine.prepare(model)

    print("\n=== Database ===")
    print(db)

    print("\n=== Queries ===")
    queries = engine.query(db, Term("query", None))
    print("Queries:", ", ".join([str(q[0]) for q in queries]))

    print("\n=== Evidence ===")
    evidence = engine.query(db, Term("evidence", None, None))
    print("Evidence:", ", ".join(["%s=%s" % ev for ev in evidence]))

    print("\n=== Ground Program ===")
    with Timer("ground"):
        gp = engine.ground_all(db)
    print(gp)

    if dotprefix != None:
        with open(dotprefix + "gp.dot", "w") as f:
            print(gp.toDot(), file=f)

    print("\n=== Acyclic Ground Program ===")
    with Timer("acyclic"):
        gp = gp.makeAcyclic()
    print(gp)

    if dotprefix != None:
        with open(dotprefix + "agp.dot", "w") as f:
            print(gp.toDot(), file=f)

    if knowledge == "sdd":
        print("\n=== SDD compilation ===")
        with Timer("compile"):
            nnf = SDD.createFrom(gp)

        if dotprefix != None:
            nnf.saveSDDToDot(dotprefix + "sdd.dot")

    else:
        print("\n=== Conversion to CNF ===")
        with Timer("convert to CNF"):
            cnf = CNF.createFrom(gp)

        print("\n=== Compile to d-DNNF ===")
        with Timer("compile"):
            nnf = DDNNF.createFrom(cnf)

    if dotprefix != None:
        with open(dotprefix + "nnf.dot", "w") as f:
            print(nnf.toDot(), file=f)

    print("\n=== Evaluation result ===")
    with Timer("evaluate"):
        result = nnf.evaluate()

    for it in result.items():
        print("%s : %s" % (it))
コード例 #6
0
ファイル: ground.py プロジェクト: rasata/ProbLog
def main(argv, result_handler=None):
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('filename',
                        metavar='MODEL',
                        type=str,
                        help='input ProbLog model')
    parser.add_argument('--format',
                        choices=('dot', 'pl', 'cnf', 'svg', 'internal'),
                        default=None,
                        help='output format')
    parser.add_argument('--break-cycles',
                        action='store_true',
                        help='perform cycle breaking')
    parser.add_argument('--transform-nnf',
                        action='store_true',
                        help='transform to NNF')
    parser.add_argument('--keep-all',
                        action='store_true',
                        help='also output deterministic nodes')
    parser.add_argument('--keep-duplicates',
                        action='store_true',
                        help='don\'t eliminate duplicate literals')
    parser.add_argument('--any-order',
                        action='store_true',
                        help='allow reordering nodes')
    parser.add_argument('--hide-builtins',
                        action='store_true',
                        help='hide deterministic part based on builtins')
    parser.add_argument('--propagate-evidence',
                        action='store_true',
                        help='propagate evidence')
    parser.add_argument('--propagate-weights',
                        action='store_true',
                        help='propagate evidence')
    parser.add_argument(
        '--compact',
        action='store_true',
        help='allow compact model (may remove some predicates)')
    parser.add_argument('--noninterpretable', action='store_true')
    parser.add_argument('--web', action='store_true', help=argparse.SUPPRESS)
    parser.add_argument('--verbose',
                        '-v',
                        action='count',
                        default=0,
                        help='Verbose output')
    parser.add_argument('-o',
                        '--output',
                        type=str,
                        help='output file',
                        default=None)
    parser.add_argument(
        '-a',
        '--arg',
        dest='args',
        action='append',
        help='Pass additional arguments to the cmd_args builtin.')

    args = parser.parse_args(argv)

    outformat = args.format
    outfile = sys.stdout
    if args.output:
        outfile = open(args.output, 'w')
        if outformat is None:
            outformat = os.path.splitext(args.output)[1][1:]

    if outformat == 'cnf' and not args.break_cycles:
        print(
            'Warning: CNF output requires cycle-breaking; cycle breaking enabled.',
            file=sys.stderr)

    if args.transform_nnf:
        target = LogicNNF
    elif args.break_cycles or outformat == 'cnf':
        target = LogicDAG
    else:
        target = LogicFormula

    if args.propagate_weights:
        semiring = SemiringLogProbability()
    else:
        semiring = None

    if args.web:
        print_result = print_result_json
    else:
        print_result = print_result_standard

    try:
        gp = target.createFrom(PrologFile(args.filename,
                                          parser=DefaultPrologParser(
                                              ExtendedPrologFactory())),
                               label_all=not args.noninterpretable,
                               avoid_name_clash=not args.compact,
                               keep_order=not args.any_order,
                               keep_all=args.keep_all,
                               keep_duplicates=args.keep_duplicates,
                               hide_builtins=args.hide_builtins,
                               propagate_evidence=args.propagate_evidence,
                               propagate_weights=semiring,
                               args=args.args)

        if outformat == 'pl':
            rc = print_result((True, gp.to_prolog()), output=outfile)
        elif outformat == 'dot':
            rc = print_result((True, gp.to_dot()), output=outfile)
        elif outformat == 'svg':
            dot = gp.to_dot()
            tmpfile = mktempfile('.dot')
            with open(tmpfile, 'w') as f:
                print(dot, file=f)
            svg = subprocess_check_output(['dot', tmpfile, '-Tsvg'])
            rc = print_result((True, svg), output=outfile)
        elif outformat == 'cnf':
            cnfnames = False
            if args.verbose > 0:
                cnfnames = True
            rc = print_result(
                (True, CNF.createFrom(gp).to_dimacs(names=cnfnames)),
                output=outfile)
        elif outformat == 'internal':
            rc = print_result((True, str(gp)), output=outfile)
        else:
            rc = print_result((True, gp.to_prolog()), output=outfile)
    except Exception as err:
        import traceback
        err.trace = traceback.format_exc()
        rc = print_result((False, err))

    if args.output:
        outfile.close()

    if rc:
        sys.exit(rc)