示例#1
0
    def clingo_solve(self, inp):
        print('solving with clingo...')
        num = self.max_time
        ms0 = num
        while True:
            solv = asp_solver.IncrementalSolver(num, self.num_agents,
                                                self.min_sum, self.total_cost,
                                                ms0, True, True)
            clingo.clingo_main(solv, [
                inp, 'bases/baseE.lp', '--opt-strat=usc,disjoint', '--outf=3',
                '--time-limit=300', '-c', 'bound={0}'.format(num)
            ])

            if solv.sol_cost > 0:
                self.sol = solv.resp
                self.check_makespan()
                print('Encontrada Primera Solucion')
                print('\tCosto total: {0}'.format(solv.sol_cost))
                print('\tMakespan: {0}'.format(self.sol_time))

                ms = int(solv.theoric_makespan)
                if ms > num:
                    num = ms
                    solv = asp_solver.IncrementalSolver(
                        num, self.num_agents, self.min_sum, self.total_cost,
                        ms0, True, True)
                    clingo.clingo_main(solv, [
                        inp, 'bases/baseE.lp', '--opt-strat=usc,disjoint',
                        '--outf=3', '--time-limit=300', '-c',
                        'bound={0}'.format(ms)
                    ])
                break

            num += 1

        self.sol = solv.resp
        self.check_makespan()
        print('-----------------')
        print('Encontrada Solucion Optima, Estadisticas Clingo:')
        #print(json.dumps(solv.stats, sort_keys=True, indent=4, separators=(',', ': ')))
        print('Encontrada Solucion')
        print('\tCosto total: {0}'.format(solv.sol_cost))
        print('\tMakespan: {0}'.format(self.sol_time))
        print('-----------------')
示例#2
0
            elif atom.name == "jump" and len(atom.arguments) == 4:
                ox, oy, d, t = ((n.number if n.type == clingo.SymbolType.Number
                                 else str(n)) for n in atom.arguments)
                jumps.setdefault(t, []).append(
                    (ox, oy, ox + sx[d], oy + sy[d]))

        try:
            MainWindow().run(Plan(field, init, jumps))
            return True
        except KeyboardInterrupt:
            return False

    def main(self, prg, files):
        for f in files:
            prg.load(f)
        prg.add("check", ["k"], "#external query(k).")

        t = 0
        sat = False
        prg.ground([("base", [])])
        while not sat:
            t += 1
            prg.ground([("step", [t])])
            prg.ground([("check", [t])])
            prg.release_external(clingo.Function("query", [t - 1]))
            prg.assign_external(clingo.Function("query", [t]), True)
            sat = prg.solve(on_model=self.__on_model).satisfiable


sys.exit(int(clingo.clingo_main(Application("visualize"), sys.argv[1:])))
示例#3
0
def run_problem(instance_path, base_path, results_path, penalty_type,
                results_mode):
    write_type = 'a'
    if results_mode:
        write_type = 'w'

    with open(results_path, write_type) as results:
        if results_mode:
            results.write('sep=;\n')
            results.write(
                'Instance;cost_relax;makespan_relax;First_solved;solved;;'
                '1stOPT;1stSOL-COST;1stMakespan;1stTheoricMakespan;1stRunTime;1stGroundTime;1stGroundPerc;1stAtoms;1stBodies;1stRules;1stTotal;;'
                'OPT;SOL-COST;Makespan;TheoricMakespan;RunTime;GroundTime;GroundPerc;Atoms;Bodies;Rules;Total\n'
            )
            results.flush()

        problem = lp_generator.Problem(50)
        print('reading instance')
        problem.read_instance(instance_path)
        print('generating solution')
        problem.gen_solution()

        buffer_path = 'buffer'
        problem.write_to_lp(buffer_path)

        print('Solving with clingo...')

        start_time = time.time()
        ms_max = problem.max_time
        ground_time = 0
        ground_time0 = 0
        runtime = 0
        runtime0 = 0

        makespan_relax = ms_max + 1
        ms0 = ms_max
        cost_relax = problem.total_cost
        first_solved = False
        solved = False

        solv0 = None
        solv = None

        curr = 300

        elapsed_real = 0

        try:
            while True:
                solv0 = asp_solver.IncrementalSolver(ms_max,
                                                     problem.num_agents,
                                                     problem.min_sum,
                                                     problem.total_cost, ms0,
                                                     penalty_type, False)
                clingo.clingo_main(solv0, [
                    buffer_path, base_path, '--outf=3',
                    '--opt-strat=usc,disjoint',
                    '--time-limit={0}'.format(curr), '-t', '4', '-c',
                    'bound={0}'.format(ms_max)
                ])

                ground_time += solv0.ground_time
                elapsed_real += (solv0.solve_time + solv0.ground_time)

                if solv0.error:
                    break

                curr = int(300 - elapsed_real)
                if curr < 0:
                    break

                if solv0.sol_cost > 0:
                    runtime0 = elapsed_real
                    first_ms = ms_max + 1
                    ms_opt = int(solv0.theoric_makespan)
                    first_solved = True
                    ground_time0 = ground_time

                    if ms_opt == ms_max:
                        solv = solv0
                        solved = True
                        runtime = runtime0
                        final_ms = first_ms
                        break

                    solv = asp_solver.IncrementalSolver(
                        ms_opt, problem.num_agents, problem.min_sum,
                        problem.total_cost, ms0, penalty_type, True)
                    clingo.clingo_main(solv, [
                        buffer_path, base_path, '--outf=3',
                        '--opt-strat=usc,disjoint',
                        '--time-limit={0}'.format(curr), '-t', '4', '-c',
                        'bound={0}'.format(ms_opt)
                    ])

                    ground_time += solv.ground_time
                    if solv.stats is not None:
                        runtime = elapsed_real + (solv.solve_time +
                                                  solv.ground_time)
                        final_ms = check_makespan(solv.resp)
                        summary = solv.stats['summary']
                        solved = True
                    break
                ms_max += 1
        except:
            print(traceback.format_exc())

        row = [instance_path]
        row.append(cost_relax)
        row.append(makespan_relax)

        if first_solved:
            row.append(1)
            row.append(0)
            row.append('\t')

            row.append(format_float(solv0.stats['summary']['costs'][0]))
            row.append(format_float(solv0.sol_cost))
            row.append(first_ms)
            row.append(int(solv0.theoric_makespan) + 1)
            row.append(format_float(runtime0))
            row.append(format_float(ground_time0))
            row.append(format_float(ground_time0 / runtime0 * 100))
            row.append(format_float(solv0.stats['problem']['lp']['atoms']))
            row.append(format_float(solv0.stats['problem']['lp']['bodies']))
            row.append(format_float(solv0.stats['problem']['lp']['rules']))
            row.append(
                format_float(solv0.stats['problem']['lp']['atoms'] +
                             solv0.stats['problem']['lp']['bodies'] +
                             solv0.stats['problem']['lp']['rules']))
            row.append('\t')

            if solved:
                row[4] = 1
                row.append(format_float(solv.stats['summary']['costs'][0]))
                row.append(format_float(solv.sol_cost))
                row.append(final_ms)
                row.append(int(solv.theoric_makespan) + 1)
                row.append(format_float(runtime))
                row.append(format_float(ground_time))
                row.append(format_float(ground_time / runtime * 100))
                row.append(format_float(solv.stats['problem']['lp']['atoms']))
                row.append(format_float(solv.stats['problem']['lp']['bodies']))
                row.append(format_float(solv.stats['problem']['lp']['rules']))
                row.append(
                    format_float(solv.stats['problem']['lp']['atoms'] +
                                 solv.stats['problem']['lp']['bodies'] +
                                 solv.stats['problem']['lp']['rules']))

        else:
            row.append(0)
            row.append(0)

        results.write(';'.join(map(str, row)) + '\n')
        results.flush()
示例#4
0
    def _main(self, ctl):
        step, ret = 0, None
        while ((self._imax is None or step < self._imax)
               and (step == 0 or step < self._imin or
                    ((self._istop == "SAT" and not ret.satisfiable) or
                     (self._istop == "UNSAT" and not ret.unsatisfiable) or
                     (self._istop == "UNKNOWN" and not ret.unknown)))):
            parts = []
            parts.append(("base", [Number(step)]))
            parts.append(("static", [Number(step)]))
            if step > 0:
                ctl.release_external(Function("finally", [Number(step - 1)]))
                parts.append(("dynamic", [Number(step)]))
            else:
                parts.append(("initial", [Number(0)]))
            ctl.ground(parts)
            ctl.assign_external(Function("finally", [Number(step)]), True)
            ret, step = ctl.solve(), step + 1

    def main(self, ctl, files):
        with ast.ProgramBuilder(ctl) as bld:
            ptf = ProgramTransformer(Function("__t"))
            ast.parse_files(files, lambda stm: bld.add(ptf(stm)))
        ctl.add("initial", ["t"], "initially(t).")
        ctl.add("static", ["t"], "#external finally(t).")
        self._main(ctl)


exit(clingo_main(TModeApp()))
示例#5
0
if __name__ == '__main__':
    instance_dir = 'benchmarks/random_graphs/'
    graph_instances = os.listdir(instance_dir)
    graph_instances.sort(
        key=lambda x: (get_parameters(x)[0], get_parameters(x)[1]))

    running_times = {}

    for idx, g in enumerate(graph_instances):
        num_nodes, p = get_parameters(g)
        graph_path = os.path.join(instance_dir, g)
        current_files = [
            'benchmarks/relaxed_clique.lpmln', graph_path, '--outf=3'
        ]
        start = time.time()
        exit_code = clingo_main(LPMLNApp(), current_files)
        end = time.time()

        running_times[str(idx)] = {
            'N': num_nodes,
            'p': p,
            'time': end - start,
            'file': g
        }
        with open('running_times.json', 'w') as fp:
            json.dump(running_times, fp)

        print(f'\n Num. nodes: {num_nodes}, probability: {p}')
        print(end - start)
示例#6
0
def main():
    """
    Run the xorro application.
    """
    _sys.exit(int(_clingo.clingo_main(Application("xorro"), _sys.argv[1:])))
示例#7
0
def main_clingo(args=None):
    sys.exit(int(clingo.clingo_main(Application(), sys.argv[1:])))
示例#8
0
'''
Module providing the clingo-like pyclingo application.
'''
from clingo import Application, clingo_main


class PyClingoApplication(Application):
    '''
    This is an example app mimimicking clingo.
    '''
    program_name = "pyclingo"

    def main(self, control, files):
        for file_ in files:
            control.load(file_)
        if not files:
            control.load('-')
        control.ground([('base', [])])
        control.solve()


if __name__ == '__main__':
    clingo_main(PyClingoApplication())

class MultiJobShopApp(clingo.Application):
    program_name = "multi-jobshop"
    version = "1.0"

    def __init__(self):
        self._model = None

    def _on_model(self, model):
        if model.optimality_proven:
            self._model = model.symbols(shown=True)

    def main(self, ctl, files):
        for path in files:
            ctl.load(path)
        if not files:
            ctl.load("-")
        ctl.ground([("base", [])], context=self)
        # for every time window
        for window in range(1, ctl.get_const("w").number + 1):
            # do something else...
            ctl.solve(on_model=self._on_model)
        if self._model:
            print("Answer:\n{}".format(" ".join(
                [str(atom) for atom in self._model])))


if __name__ == "__main__":
    clingo.clingo_main(MultiJobShopApp(), sys.argv[1:])
示例#10
0
        symbols = model.symbols(theory=True)
        assignment = []
        for symbol in sorted(symbols):
            if symbol.match("__lpx", 2):
                args = symbol.arguments
                assignment.append(f"{args[0]}={args[1].string}")
        sys.stdout.write(" ".join(assignment))
        sys.stdout.write('\n')

        sys.stdout.flush()

    def main(self, control, files):
        self.__theory.register(control)

        with ast.ProgramBuilder(control) as bld:
            ast.parse_files(files, lambda stm: self.__theory.rewrite_ast(stm, bld.add))

        control.ground([("base", [])])
        self.__theory.prepare(control)

        control.solve(on_model=self.__on_model, on_statistics=self.__on_statistics)

    def __on_model(self, model):
        self.__theory.on_model(model)

    def __on_statistics(self, step, accu):
        self.__theory.on_statistics(step, accu)

if __name__ == "__main__":
    sys.exit(int(clingo.clingo_main(Application("clingo-lpx"), sys.argv[1:])))
示例#11
0
import sys
import clingo
import json


class Application:
    def __init__(self, name, minimum_time):
        self.program_name = name
        self.minimum_time = minimum_time

    def main(self, ctl, files):
        if len(files) > 0:
            for f in files:
                ctl.load(f)
        else:
            ctl.load("-")
        ctl.ground([("base", [])])
        ret = ctl.solve()
        print(
            json.dumps(ctl.statistics,
                       sort_keys=True,
                       indent=4,
                       separators=(',', ': ')))


if __name__ == '__main__':
    print(sys.argv)
    app = Application(sys.argv[0], 20)
    ret = clingo.clingo_main(app, sys.argv[1:])
示例#12
0
        self.theory = thy
        thy.register(ctl)
        with ProgramBuilder(ctl) as bld:
            parse_files(files, lambda ast: thy.rewrite_ast(ast, bld.add))

        pareto_propagator = ParetoPropagator(thy, self.mode)
        self.propagator = pareto_propagator
        ctl.register_propagator(pareto_propagator)

        ctl.ground([('base', [])])
        thy.prepare(ctl)
        thy.configure("propagate", self.dl_propagation_mode)

        if self.mode == "breadth":
            ctl.solve(on_model=self.on_model,
                      on_finish=self.print_front,
                      on_statistics=self._on_statistics)
        elif self.mode == "depth":
            models = 0
            while models < self.nr_models or self.nr_models == 0:
                r = ctl.solve(
                    on_model=self.on_model,
                    on_finish=lambda m: self.print_single(models + 1, m),
                    on_statistics=self._on_statistics)
                if r.unsatisfiable: return
                models += 1
                self.propagator.save_best()


sys.exit(clingo_main(DSEApp(), sys.argv[1:]))
示例#13
0
def run_problem(problem_folder, base_path, results_path, instance_name, window_size):
    with open(results_path, 'a') as results:
        path = '../problems/original/{0}/Instances/{1}'.format(problem_folder, instance_name)
        #path = 'Instance-8-10-4-0'
        #path = 'brc202d-70-0'
        #path = 'ost003d-70-0'


        problem = lp_generator.Problem(window_size)
        print('reading instance')
        problem.read_instance(path)
        print('generating solution')
        problem.gen_solution()


        window_id = 0
        #path = 'problems/asp/{0}/{1}-{2}'.format(problem_folder,instance_name, window_id)
        path = 'buffer'       
        print('Solving with clingo...')
        start_time = time.time()
        max_bound = problem.max_time
        print(max_bound)
        ground_time = 0
        curr_time = 600
        solved = False

        current_makespan = 0
        current_costs = []
        current_penalty = []
        total_cost = 0

        for ag in range(problem.num_agents):
            current_costs.append(0)
            current_penalty.append(0)

        problem.write_to_lp_window(path, problem.agents_pos, current_penalty)
        while True:
            current_makespan += window_size
            solv = asp_solver.IncrementalSolver('{0}.lp'.format(path), problem.num_agents, window_size)
            clingo.clingo_main(solv, ['{0}.lp'.format(path), '{0}.lp'.format(base_path), '--opt-strat=usc,disjoint','--outf=3','--time-limit={0}'.format(curr_time), '-t', '4', '-c', 'window_bound={0}'.format(window_size)])
            window_id+=1
            
            ground_time += solv.ground_time

            elapsed = time.time() - start_time
            curr_time = int(600.0 - elapsed)
            print(elapsed)
            if curr_time < 0:
                break

            if solv.sol_cost < 0:
                break

            solved_agents = problem.check_solved(solv.final_pos)
            all_solved = True
            total_cost = 0
            for ag in range(problem.num_agents):
                if solved_agents[ag]:
                    current_penalty[ag] += window_size - (solv.current_costs[ag] - solv.reset_penalty[ag])
                else:
                    all_solved = False
                    
                current_costs[ag] += solv.current_costs[ag]
                total_cost += current_costs[ag]

            #print(current_costs)
            if all_solved:
                solved = True
                break
            
            #x = input()
            #path = 'problems/asp/{0}/{1}-{2}'.format(problem_folder,instance_name, window_id)
            path = 'buffer'
            problem.write_to_lp_window(path, solv.final_pos, current_penalty)

        row = [instance_name]

        if solved:
            row.append(1)
        else:
            row.append(0)
        
        row.append(ground_time)
        row.append(elapsed)
        row.append(total_cost)
        row.append(window_id)
        row.append(window_size)
        results.write(';'.join(map(str, row)) + '\n')
        results.flush()
示例#14
0
def run_problem(problem_folder, base_path, results_path, instance_name):
    with open(results_path, 'a') as results:

        path = 'problems/original/{0}/Instances/{1}'.format(
            problem_folder, instance_name)

        problem = lp_generator.Problem(50, 0, 0)
        print('reading instance')
        problem.read_instance(path)
        print('generating solution')
        problem.gen_solution()

        path = 'problems/asp/{0}/{1}'.format(problem_folder, instance_name)
        problem.write_to_lp(path)

        print('Solving with clingo...')

        start_time = time.time()
        num = problem.max_time
        ground_time = 0
        ground_time0 = 0
        runtime = 0
        runtime0 = 0

        print(num)
        first_solved = False
        solved = False

        solv0 = None
        solv = None

        curr = 300

        while True:

            solv0 = asp_solver.IncrementalSolver('{0}.lp'.format(path), num,
                                                 problem.num_agents,
                                                 problem.min_sum,
                                                 problem.total_cost, 4, False)
            clingo.clingo_main(solv0, [
                '{0}.lp'.format(path), '{0}.lp'.format(base_path), '--outf=3',
                '--opt-strat=usc,disjoint', '--time-limit={0}'.format(curr),
                '-t', '4', '-c', 'bound={0}'.format(num)
            ])
            #print(solv0.ground_time)
            ground_time += solv0.ground_time

            elapsed = time.time() - start_time
            curr = int(300 - elapsed)
            print(curr)

            if curr < 0:
                break

            if solv0.sol_cost > 0:
                runtime0 = time.time() - start_time
                ms = int(solv0.theoric_makespan)
                first_solved = True
                ground_time0 = ground_time

                print(ms)
                if ms == num:
                    solv = solv0
                    solved = True
                    runtime = runtime0
                    break

                solv = asp_solver.IncrementalSolver('{0}.lp'.format(path), ms,
                                                    problem.num_agents,
                                                    problem.min_sum,
                                                    problem.total_cost, 4,
                                                    False)
                clingo.clingo_main(solv, [
                    '{0}.lp'.format(path), '{0}.lp'.format(base_path),
                    '--outf=3', '--opt-strat=usc,disjoint',
                    '--time-limit={0}'.format(curr), '-t', '4', '-c',
                    'bound={0}'.format(ms)
                ])

                ground_time += solv.ground_time
                if solv.stats is not None:
                    runtime = time.time() - start_time
                    summary = solv.stats['summary']
                    solved = True
                break
            num += 1
            print(num)

        #sol = solv.resp
        row = [instance_name]
        #print(solv.sol_cost)

        if first_solved:

            #print(json.dumps(solv.stats, sort_keys=True, indent=4, separators=(',', ': ')))

            row.append(1)
            row.append(0)
            row.append('\t')

            row.append(format_float(solv0.stats['summary']['costs'][0]))
            row.append(format_float(solv0.sol_cost))
            row.append('-1')
            row.append(int(solv0.theoric_makespan))
            row.append(format_float(runtime0))
            row.append(format_float(ground_time0))
            row.append(format_float(ground_time0 / runtime0 * 100))
            row.append(format_float(solv0.stats['problem']['lp']['atoms']))
            row.append(format_float(solv0.stats['problem']['lp']['bodies']))
            row.append(format_float(solv0.stats['problem']['lp']['rules']))
            row.append(
                format_float(solv0.stats['problem']['lp']['atoms'] +
                             solv0.stats['problem']['lp']['bodies'] +
                             solv0.stats['problem']['lp']['rules']))
            row.append('\t')

            if solved:
                row[2] = 1
                row.append(format_float(solv.stats['summary']['costs'][0]))
                row.append(format_float(solv.sol_cost))
                row.append('-1')
                row.append(int(solv.theoric_makespan))
                row.append(format_float(runtime))
                row.append(format_float(ground_time))
                row.append(format_float(ground_time / runtime * 100))
                row.append(format_float(solv.stats['problem']['lp']['atoms']))
                row.append(format_float(solv.stats['problem']['lp']['bodies']))
                row.append(format_float(solv.stats['problem']['lp']['rules']))
                row.append(
                    format_float(solv.stats['problem']['lp']['atoms'] +
                                 solv.stats['problem']['lp']['bodies'] +
                                 solv.stats['problem']['lp']['rules']))

        else:
            row.append(0)
            row.append(0)

        #print(elapsed)
        #print(solv.resp)
        #print(check_makespan(solv.resp))

        results.write(';'.join(map(str, row)) + '\n')
        results.flush()
示例#15
0
文件: lpmln.py 项目: nrueh/LPMLN
        with ctl.solve(yield_=True) as handle:
            for model in handle:
                if self.display_all_probs or self.query != []:
                    model_costs.append(model.cost)
                    if self.query != []:
                        self._check_model_for_query(model)

        if model_costs != [] and (self.display_all_probs or self.query != []):
            if 0 not in observer.priorities:
                # TODO: Should this be error or warning?
                print(
                    'No soft weights in program. Cannot calculate probabilites'
                )
            # TODO: What about case where there are other priorities than 0/1?
            # elif not self.two_solve_calls and any(
            #         x > 1 for x in observer.priorities):
            #     print(observer.priorities)
            #     print('testasd')
            else:
                probs = ProbabilityModule(
                    model_costs, observer.priorities,
                    [self.translate_hard_rules, self.two_solve_calls])
                if self.display_all_probs:
                    probs.print_probs()
                if self.query != []:
                    probs.get_query_probability(self.query)


if __name__ == '__main__':
    sys.exit(int(clingo_main(LPMLNApp(), sys.argv[1:])))
示例#16
0
def run(problem_path, lp_path, base_path, landmarks, overflow):
    num_landmarks = int(landmarks)
    num_overflow = int(overflow)

    problem = lp_generator.Problem(50, num_landmarks, num_overflow)
    print('reading instance')
    problem.read_instance(problem_path)
    print('generating solution')
    problem.gen_solution()

    problem.write_to_lp(lp_path)

    print('Solving with clingo...')
    return

    start_time = time.time()
    num_makespan = problem.max_time + num_overflow
    ground_time = 0
    runtime = 0
    first_solved = False
    solved = False

    curr_time = 300
    print(num_makespan)

    solv0 = asp_solver.IncrementalSolver('{0}.lp'.format(lp_path),
                                         num_makespan, problem.num_agents,
                                         problem.min_sum, problem.total_cost,
                                         4, True)
    clingo.clingo_main(solv0, [
        '{0}.lp'.format(lp_path), '{0}'.format(base_path),
        '--time-limit={0}'.format(curr_time), '-t', '4', '-c',
        'bound={0}'.format(num_makespan), '-c',
        'lbound={0}'.format(num_landmarks), '--opt-strategy=usc,disjoint',
        '--text'
    ])
    print(solv0.resp)
    print('found solution: ')
    print('\t total_cost: {0}'.format(solv0.sol_cost))
    #print('\t makespan: {0}'.format(check_makespan(solv.resp)))

    return

    while curr_time >= 0:

        print('solving with makespan: {0}'.format(num_makespan + 1))
        solv0 = asp_solver.IncrementalSolver('{0}.lp'.format(lp_path),
                                             num_makespan, problem.num_agents,
                                             problem.min_sum,
                                             problem.total_cost, 4, True)
        clingo.clingo_main(solv0, [
            '{0}.lp'.format(lp_path), '{0}'.format(base_path), '--outf=3',
            '--opt-strat=usc,disjoint', '--time-limit={0}'.format(curr_time),
            '-t', '4', '-c', 'bound={0}'.format(num_makespan)
        ])
        ground_time += solv0.ground_time
        elapsed = time.time() - start_time
        curr_time = int(300 - elapsed)
        if curr_time < 0:
            break

        if solv0.sol_cost > 0:
            runtime0 = time.time() - start_time
            ms = int(solv0.theoric_makespan)
            first_solved = True
            ground_time0 = ground_time

            if ms == num_makespan:
                solv = solv0
                solved = True
                runtime = runtime0
                break

            print('solving with makespan: {0}'.format(ms + 1))
            solv = asp_solver.IncrementalSolver('buffer.lp'.format(lp_path),
                                                ms, problem.num_agents,
                                                problem.min_sum,
                                                problem.total_cost, 4, True)
            clingo.clingo_main(solv, [
                '{0}.lp'.format(lp_path), '{0}'.format(base_path), '--outf=3',
                '--opt-strat=usc,disjoint',
                '--time-limit={0}'.format(curr_time), '-t', '4', '-c',
                'bound={0}'.format(ms)
            ])
            ground_time += solv.ground_time
            if solv.stats is not None:
                runtime = time.time() - start_time
                ground_time += solv.ground_time
                solved = True
            break
        num_makespan += 1

    print('----------')
    if solved:
        print('found solution: ')
        print('\t total_cost: {0}'.format(solv.sol_cost))
        #print('\t makespan: {0}'.format(check_makespan(solv.resp)))
        print('\t runtime: {0} seconds'.format(runtime))
        print('\t ground_time: {0} seconds'.format(ground_time))
    else:
        print('No solution found')
示例#17
0
def run_test(solver_type, problem_folder, call_extra, only_first_sol, base_path):
    opt_makespans = []
    if solver_type == 2:
        with open('problems/original/{0}/opt_makespan'.format(problem_folder), 'r') as in_file:
            opt_makespans = [int(line.strip()) for line in in_file]



    with open('results/results_{0}_{1}_last.csv'.format(problem_folder, base_path.split('/')[-1]), 'w') as results:
        results.write('sep=;\n')
        '''
        results.write('Instance; First_solved;solved;Models; Optimum; Calls;Threads;MIN-Timestep;Min-SUMTIME; ;'
            '1stTime(Total); 1stTime(Solving);1stTime(Unsat); 1stCPU Time;1stOptimization;1stSOL-COST; 1st Makespan; ;'
            'OPT - Optimization; OPT- Time(Total); OPT-Time(Solving); OPT-Time(Unsat); OPT-CPU Time; OPT-SOL-COST; Last-Makespan ;OPT-Makespan; OPT-Solved;' 
            'Moved On Goal; Theoric Makespan; 1stRunTime ;Total RunTime; Ground Time; Percent Grounding; Called Extra; Atoms; Bodies; Rules; Total\n')
        '''
        
        results.write('Instance; First_solved;solved;;'
            '1stOPT;1stSOL-COST;1stMakespan;1stTheoricMakespan;1stRunTime;1stGroundTime;1stGroundPerc;1stAtoms;1stBodies;1stRules;1stTotal;;'
            'OPT;SOL-COST;Makespan;TheoricMakespan;RunTime;GroundTime;GroundPerc;Atoms;Bodies;Rules;Total\n')

        print(base_path.split('/')[-1])


        i = 1
        #l1 = [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
        #l1 = [0,5,10,15,20,25,30]
        #l1 = [12,18,24,30]
        #l1 = [14,16,18,20,22,24,26,28,30]
        #l1 = [40,45,50,55,60,65,70,75,80]
        l1 = [20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50]
        #l1 = [42,44,46,48,50]
        #l1 = [1,60,65,70,75,80,85,90,95,100,100]
        #l1 = [42,44,46,48,50]
        l1 = [50]
        for x in l1:
            for y in range(10):
                name = 'Instance-20-10-{0}-{1}'.format(x,y)
                #name = 'brc202d-{0}-{1}'.format(x,y)
                path = 'problems/original/{0}/Instances/{1}'.format(problem_folder, name)
                i+=1           

                if y != 5:
                    continue
                #print(name)
                '''
                if x < 38:
                    continue

                if x == 38 and (y <= 6 or y == 8):
                   continue 

                if x == 40 and (y == 0 or y == 2 or y == 3 or y == 4 or y == 8):
                    continue
                    '''

                problem = lp_generator.Problem(50)
                print('reading instance')
                problem.read_instance(path)
                print('generating solution')
                problem.gen_solution()


                path = 'problems/asp/{0}/{1}'.format(problem_folder,name)
                problem.write_to_lp(path)
                
                print('Solving with clingo...')
            

                start_time = time.time()
                num = problem.max_time
                ground_time = 0
                ground_time0 = 0
                runtime = 0
                runtime0 = 0

                print(num)
                first_solved = False
                solved = False


                solv0 = None
                solv = None

                curr = 300

                while True:


                    solv0 = asp_solver.IncrementalSolver('{0}.lp'.format(path), num, problem.num_agents, problem.min_sum, problem.total_cost, solver_type, only_first_sol)
                    clingo.clingo_main(solv0, ['{0}.lp'.format(path), '{0}.lp'.format(base_path) , '--outf=3', '--opt-strat=usc,disjoint', '--time-limit={0}'.format(curr), '-t', '4', '-c','bound={0}'.format(num)])
                    #print(solv0.ground_time)
                    ground_time += solv0.ground_time

                    elapsed = time.time() - start_time
                    curr = int(300 - elapsed)
                    print(curr)

                    if curr < 0:
                        break


                    if solv0.sol_cost > 0:
                        runtime0 = time.time() - start_time
                        ms = int(solv0.theoric_makespan)
                        first_solved = True
                        ground_time0 = ground_time


                        print(ms)
                        if ms == num:
                            solv = solv0
                            solved = True
                            runtime = runtime0
                            break

                        break


                        

                        solv = asp_solver.IncrementalSolver('{0}.lp'.format(path), ms, problem.num_agents, problem.min_sum, problem.total_cost, solver_type, only_first_sol)
                        clingo.clingo_main(solv, ['{0}.lp'.format(path), '{0}.lp'.format(base_path) ,  '--outf=3', '--opt-strat=usc,disjoint', '--time-limit={0}'.format(curr), '-t', '4', '-c','bound={0}'.format(ms)])

                        ground_time += solv.ground_time
                        if solv.stats is not None:
                            runtime = time.time() - start_time
                            summary = solv.stats['summary']
                            solved = True
                        break
                    num += 1
                    print(num)



                
                #sol = solv.resp
                row = [name]
                #print(solv.sol_cost)

                if first_solved:

                    #print(json.dumps(solv.stats, sort_keys=True, indent=4, separators=(',', ': ')))

                    row.append(1)
                    row.append(0)
                    row.append('\t')

                    row.append(format_float(solv0.stats['summary']['costs'][0]))
                    row.append(format_float(solv0.sol_cost))
                    row.append('-1')
                    row.append(int(solv0.theoric_makespan))
                    row.append(format_float(runtime0))
                    row.append(format_float(ground_time0))
                    row.append(format_float(ground_time0/runtime0*100))
                    row.append(format_float(solv0.stats['problem']['lp']['atoms']))
                    row.append(format_float(solv0.stats['problem']['lp']['bodies']))
                    row.append(format_float(solv0.stats['problem']['lp']['rules']))
                    row.append(format_float(solv0.stats['problem']['lp']['atoms'] + solv0.stats['problem']['lp']['bodies'] + solv0.stats['problem']['lp']['rules']))
                    row.append('\t')

                    if solved:
                        row[2] = 1
                        row.append(format_float(solv.stats['summary']['costs'][0]))
                        row.append(format_float(solv.sol_cost))
                        row.append('-1')
                        row.append(int(solv.theoric_makespan))
                        row.append(format_float(runtime))
                        row.append(format_float(ground_time))
                        row.append(format_float(ground_time/runtime*100))
                        row.append(format_float(solv.stats['problem']['lp']['atoms']))
                        row.append(format_float(solv.stats['problem']['lp']['bodies']))
                        row.append(format_float(solv.stats['problem']['lp']['rules']))
                        row.append(format_float(solv.stats['problem']['lp']['atoms'] + solv.stats['problem']['lp']['bodies'] + solv.stats['problem']['lp']['rules']))

                else:
                    row.append(0)
                    row.append(0)

                    
                #print(elapsed_time)
                #print(solv.resp)
                #print(check_makespan(solv.resp))
                
                results.write(';'.join(map(str, row)) + '\n')
                results.flush()
示例#18
0
                if sym.name == "on":
                    args = sym.arguments
                    robot = int(args[0].name[-1:]) - 1

                if sym.name == "exec":
                    args = sym.arguments
                    robot = int(args[0].name[-1:]) - 1
                    if robot == 2:
                        print(sym)

                if sym.name == "penalty":
                    args = sym.arguments
                    robot = int(args[0].name[-1:]) - 1
                    if robot == 2:
                        print(sym)

        print(m.optimality_proven, "????")


if __name__ == '__main__':
    min_bound = 10
    while True:
        app = Application(sys.argv[0], min_bound)
        args = sys.argv[1:]
        args.append("-c")
        args.append("bound={0}".format(min_bound))
        ret = clingo.clingo_main(app, args)
        if app.solved:
            break
        min_bound += 1
                    for model in handle:
                        a = self.__theory.assignment(model.thread_id)
                        total_facts, bound = self.get_total_facts(a)
                        break
                    else:
                        non_interrupted_calls += 1
                        # sys.stdout.write("Optimum Found\n")
                        break
                toc = time.time()
                time_used += (toc - tic)
                self.add_new_constraint(prg, bound)
            else:
                ret = prg.solve()
            if i != 0:
                makespan_time_window.append(last_bound)
            i = i + 1  # Go to the next Time Window
            #next_window_assignment = ''
            self.generating_next_time_window(
                total_facts, i
            )  # This call is to generate Time Window Assignment for the upcoming Window
        for x in range(NUM_OF_TIME_WINDOWS):
            print("Completion Time for Window {} : {} ".format(
                x + 1, makespan_time_window[x]))
        print("Number of interrupted calls : {} ".format(interrupted_calls))
        print("Number of non-interrupted calls : {} ".format(
            non_interrupted_calls - 1))
        #print(sys.argv[2])


sys.exit(int(clingo.clingo_main(Application("test"), sys.argv[1:])))
示例#20
0
def main():
    setup_logger()
    sys.exit(int(clingo.clingo_main(Application(), sys.argv[1:])))