Beispiel #1
0
    def ground(self, kind):
        count = self.objects + self.horizon + 1
        parts = [("expand", [Number(count)])]

        if self.args.scratch and count > 1:
            self.control = Control()
            for source in self.args.file:
                self.control.load(source)
            for i in range(0, self.objects):
                parts.append(("object", [Number(i + 1, count)]))
            for i in range(0, self.horizon):
                parts.append(("horizon", [Number(i + 1, count)]))

        if self.args.scratch or count == 1:
            for option in self.args.option:
                setattr(self.control.configuration, option[0], option[1])
            parts.append(("base", []))

        if kind:
            self.objects += 1
            parts.append(("object", [Number(self.objects), Number(count)]))
        else:
            self.horizon += 1
            parts.append(("horizon", [Number(self.horizon), Number(count)]))

        if self.args.verbose:
            print("")
            print("Objects: {}".format(Number(self.objects)))
            print("Horizon: {}".format(Number(self.horizon)))

        self.control.ground(parts)

        if self.args.verbose:
            print("Solving: {}".format(count))
Beispiel #2
0
    def _check(self, prg, prg10, prg_str):
        '''
        Check various ways to remap a program.

        1. No remapping.
        2. Identity remapping via Backend and Control.
        3. Remapping via Backend and Control.
        4. Remapping via remap function without Backend and Control.
        5. Remap a program using the Remapping class.
        '''
        self.assertEqual(self.prg, prg)
        self.assertEqual(str(self.prg), prg_str)

        r_prg = _remap(self.prg)
        self.assertEqual(self.prg, r_prg)
        self.assertEqual(str(r_prg), prg_str)

        r_prg10 = _remap(self.prg, _plus10)
        self.assertEqual(r_prg10, prg10)
        self.assertEqual(str(r_prg10), prg_str)

        ra_prg10 = self.prg.copy().remap(_plus10)
        self.assertEqual(ra_prg10, prg10)
        self.assertEqual(str(ra_prg10), prg_str)

        # note that the backend below is just used as an atom generator
        ctl = Control()
        with ctl.backend() as b:
            for _ in range(10):
                b.add_atom()
            rm_prg = prg.copy().remap(Remapping(b, self.prg.output_atoms, self.prg.facts))
        self.assertEqual(str(rm_prg), prg_str)
Beispiel #3
0
 def test_backend(self):
     '''
     Test backend via observer.
     '''
     ctl = Control()
     obs = TestObserverBackend(self)
     ctl.register_observer(obs)
     with ctl.backend() as backend:
         self.assertIn('init_program', obs.called)
         self.assertIn('begin_step', obs.called)
         backend.add_atom()
         backend.add_atom(Function('a'))
         backend.add_rule([1], [2, 3], True)
         self.assertIn('rule', obs.called)
         backend.add_weight_rule([2], 1, [(2, 3), (4, 5)])
         self.assertIn('weight_rule', obs.called)
         backend.add_minimize(0, [(2, 3), (4, 5)])
         self.assertIn('minimize', obs.called)
         backend.add_project([2, 4])
         self.assertIn('project', obs.called)
         backend.add_heuristic(2, HeuristicType.Level, 5, 7, [1, 3])
         self.assertIn('heuristic', obs.called)
         backend.add_assume([2, 3])
         self.assertIn('assume', obs.called)
         backend.add_acyc_edge(1, 2, [3, 4])
         self.assertIn('acyc_edge', obs.called)
         backend.add_external(3, TruthValue.Release)
         self.assertIn('external', obs.called)
     self.assertIn('output_atom', obs.called)
     ctl.solve()
     self.assertIn('end_step', obs.called)
Beispiel #4
0
 def test_theory(self):
     '''
     Test observer via grounding.
     '''
     ctl = Control()
     obs = TestObserverTheory(self)
     ctl.register_observer(obs)
     ctl.add(
         'base', [], '''\
     #theory test {
         t { };
         &a/0 : t, head
     }.
     {a; b}.
     #show t : a, b.
     &a { (1,a): a,b }.
     ''')
     ctl.ground([('base', [])])
     self.assertIn('output_term', obs.called)
     self.assertIn('theory_term_number', obs.called)
     self.assertIn('theory_term_string', obs.called)
     self.assertIn('theory_term_compound', obs.called)
     self.assertIn('theory_element', obs.called)
     self.assertIn('theory_atom', obs.called)
     ctl.solve()
Beispiel #5
0
def _remap(prg: Program, mapping=None):
    '''
    Add the given program to a backend passing it through an observer and then
    return the observer program.

    The resulting program is initialized with the symbols from the orginial
    program.
    '''

    ctl, chk = Control(), Program()
    # note that output atoms are not passed to the backend
    if mapping is None:
        chk.output_atoms = prg.output_atoms
        chk.shows = prg.shows
    else:
        chk.output_atoms = {mapping(lit): sym for lit, sym in prg.output_atoms.items()}
        chk.shows = [cast(Show, remap(x, mapping)) for x in prg.shows]
    chk.facts = prg.facts

    ctl.register_observer(ProgramObserver(chk))

    with ctl.backend() as b:
        prg.add_to_backend(b, mapping)

    return chk
Beispiel #6
0
    def test_control(self):
        '''
        Test observer together with a control object.
        '''
        ctl = Control()
        ctl.register_observer(self.obs)
        ctl.add('base', [], '''\
            b.
            {c}.
            a :- b, not c.
            #minimize{7@10,a:a; 5@10,c:c}.
            #project a.
            #project b.
            #external a.
            ''')
        ctl.ground([('base', [])])

        a, b, c = (Function(s) for s in ('a', 'b', 'c'))
        la, lb, lc = (ctl.symbolic_atoms[sym].literal for sym in (a, b, c))

        self.prg.sort()

        self.assertEqual(self.prg, Program(
            output_atoms={la: a, lc: c},
            shows=[],
            facts=[Fact(symbol=b)],
            rules=[Rule(choice=False, head=[lb], body=[]),
                   Rule(choice=False, head=[la], body=[-lc]),
                   Rule(choice=True, head=[lc], body=[])],
            minimizes=[Minimize(priority=10, literals=[(lc, 5), (la, 7)])],
            externals=[External(atom=la, value=TruthValue.False_)],
            projects=[Project(atom=lb), Project(atom=la)]).sort())
Beispiel #7
0
 def test_ground_error(self):
     '''
     Test grounding with context and parameters.
     '''
     ctx = Context()
     ctl = Control()
     ctl.add('part', ['c'], 'p(@cb_error()).')
     self.assertRaisesRegex(TestError, 'test', ctl.ground, [('part', [Number(1)])], ctx)
Beispiel #8
0
 def __init__(self):
     self.k = 0
     self.prg = Control()
     self.prg.load("client.lp")
     self.prg.ground([("pigeon", []), ("sleep", [Number(self.k)])])
     self.prg.assign_external(Function("sleep", [Number(self.k)]), True)
     self.ret = None
     self.models = []
Beispiel #9
0
def symbolic_atoms_to_facts_test1(q,facts_only):
    prgstr="""xq(1). xq("a"). 1 { xp(1);xp(2) }2."""
    ctrl=Control()
    add_program_string(ctrl,prgstr)
    ctrl.ground([("base",[])])
    fb=symbolic_atoms_to_facts(ctrl.symbolic_atoms,[XP,XQ,XQ2],
                               facts_only=facts_only)
    q.put(fb)
Beispiel #10
0
    def test_enum(self):
        '''
        Test core retrieval.
        '''
        self.ctl = Control(['0', '-e', 'cautious'])
        self.ctl.add("base", [], "1 {a; b} 1. c.")
        self.ctl.ground([("base", [])])
        self.ctl.solve(on_model=self.mcb.on_model)
        self.assertEqual(self.mcb.last[0], ModelType.CautiousConsequences)
        self.assertEqual([self.mcb.last[1]], _p(['c']))

        self.ctl = Control(['0', '-e', 'brave'])
        self.ctl.add("base", [], "1 {a; b} 1. c.")
        self.ctl.ground([("base", [])])
        self.ctl.solve(on_model=self.mcb.on_model)
        self.assertEqual(self.mcb.last[0], ModelType.BraveConsequences)
        self.assertEqual([self.mcb.last[1]], _p(['a', 'b', 'c']))
Beispiel #11
0
def test_fail_after_grounding():
    context = Context()

    class Foo:
        @classmethod
        def after_grounding(cls):
            raise ValueError('so nice')

    context.valasp_register_class(Foo)

    context.valasp_run(Control(), with_validators=False)
    context.valasp_run(Control(), with_validators=False, with_solve=False)

    with pytest.raises(ValueError):
        context.valasp_run(Control(), with_validators=True)

    with pytest.raises(ValueError):
        context.valasp_run(Control(), with_validators=True, with_solve=True)
Beispiel #12
0
def get_ground_universe(program: Program) -> Set[Symbol]:
    prg = program_to_string(program)
    ctl = Control()
    ctl.add("base", [], prg)
    ctl.ground([("base", [])])
    ground_universe = set(
        [ground_atom.symbol for ground_atom in ctl.symbolic_atoms])
    log(f"Ground universe: {ground_universe}")
    return ground_universe
Beispiel #13
0
 def __init__(self, connection):
     Thread.__init__(self)
     self.k = 0
     self.prg = Control()
     self.prg.load("client.lp")
     self.prg.ground([("pigeon", []), ("sleep", [Number(self.k)])])
     self.prg.assign_external(Function("sleep", [Number(self.k)]), True)
     self.state = SolveThread.STATE_IDLE
     self.input = Connection()
     self.output = connection
Beispiel #14
0
 def test_ground(self):
     '''
     Test grounding with context and parameters.
     '''
     ctx = Context()
     ctl = Control()
     ctl.add('part', ['c'], 'p(@cb_num(c)).')
     ctl.ground([('part', [Number(1)])], ctx)
     symbols = [atom.symbol for atom in ctl.symbolic_atoms]
     self.assertEqual(sorted(symbols), [Function('p', [Number(0)]), Function('p', [Number(2)])])
Beispiel #15
0
 def test_heurisitc(self):
     '''
     Test decide.
     '''
     self.ctl = Control(['1'])
     self.ctl.add("base", [], "{a;b}.")
     self.ctl.ground([("base", [])])
     self.ctl.register_propagator(TestHeuristic(self))
     self.ctl.solve(on_model=self.mcb.on_model)
     self.assertEqual(self.mcb.models, _p(['a']))
Beispiel #16
0
 def test_lower(self):
     '''
     Test lower bounds reported during optimization.
     '''
     ctl = Control(['--opt-str=usc,oll,0', '--stats=2'])
     ctl.add('base', [], '1 { p(X); q(X) } 1 :- X=1..3. #minimize { 1,p,X: p(X); 1,q,X: q(X) }.')
     ctl.ground([('base', [])])
     lower = []
     self.assertTrue(ctl.solve(on_unsat=lower.append).satisfiable)
     self.assertEqual(lower, [[1], [2], [3]])
     self.assertEqual(ctl.statistics['summary']['lower'], [3.0])
Beispiel #17
0
    def test_noclingo(self):
        from clingo import Control
        import clingo
        import clorm.noclingo as noclingo

        self.assertEqual(clingo.String("blah"), noclingo.String("blah"))
        self.assertEqual(clingo.Number(5), noclingo.Number(5))
        with self.assertRaises(TypeError) as ctx:
            instance = Control()
        with self.assertRaises(TypeError) as ctx:
            instance = clingo.Control()
Beispiel #18
0
 def test_simple_stats(self):
     '''
     Test simple statistics.
     '''
     ctl = Control(['-t', '2', '--stats=2'])
     ctl.add('base', [], '1 { a; b }.')
     ctl.ground([('base', [])])
     ctl.solve()
     stats = ctl.statistics
     self.assertGreaterEqual(stats['problem']['lp']['atoms'], 2)
     self.assertGreaterEqual(stats['solving']['solvers']['choices'], 1)
Beispiel #19
0
 def __init__(self,
              arguments: List[str] = [],
              logger=None,
              message_limit: int = 20,
              print_entire_models=False,
              atom_draw_maximum=15):
     self.control = Control(arguments, logger, message_limit)
     self.painter: List[PythonModel] = list()
     self.program: ASTProgram = list()
     self.raw_program: str = ""
     self.transformer = JustTheRulesTransformer()
     self._print_changes_only = not print_entire_models
     self._atom_draw_maximum = atom_draw_maximum
Beispiel #20
0
 def test_config(self):
     '''
     Test configuration.
     '''
     ctl = Control(['-t', '2'])
     self.assertIn('solver', ctl.configuration.keys)
     self.assertEqual(len(ctl.configuration.solver), 2)
     self.assertIsInstance(ctl.configuration.solver[0], Configuration)
     conf = cast(Configuration, ctl.configuration.solver[0])
     self.assertIsInstance(conf.heuristic, str)
     self.assertIsInstance(conf.description('heuristic'), str)
     conf.heuristic = 'berkmin'
     self.assertTrue(conf.heuristic.startswith('berkmin'))
Beispiel #21
0
    def test_control_add_facts(self):
        class F(Predicate):
            anum = IntegerField

        f1 = F(1) ; f2 = F(2)
        ctrl = Control()
        control_add_facts(ctrl,[f1,f2])
        ctrl.ground([("base",[])])
        model = None
        with ctrl.solve(yield_=True) as sh:
            for m in sh:
                model=str(m)
        self.assertEqual(model, "{} {}".format(f1,f2))
Beispiel #22
0
def test_doc_example():
    context = Context()

    @context.valasp(validate_predicate=False, with_fun=Fun.IMPLICIT)
    class Date:
        year: int
        month: int
        day: int

        def __post_init__(self):
            datetime.datetime(self.year, self.month, self.day)

    @context.valasp()
    class Birthday:
        name: String
        date: Date

    res = None

    def on_model(model):
        nonlocal res
        res = []
        for atom in model.symbols(atoms=True):
            res.append(atom)

    context.valasp_run(
        Control(),
        on_model=on_model,
        aux_program=[
            'birthday("sofia",date(2019,6,25)). birthday("leonardo",date(2018,2,1)).'
        ])
    assert str(
        res
    ) == '[birthday("sofia",date(2019,6,25)), birthday("leonardo",date(2018,2,1))]'

    with pytest.raises(RuntimeError):
        context.valasp_run(Control(),
                           aux_program=['birthday("no one",date(2019,2,29)).'])
Beispiel #23
0
    def __init__(self):
        self.size           = 1
        self.blocked        = set()
        self.barriers       = set()
        self.targets        = set()
        self.pos            = dict()
        self.robots         = [{}]
        self.moves          = []
        self.current_target = None
        self.solution       = None

        ctl = Control()
        ctl.load("board.lp")
        ctl.ground([("base", [])])
        ctl.solve(on_model=self.__on_model)
Beispiel #24
0
    def test_solve(self):
        cc = Control()

        cc.add('base', [], '''
        a(X) :- not b(X), d(X).
        b(X) :- not a(X), d(X).''')
        cc.add('base', [], "d(1;2;3).")
        cc.ground([("base",[])])

        out = {}
        def onmodel(m):
            out['out'] = str(m)
        cc.solve(on_model = onmodel)

        self.assertEqual('d(1) d(2) d(3) b(1) b(2) b(3)', out['out'])
Beispiel #25
0
    def test_user_stats(self):
        '''
        Test user statistics.
        '''
        def on_statistics(step, accu):
            step['test'] = {'a': 0, 'b': [1, 2], 'c': {'d': 3}}
            accu['test'] = step['test']
            step['test'] = {
                'a': lambda a: a + 1,
                'e': lambda a: 4 if a is None else 0,
                'b': [-1, 2, 3]
            }
            self.assertEqual(len(step['test']), 4)
            self.assertEqual(len(step['test']['b']), 3)
            self.assertEqual(len(step['test']['c']), 1)
            self.assertIn('a', step['test'])
            self.assertEqual(sorted(step['test']), ['a', 'b', 'c', 'e'])
            self.assertEqual(sorted(step['test'].keys()), ['a', 'b', 'c', 'e'])
            self.assertEqual(sorted(step['test']['c'].items()), [('d', 3.0)])
            self.assertEqual(sorted(step['test']['c'].values()), [3.0])

            step['test']['b'][1] = 99
            self.assertEqual(step['test']['b'][1], 99)
            step['test']['b'].extend([3, 4])
            step['test']['b'] += [3, 4]

        ctl = Control(['-t', '2', '--stats=2'])
        ctl.add('base', [], '1 { a; b }.')
        ctl.ground([('base', [])])
        ctl.solve(on_statistics=on_statistics)
        stats = ctl.statistics
        self.assertEqual(
            stats['user_step']['test'], {
                'a': 1.0,
                'b': [-1.0, 99.0, 3.0, 3.0, 4.0, 3.0, 4.0],
                'c': {
                    'd': 3.0
                },
                'e': 4.0
            })
        self.assertEqual(stats['user_accu']['test'], {
            'a': 0,
            'b': [1, 2],
            'c': {
                'd': 3
            }
        })
Beispiel #26
0
    def test_error_handling(self):
        '''
        Test basic error handling during solving.
        '''
        ctl = Control()
        ctl.add('base', [], '1 {a; b} 1.')
        ctl.ground([('base', [])])

        self.assertRaises(ZeroDivisionError,
                          lambda: ctl.solve(on_model=lambda m: 1 / 0))

        with ctl.solve(on_model=lambda m: 1 / 0, yield_=True) as handle:
            self.assertRaises(ZeroDivisionError, lambda: [_ for _ in handle])

        # Note: currently clasp does not store and re-raise the exception in
        # asynchronous mode, so we get a runtime error instead
        with ctl.solve(on_model=lambda m: 1 / 0, async_=True) as handle:
            self.assertRaises(RuntimeError, handle.get)
Beispiel #27
0
 def test_theory_with_guard(self):
     '''
     Test observer via grounding.
     '''
     ctl = Control()
     obs = TestObserverTheoryWithGuard(self)
     ctl.register_observer(obs)
     ctl.add(
         'base', [], '''\
     #theory test {
         t { };
         &a/0 : t, {=}, t, head
     }.
     &a { } = a.
     ''')
     ctl.ground([('base', [])])
     self.assertIn('theory_term_string: a', obs.called)
     self.assertIn('theory_term_string: =', obs.called)
     self.assertIn('theory_atom_with_guard', obs.called)
     ctl.solve()
Beispiel #28
0
    def __init__(self, horizon=0):
        self.__horizon = horizon
        self.__prg = Control(['-t4'])
        self.__future = None
        self.__solution = None
        self.__assign = []

        self.__prg.load("board.lp")
        self.__prg.load("robots.lp")
        parts = [ ("base", [])
                , ("check", [Number(0)])
                , ("state", [Number(0)])
                ]
        for t in range(1, self.__horizon+1):
            parts.extend([ ("trans", [Number(t)])
                         , ("check", [Number(t)])
                         , ("state", [Number(t)])
                         ])
        self.__prg.ground(parts)
        self.__prg.assign_external(Function("horizon", [Number(self.__horizon)]), True)
Beispiel #29
0
    def solve_instance(self):
        prg = Control()

        prg.load("puzzle15.lp")
        prg.load(self.new_filename)
        ret, parts, step = SolveResult.unsatisfiable, [], 1
        parts.append(("base", []))
        while ret == SolveResult.unsatisfiable:
            parts.append(("step", [step]))
            parts.append(("check", [step]))
            prg.ground(parts)
            prg.release_external(Function("query", [step - 1]))
            prg.assign_external(Function("query", [step]), True)
            #f = lambda m: stdout.write(str(m)+'\n')
            print("step:" + str(step) + " Solving...")
            ret, parts, step = prg.solve(on_model=self.on_model), [], step + 1
            if ret.__repr__() == 'UNSAT':
                ret = SolveResult.unsatisfiable
            else:
                ret = SolveResult.satisfiable
Beispiel #30
0
def main():
    # Create a Control object that will unify models against the appropriate
    # predicates. Then load the asp file that encodes the problem domain.
    ctrl = Control(unifier=[Driver, Item, Assignment])
    ctrl.load(ASP_PROGRAM)

    # Dynamically generate the instance data
    drivers = [Driver(name=n) for n in ["dave", "morri", "michael"]]
    items = [Item(name="item{}".format(i)) for i in range(1, 6)]
    instance = FactBase(drivers + items)

    # Add the instance data and ground the ASP program
    ctrl.add_facts(instance)
    ctrl.ground([("base", [])])

    # Generate a solution - use a call back that saves the solution
    solution = None

    def on_model(model):
        nonlocal solution
        solution = model.facts(atoms=True)

    ctrl.solve(on_model=on_model)
    if not solution:
        raise ValueError("No solution found")

    # Do something with the solution - create a query so we can print out the
    # assignments for each driver.

    #    query=solution.select(Assignment).where(lambda x,o: x.driver == o)
    query=solution.query(Driver,Assignment)\
                  .join(Driver.name == Assignment.driver)\
                  .group_by(Driver.name).order_by(Assignment.time).select(Assignment)
    for d, aiter in query.all():
        assignments = list(aiter)
        if not assignments:
            print("Driver {} is not working today".format(d))
        else:
            print("Driver {} must deliver: ".format(d))
            for a in assignments:
                print("\t Item {} at time {}".format(a.item, a.time))