コード例 #1
0
ファイル: classify.py プロジェクト: ysard/caspo
def __learn_io__(networks, setup, configure):
    encoding = os.path.join(os.path.dirname(__file__),
                            'encodings/classify/io.lp')
    setup_fs = setup.to_funset()

    behaviors = core.LogicalNetworkList.from_hypergraph(networks.hg)
    for rep in networks:
        found = False
        nlist = core.LogicalNetworkList.from_hypergraph(networks.hg, [rep])
        for i, behavior in enumerate(behaviors):
            blist = core.LogicalNetworkList.from_hypergraph(
                networks.hg, [behavior])
            fs = setup_fs.union(nlist.concat(blist).to_funset())
            instance = ". ".join(map(str, fs)) + "."

            clingo = gringo.Control()
            if configure is not None:
                configure(clingo.conf)

            clingo.add("base", [], instance)
            clingo.load(encoding)

            clingo.ground([("base", [])])
            if clingo.solve() == gringo.SolveResult.UNSAT:
                found = True
                behaviors.add_network(i, rep)
                break

        if not found:
            behaviors.append(rep)

    return behaviors
コード例 #2
0
ファイル: pyclingo.py プロジェクト: abbuser/unicl
def test():
    print("solve something")
    c = gringo.Control(["0"])
    c.add("base", [], "1{a;b;p(@test2())}.")
    c.ground("base", [])
    with c.iterSolve() as it:
        for m in it:
            print m

    print("solve something different")
    d = gringo.Control(["0"])
    d.add("base", [], "1{b;c;p(@test3())}.")
    d.ground("base", [])
    with d.iterSolve() as it:
        for m in it:
            print m
コード例 #3
0
def ground(kind):
    global control, scratch, verbose, sources, options, objects, horizon

    count = objects+horizon+1
    parts = [("expand", [count])]

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

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

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

    if verbose:
         print
         print "Objects:", objects
         print "Horizon:", horizon

    control.ground(parts)

    if verbose:
         print "Solving:", count
コード例 #4
0
    def __get_clingo__(self, encodings, args=None):
        clingo = gringo.Control(args or [])

        clingo.add("base", [], self.instance)
        for enc in encodings:
            clingo.load(self.encodings[enc])

        return clingo
コード例 #5
0
ファイル: controller.py プロジェクト: abuzreq/Taksim
 def __init__(self):
     self.k = 0
     self.prg = gringo.Control()
     self.prg.load("client.lp")
     self.prg.ground([("pigeon", []), ("sleep", [self.k])])
     self.prg.assign_external(Fun("sleep", [self.k]), True)
     self.ret = SolveResult.UNKNOWN
     self.models = []
コード例 #6
0
ファイル: control.py プロジェクト: ysard/caspo
    def control(self, size=0, configure=None):
        """
        Finds all inclusion-minimal intervention strategies up to the given size.
        Intervention strategies found are saved in the attribute :attr:`strategies`
        as a :class:`caspo.core.clamping.ClampingList` object instance.

        Example::

            >>> from caspo import core, control

            >>> networks = core.LogicalNetworkList.from_csv('networks.csv')
            >>> scenarios = control.ScenarioList('scenarios.csv')

            >>> controller = control.Controller(networks, scenarios)
            >>> controller.control()

            >>> controller.strategies.to_csv('strategies.csv')

        Parameters
        ----------
        size : int
            Maximum number of intervention per intervention strategy

        configure : callable
            Callable object responsible of setting clingo configuration
        """
        self._strategies = []

        clingo = gringo.Control(['-c maxsize=%s' % size])

        clingo.conf.solve.models = '0'
        if configure:
            def overwrite(args, proxy):
                for i in xrange(args.threads):
                    proxy.solver[i].no_lookback = 'false'
                    proxy.solver[i].heuristic = 'domain'
                    proxy.solver[i].dom_mod = '5,16'

            configure(clingo.conf, overwrite)
        else:
            clingo.conf.solver.no_lookback = 'false'
            clingo.conf.solver.heuristic = 'domain'
            clingo.conf.solver.dom_mod = '5,16'

        clingo.conf.solve.enum_mode = 'domRec'

        clingo.add("base", [], self.instance)
        clingo.load(self.encodings['control'])

        clingo.ground([("base", [])])
        clingo.solve(on_model=self.__save__)

        self.stats['time_optimum'] = clingo.stats['time_solve']
        self.stats['time_enumeration'] = clingo.stats['time_total']

        self._logger.info("%s optimal intervention strategies found in %.4fs", len(self._strategies), self.stats['time_enumeration'])

        self.strategies = core.ClampingList(self._strategies)
コード例 #7
0
    def __init__(self, script_args, control_args):
        Solver.__init__(self, script_args)
        self.__prg = gringo.Control(control_args)
        self.add_const(self.__prg)
        for f in script_args.file:
            self.__prg.load(f)

        self.__prg.add("check", ["t"], "#external query(t).")
        self.__future = None
コード例 #8
0
ファイル: identify.py プロジェクト: misbahch6/caspo-ts
 def default_control(self, *args):
     control = gringo.Control(
         ["--conf=trendy", "--stats", "--opt-strat=usc"] + list(args))
     for f in self.domain:
         control.load(f)
     control.load(aspf("supportConsistency.lp"))
     control.load(aspf("normalize.lp"))
     control.add("base", [], self.data)
     return control
コード例 #9
0
 def __init__(self, connection):
     Thread.__init__(self)
     self.k   = 0
     self.prg = gringo.Control()
     self.prg.load("client.lp")
     self.prg.ground([("pigeon", []), ("sleep",  [self.k])])
     self.prg.assign_external(Fun("sleep", [self.k]), True)
     self.state = SolveThread.STATE_IDLE
     self.input = Connection()
     self.output = connection
コード例 #10
0
 def solve(self):
     locale.setlocale(locale.LC_ALL, 'C')
     ctl = gringo.Control(['-Wno-atom-undefined','-t8'])
     ctl.load(self.aspfile)
     #ctl.conf.solve.models = 0 if self.solveMode in ["all","optN"] else self.solveMode
     #if self.solveMode == 'optN':
     #    ctl.conf.solve.opt_mode = 'optN'
     ctl.ground([("base", [])])
     #self.result = ctl.solve(assumptions = None, on_model = self.__on_model)
     ctl.solve(assumptions = None, on_model = self.__on_model)
     print(ctl.stats['time_total'],ctl.stats['lp']['atoms'])
コード例 #11
0
ファイル: storygen.py プロジェクト: cblop/oddjob
def storygen(characters):
    prg = gringo.Control()
    prg.load("story.lp")
    prg.ground([("base", [])])
    res = prg.solve(None, on_model)
    print("solving...")
    print(story)
    while True:
        if story:
            if (len(story) / 5) == scenes:
                return story
コード例 #12
0
ファイル: identify.py プロジェクト: misbahch6/myforkedrep
    def default_control(self, *args):
        control = gringo.Control(["--conf=trendy", "--stats",
                            "--opt-strat=usc"] + list(args))
        for f in self.domain:
            control.load(f)
        if not self.nodataset:
            control.load(aspf("supportConsistency.lp"))
            control.load(aspf("normalize.lp"))
        control.add("base", [], self.data)

        if self.opts.clingo_parallel_mode:
            control.conf.solve.parallel_mode = self.opts.clingo_parallel_mode

        return control
コード例 #13
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 = gringo.Control()
        ctl.load("board.lp")
        ctl.ground([("base", [])])
        ctl.solve(on_model=self.__on_model)
コード例 #14
0
    def __init__(self, horizon=0):
        self.__horizon = horizon
        self.__prg = gringo.Control(['-t4'])
        self.__future = None
        self.__solution = None
        self.__assign = []

        self.__prg.load("board.lp")
        self.__prg.load("robots.lp")
        parts = [("base", []), ("check", [0]), ("state", [0])]
        for t in range(1, self.__horizon + 1):
            parts.extend([("trans", [t]), ("check", [t]), ("state", [t])])
        self.__prg.ground(parts)
        self.__prg.assign_external(gringo.Fun("horizon", [self.__horizon]),
                                   True)
コード例 #15
0
def compute_backdoor(l, threads):
    if threads:
        raise NotImplemented
    logging.info('Generate LP instance')
    ctl = gringo.Control()
    ctl.load("vc.lp")
    logging.info('Grounding rules')
    define_edges(l, ctl)
    ctl.ground([("base", [])])
    logging.info('Solving LP instance...')
    vc = AnswerSet()
    f = ctl.solve_async(on_model=vc.update_model)
    f.wait()
    logging.warning('=' * 80)
    logging.warning('Solution value  = %s', vc.optimization)
    return imap(lambda x: l.symtab.tab[x], vc.iter_edges())
コード例 #16
0
 def start(self, step):
     self.__prg = gringo.Control(self.__control_args)
     self.add_const(self.__prg)
     for f in self.__script_args.file:
         self.__prg.load(f)
     self.__prg.add("base", [], "query({0}).".format(step))
     self.__step = step
     for i in range(0, step + 1):
         parts = []
         parts.append(("check", [i]))
         if i > 0:
             parts.append(("step", [i]))
             self.__prg.cleanup_domains()
         else:
             parts.append(("base", []))
         self.__prg.ground(parts)
     self.__future = self.__prg.solve_async(on_finish=self.on_finish)
コード例 #17
0
ファイル: ASPHandlerNew.py プロジェクト: mfcardenas/OLED
 def solve(aspFile, solveMode, task):
     print('test')
     solvingTime = 0.0
     grndPrgSize = 0.0
     locale.setlocale(locale.LC_ALL, 'C')
     ctl = gringo.Control(['-Wno-atom-undefined','-t8'])
     ctl.load(aspFile)
     ctl.conf.solve.models = 0 if solveMode in ["all","optN"] else solveMode
     if solveMode == 'optN':
         ctl.conf.solve.opt_mode = 'optN'
     ctl.ground([("base", [])])
     result = ctl.solve(assumptions = None, on_model = __on_model)
     if task == 'score_rules':
         solvingTime = ctl.stats['time_total']
         grndPrgSize = ctl.stats['lp']['atoms']
         print(solvingTime)
     return (result,solvingTime,grndPrgSize)
コード例 #18
0
ファイル: ASPHandler.py プロジェクト: mfcardenas/OLED
    def solve(self):
        #cores = '-t%d'%(self.getCores())
        locale.setlocale(locale.LC_ALL, 'C')
        ctl = gringo.Control(['-Wno-atom-undefined','-t4'])
        ctl.load(self.aspfile)
        ctl.conf.solve.models = 0 if self.solveMode in ["all","optN"] else self.solveMode
        if self.solveMode == 'optN':
            ctl.conf.solve.opt_mode = 'optN'
        ctl.ground([("base", [])], functions)
        #f = ctl.solve_async(assumptions = None, on_model = self.__on_model, on_finish = self.__on_finish)
        #f.wait()
        self.result = ctl.solve(assumptions = None, on_model = self.__on_model)

        #print(ctl.stats.keys())
        #for k in ctl.stats.keys():
        #    print(k,ctl.stats[k])

        if self.task == 'score_rules':
            self.solvingTime = ctl.stats['time_total']
            self.grndPrgSize = ctl.stats['lp']['atoms']
コード例 #19
0
    def solve(self):
        # There is a very strange behaviour with parallel mode (-t): When running
        # experiments in parallel, there were cases when unnecessary use3 atoms
        # were included in an answer set. This happened only with -t on. The
        # unnecessary atoms lead to NoSuchElement exceptions (when trying to retrieve)
        # the corresponding literal from the map, or to wrong rules.
        # This happened only when running experiments in parallel, when running ILED in
        # a single core the -t option works fine and its ok to use it (it also speeds
        # up the application in cases that you'd have to wait for hours -- at best--
        # to get an answer).

        # ctl = gringo.Control(['-Wno-atom-undefined','-t8']) # -t8: run in parallel using 8 threads
        ctl = gringo.Control(['-Wno-atom-undefined'])
        #ctl = gringo.Control()
        ctl.load(self.aspfile)
        ctl.conf.solve.models = 0
        if self.solveMode == 'optN':
            ctl.conf.solve.opt_mode = 'optN'
        ctl.ground([("base", [])])
        #f = ctl.solve_async(assumptions = None, on_model = self.__on_model, on_finish = self.__on_finish)
        #f.wait()
        self.result = ctl.solve(assumptions=None, on_model=self.__on_model)
コード例 #20
0
ファイル: pyclingo.py プロジェクト: abbuser/unicl
#!/usr/bin/env python

import gringo

print "to begin with"
a = gringo.Control(["0"])
a.add(
    "base", [], """
#script(python)
def test2():
    return 42
#end.
1{a;b;p(@test2())}.
""")
a.ground("base", [])
a.solve()
with a.iterSolve() as it:
    for m in it:
        print m


def test3():
    return 23


def test():
    print("solve something")
    c = gringo.Control(["0"])
    c.add("base", [], "1{a;b;p(@test2())}.")
    c.ground("base", [])
    with c.iterSolve() as it:
コード例 #21
0
#!/usr/bin/env python

import gringo
import json
import sys

control = gringo.Control()
scratch = False

outputs = True
statist = False
verbose = False

sources = []
options = []

objects = 0
horizon = 0

end = 0

def info():
    print "Usage:   main.py [--scratch] [--quiet] [--stats] [--verbose] [--maxobj=n] [--option=\"<option key> <option value>\"]* [logic program files]+"
    print "Example: main.py --scratch --quiet --stats --verbose --maxobj=42 --option=\"solve.models 0\" encoding.lp instance.lp"

def show(model):
    global outputs

    if outputs: print "Model:  ", model.atoms()

def ground(kind):
コード例 #22
0
        urwid.connect_signal(ba, 'click', c.prev)

        sf = urwid.Text("")

        b = urwid.Columns([sf, ('fixed', len(bc.label) + 4, bc), ('fixed', len(ba.label) + 4, ba), ('fixed', len(bb.label) + 4, bb), sf], 1)
        f = urwid.Frame(urwid.Filler(c.display), None, b, 'footer')

        palette = [
            ('red', 'black', 'light red'),
            ('green', 'black', 'light green'),
            ('blue', 'black', 'light blue'), ]

        self.loop = urwid.MainLoop(f, palette)
        self.loop.run()

c = gringo.Control()
c.add("check", ["k"], "#external query(k).")
for f in sys.argv[1:]: c.load(f)
def make_on_model(field, stone, move, target):
    def on_model(m):
        for atom in m.atoms(gringo.Model.ATOMS):
            if atom.name() == "field" and len(atom.args()) == 2:
                x, y = atom.args()
                field.append((x, y))
            elif atom.name() == "stone" and len(atom.args()) == 5:
                s, d, x, y, l = atom.args()
                stone.append((str(s), str(d), x, y, l))
            elif atom.name() == "move" and len(atom.args()) == 4:
                t, s, d, xy = atom.args()
                move.setdefault(t, []).append((str(s), str(d), xy))
            elif atom.name() == "target" and len(atom.args()) == 3:
コード例 #23
0
            directory = os.path.join(path, results)
            #print(directory, end='')
            #shutil.rmtree(directory, ignore_errors=True)
            try:
                #for the_file in os.listdir(directory):
                #    file_path = os.path.join(directory, the_file)
                #    if os.path.isfile(file_path):
                #        os.unlink(file_path)
                os.makedirs(directory)
            except Exception, e:
                pass
            #print(e)
            for i in datasets:
                print(i, end=',')
                #help(gringo)
                control = gringo.Control(
                    ["--conf=trendy", "--stats", "0", "--opt-strat=usc"])
                #print_conf(control.conf, "")
                control.load("guessBN.lp")
                control.load(encoding)
                control.load("minimizeWeightOnly.lp")
                control.load("normalize.lp")
                #		control.load("../../Benchmarks/nets_to_test/1/asp/pkn.lp")
                control.load(os.path.join(path, pkn))
                control.load(os.path.join(path, i))
                control.ground([("base", [])])

                control.load("show.lp")
                control.ground([("show", [])])
                control.assign_external(gringo.Fun("tolerance"), False)

                start = time.time()
コード例 #24
0
ファイル: design.py プロジェクト: ysard/caspo
    def design(self,
               max_stimuli=-1,
               max_inhibitors=-1,
               max_experiments=10,
               relax=False,
               configure=None):
        """
        Finds all optimal experimental designs using up to :attr:`max_experiments` experiments, such that each experiment has
        up to :attr:`max_stimuli` stimuli and :attr:`max_inhibitors` inhibitors. Each optimal experimental design is appended in the
        attribute :attr:`designs` as an instance of :class:`caspo.core.clamping.ClampingList`.

        Example::

            >>> from caspo import core, design
            >>> networks = core.LogicalNetworkList.from_csv('behaviors.csv')
            >>> setup = core.Setup.from_json('setup.json')

            >>> designer = design.Designer(networks, setup)
            >>> designer.design(3, 2)

            >>> for i,d in enumerate(designer.designs):
            ...     f = 'design-%s' % i
            ...     d.to_csv(f, stimuli=self.setup.stimuli, inhibitors=self.setup.inhibitors)



        Parameters
        ----------
        max_stimuli : int
            Maximum number of stimuli per experiment

        max_inhibitors : int
            Maximum number of inhibitors per experiment

        max_experiments : int
            Maximum number of experiments per design

        relax : boolean
            Whether to relax the full-pairwise networks discrimination (True) or not (False).
            If relax equals True, the number of experiments per design is fixed to :attr:`max_experiments`

        configure : callable
            Callable object responsible of setting clingo configuration
        """
        self.designs = []

        args = [
            '-c maxstimuli=%s' % max_stimuli,
            '-c maxinhibitors=%s' % max_inhibitors, '-Wno-atom-undefined'
        ]

        clingo = gringo.Control(args)
        clingo.conf.solve.opt_mode = 'optN'
        if configure is not None:
            configure(clingo.conf)

        clingo.add("base", [], self.instance)
        clingo.load(self.encodings['design'])

        clingo.ground([("base", [])])

        if relax:
            parts = [("step", [step])
                     for step in xrange(1, max_experiments + 1)]
            parts.append(("diff", [max_experiments + 1]))
            clingo.ground(parts)
            ret = clingo.solve(on_model=self.__save__)
        else:
            step, ret = 0, gringo.SolveResult.UNKNOWN
            while step <= max_experiments and ret != gringo.SolveResult.SAT:
                parts = []
                parts.append(("check", [step]))
                if step > 0:
                    clingo.release_external(gringo.Fun("query", [step - 1]))
                    parts.append(("step", [step]))
                    clingo.cleanup_domains()

                clingo.ground(parts)
                clingo.assign_external(gringo.Fun("query", [step]), True)
                ret, step = clingo.solve(on_model=self.__save__), step + 1

        self.stats['time_optimum'] = clingo.stats['time_solve']
        self.stats['time_enumeration'] = clingo.stats['time_total']

        self._logger.info("%s optimal experimental designs found in %.4fs",
                          len(self.designs), self.stats['time_enumeration'])
コード例 #25
0
 def __init__(self, fpath):
     self._prg = gringo.Control()
     self._prg.conf.solve.models = 0 
     self._prg.load(fpath)
     self._prg.ground([("base", [])])