Пример #1
0
    def evaluate_explicit_from_fsdd(self, custom_semiring=None):
        try:
            parser = DefaultPrologParser(ExtendedPrologFactory())
            lf = PrologFile(filename, parser=parser)
            kc = _ForwardSDD.create_from(lf)  # type: _ForwardSDD
            kc = kc.to_explicit_encoding()

            if custom_semiring is not None:
                semiring = custom_semiring  # forces the custom semiring code.
            elif logspace:
                semiring = SemiringLogProbability()
            else:
                semiring = SemiringProbability()

            computed = kc.evaluate(semiring=semiring)
            computed = {str(k): v for k, v in computed.items()}
        except Exception as err:
            #print("exception %s" % err)
            e = err
            computed = None

        if computed is None:
            self.assertEqual(correct, type(e).__name__)
        else:
            self.assertIsInstance(correct, dict)
            self.assertSequenceEqual(correct, computed)

            for query in correct:
                self.assertAlmostEqual(correct[query],
                                       computed[query],
                                       msg=query)
Пример #2
0
    def problog(self, line, cell=None):
        """problog line/cell magic"""
        args = parse_argstring(self.problog, line)
        if args.knowledge == 'nnf':
            knowledge = DDNNF
        elif args.knowledge == 'sdd':
            knowledge = SDD
        elif args.knowledge is None:
            if SDD.is_available():
                knowledge = SDD
            else:
                knowledge = DDNNF
        else:
            error("Unknown option for --knowledge: '%s'" % args.knowledge)
        if args.logspace:
            semiring = SemiringLogProbability()
        else:
            semiring = None

        s = cell
        data = runproblog(s,
                          knowledge=knowledge,
                          semiring=semiring,
                          output='html')
        if data:
            display_html(data, raw=True)
Пример #3
0
    def test(self) :
        try :
            parser = DefaultPrologParser(ExtendedPrologFactory())
            sdd = SDD.createFrom(PrologFile(filename, parser=parser))

            if logspace :
                semiring = SemiringLogProbability()
            else :
                semiring = SemiringProbability()

            computed = sdd.evaluate(semiring=semiring)
            computed = { str(k) : v for k,v in computed.items() }
        except Exception as err :
            e = err
            computed = None

        if computed is None :
            self.assertEqual(correct, type(e).__name__)
        else :
            self.assertIsInstance( correct, dict )
            self.assertSequenceEqual(correct, computed)

            for query in correct :
                self.assertAlmostEqual(correct[query], computed[query], msg=query)
Пример #4
0
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
 def value(self, a):
     # Argument 'a' contains ground term. Look up its probability in the
     # weights dictionary.
     return SemiringLogProbability.value(self, self.weights.get(a, a))
Пример #6
0
 def __init__(self, weights):
     SemiringLogProbability.__init__(self)
     self.weights = weights
Пример #7
0
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)