Exemple #1
0
def schedule(args):
	"""
	Runs the Scheduler with the OrderList from orderListName on the Plant
	with plantName.
	"""
	plantName = args[0]
	orderListName = args[1]
	try:
		solverIndex = int(args[2])
	except:
		solverIndex = -1
	
	plant = Plant.fromXmlFile(plantFileExists(plantName))
	orderList = OrderList.fromXmlFile(orderListExists(orderListName))

	solver = None
	if solverIndex == 0:
		solver = BacktrackingSolver()
	else:
		if solverIndex == 1:
			solver = RecursiveBacktrackingSolver()
		else:
			solver = MinConflictsSolver()

	scheduler = Scheduler(plant, orderList, solver)
	scheduler.run()
Exemple #2
0
    def run(self, dag):
        """run the layout method"""
        qubits = dag.qubits
        cxs = set()

        from constraint import Problem, AllDifferentConstraint, RecursiveBacktrackingSolver
        from qiskit.transpiler.passes.layout._csp_custom_solver import CustomSolver

        for gate in dag.two_qubit_ops():
            cxs.add((qubits.index(gate.qargs[0]), qubits.index(gate.qargs[1])))
        edges = set(self.coupling_map.get_edges())

        if self.time_limit is None and self.call_limit is None:
            solver = RecursiveBacktrackingSolver()
        else:
            solver = CustomSolver(call_limit=self.call_limit,
                                  time_limit=self.time_limit)

        variables = list(range(len(qubits)))
        variable_domains = list(self.coupling_map.physical_qubits)
        random.Random(self.seed).shuffle(variable_domains)

        problem = Problem(solver)
        problem.addVariables(variables, variable_domains)
        problem.addConstraint(
            AllDifferentConstraint())  # each wire is map to a single qubit

        if self.strict_direction:

            def constraint(control, target):
                return (control, target) in edges

        else:

            def constraint(control, target):
                return (control, target) in edges or (target, control) in edges

        for pair in cxs:
            problem.addConstraint(constraint, [pair[0], pair[1]])

        solution = problem.getSolution()

        if solution is None:
            stop_reason = "nonexistent solution"
            if isinstance(solver, CustomSolver):
                if solver.time_current is not None and solver.time_current >= self.time_limit:
                    stop_reason = "time limit reached"
                elif solver.call_current is not None and solver.call_current >= self.call_limit:
                    stop_reason = "call limit reached"
        else:
            stop_reason = "solution found"
            self.property_set["layout"] = Layout(
                {v: qubits[k]
                 for k, v in solution.items()})
            for reg in dag.qregs.values():
                self.property_set["layout"].add_register(reg)

        self.property_set["CSPLayout_stop_reason"] = stop_reason
Exemple #3
0
def _performance():
    backtracking_solver = _delta_time(
        lambda: list(solution(dimension=6, solver=BacktrackingSolver())))
    print(f"dimension=6, BacktrackingSolver: {backtracking_solver}")
    recursive_backtracking_solver = _delta_time(
        lambda: solution(dimension=6, solver=RecursiveBacktrackingSolver()))
    print(
        f"dimension=6, RecursiveBacktrackingSolver: {recursive_backtracking_solver}"
    )
Exemple #4
0
    def run(self, dag):
        qubits = dag.qubits
        cxs = set()

        for gate in dag.two_qubit_ops():
            cxs.add((qubits.index(gate.qargs[0]), qubits.index(gate.qargs[1])))
        edges = set(self.coupling_map.get_edges())

        if self.time_limit is None and self.call_limit is None:
            solver = RecursiveBacktrackingSolver()
        else:
            solver = CustomSolver(call_limit=self.call_limit,
                                  time_limit=self.time_limit)

        problem = Problem(solver)
        problem.addVariables(list(range(len(qubits))),
                             self.coupling_map.physical_qubits)
        problem.addConstraint(
            AllDifferentConstraint())  # each wire is map to a single qubit

        if self.strict_direction:

            def constraint(control, target):
                return (control, target) in edges
        else:

            def constraint(control, target):
                return (control, target) in edges or (target, control) in edges

        for pair in cxs:
            problem.addConstraint(constraint, [pair[0], pair[1]])

        random.seed(self.seed)
        solution = problem.getSolution()

        if solution is None:
            stop_reason = 'nonexistent solution'
            if isinstance(solver, CustomSolver):
                if solver.time_current is not None and solver.time_current >= self.time_limit:
                    stop_reason = 'time limit reached'
                elif solver.call_current is not None and solver.call_current >= self.call_limit:
                    stop_reason = 'call limit reached'
        else:
            stop_reason = 'solution found'
            self.property_set['layout'] = Layout(
                {v: qubits[k]
                 for k, v in solution.items()})

        self.property_set['CSPLayout_stop_reason'] = stop_reason
Exemple #5
0
    def run(self, dag):
        try:
            from constraint import Problem, RecursiveBacktrackingSolver, AllDifferentConstraint
        except ImportError:
            raise TranspilerError('CSPLayout requires python-constraint to run. '
                                  'Run pip install python-constraint')
        qubits = dag.qubits()
        cxs = set()

        for gate in dag.twoQ_gates():
            cxs.add((qubits.index(gate.qargs[0]),
                     qubits.index(gate.qargs[1])))
        edges = self.coupling_map.get_edges()

        problem = Problem(RecursiveBacktrackingSolver())

        problem.addVariables(list(range(len(qubits))), self.coupling_map.physical_qubits)

        problem.addConstraint(AllDifferentConstraint())  # each wire is map to a single qbit

        if self.strict_direction:
            def constraint(control, target):
                return (control, target) in edges
        else:
            def constraint(control, target):
                return (control, target) in edges or (target, control) in edges

        for pair in cxs:
            problem.addConstraint(constraint, [pair[0], pair[1]])

        random.seed(self.seed)
        solution = problem.getSolution()

        if solution is None:
            return

        self.property_set['layout'] = Layout({v: qubits[k] for k, v in solution.items()})
Exemple #6
0
    def run(self, dag):
        try:
            from constraint import Problem, RecursiveBacktrackingSolver, AllDifferentConstraint
        except ImportError:
            raise TranspilerError(
                'CSPLayout requires python-constraint to run. '
                'Run pip install python-constraint')
        qubits = dag.qubits()
        cxs = set()

        for gate in dag.twoQ_gates():
            cxs.add((qubits.index(gate.qargs[0]), qubits.index(gate.qargs[1])))
        edges = self.coupling_map.get_edges()

        class CustomSolver(RecursiveBacktrackingSolver):
            """A wrap to RecursiveBacktrackingSolver to support ``call_limit``"""
            def __init__(self, call_limit=None, time_limit=None):
                self.call_limit = call_limit
                self.time_limit = time_limit
                self.call_current = None
                self.time_start = None
                self.time_current = None
                super().__init__()

            def limit_reached(self):
                """Checks if a limit is reached."""
                if self.call_current is not None:
                    self.call_current += 1
                    if self.call_current > self.call_limit:
                        return True
                if self.time_start is not None:
                    self.time_current = time() - self.time_start
                    if self.time_current > self.time_limit:
                        return True
                return False

            def getSolution(
                    self,  # pylint: disable=invalid-name
                    domains,
                    constraints,
                    vconstraints):
                """Wrap RecursiveBacktrackingSolver.getSolution to add the limits."""
                if self.call_limit is not None:
                    self.call_current = 0
                if self.time_limit is not None:
                    self.time_start = time()
                return super().getSolution(domains, constraints, vconstraints)

            def recursiveBacktracking(
                    self,  # pylint: disable=invalid-name
                    solutions,
                    domains,
                    vconstraints,
                    assignments,
                    single):
                """Like ``constraint.RecursiveBacktrackingSolver.recursiveBacktracking`` but
                limited in the amount of calls by ``self.call_limit`` """
                if self.limit_reached():
                    return None
                return super().recursiveBacktracking(solutions, domains,
                                                     vconstraints, assignments,
                                                     single)

        if self.time_limit is None and self.call_limit is None:
            solver = RecursiveBacktrackingSolver()
        else:
            solver = CustomSolver(call_limit=self.call_limit,
                                  time_limit=self.time_limit)

        problem = Problem(solver)
        problem.addVariables(list(range(len(qubits))),
                             self.coupling_map.physical_qubits)
        problem.addConstraint(
            AllDifferentConstraint())  # each wire is map to a single qbit

        if self.strict_direction:

            def constraint(control, target):
                return (control, target) in edges
        else:

            def constraint(control, target):
                return (control, target) in edges or (target, control) in edges

        for pair in cxs:
            problem.addConstraint(constraint, [pair[0], pair[1]])

        random.seed(self.seed)
        solution = problem.getSolution()

        if solution is None:
            stop_reason = 'nonexistent solution'
            if isinstance(solver, CustomSolver):
                if solver.time_limit is not None and solver.time_current >= self.time_limit:
                    stop_reason = 'time limit reached'
                elif solver.call_limit is not None and solver.call_current >= self.call_limit:
                    stop_reason = 'call limit reached'
        else:
            stop_reason = 'solution found'
            self.property_set['layout'] = Layout(
                {v: qubits[k]
                 for k, v in solution.items()})

        self.property_set['CSPLayout_stop_reason'] = stop_reason
Exemple #7
0
def rank(tree):
    @extend(node.number)
    def _rank(self):
        problem.addVariable(id(self), [0])

    @extend(node.let)
    def _rank(self):
        if isinstance(self.ret, node.ident):
            # plain assignment -- not a field, lhs indexing
            vars = [id(self.ret), id(self.args)]
            try:
                problem.addVariables(vars, range(4))
                problem.addConstraint(operator.__eq__, vars)
            except ValueError:
                pass
        else:
            # lhs indexing or field
            pass

    @extend(node.for_stmt)
    def _rank(self):
        vars = [id(self.ident), id(self.expr)]
        problem.addVariables(vars, range(4))
        problem.addConstraint((lambda u, v: u + 1 == v), vars)

    @extend(node.if_stmt)
    def _rank(self):
        # could use operator.__not__ instead of lambda expression
        problem.addVariable(id(self.cond_expr), range(4))
        problem.addConstraint(lambda t: t == 0, [id(self.cond_expr)])

    @extend(node.ident)
    def _rank(self):
        try:
            x = id(self)
            problem.addVariable(x, range(4))
            for other in self.defs:
                y = id(other)
                try:
                    problem.addVariable(y, range(4))
                except ValueError:
                    pass
                problem.addConstraint(operator.__eq__, [x, y])
        except:
            print "Ignored ", self

    """

    @extend(funcall)
    def rank(self,problem):
        if not isinstance(self.func_expr,ident):
            # In MATLAB, chaining subscripts, such as size(a)(1)
            # is not allowed, so only fields and dot expressions
            # go here.  In Octave, chaining subscripts is allowed,
            # and such expressions go here.
            return
        try:
            if defs.degree(self.func_expr):
                # If a variable is defined, it is not a function,
                # except function handle usages, such as
                #    foo=@size; foo(17)
                # which is not handled properly yet.
                x = id(self.func_expr)
                n = len(self.args)
                problem.addVariable(x,range(4))
                problem.addConstraint((lambda u: u>=n),[x])
                return
        except TypeError: # func_expr is unhashable
            # For example [10 20 30](2)
            return
        except KeyError:
            # See tests/clear_margins.m
            return
        assert getattr(self.func_expr,"name",None)
        # So func_expr is an undefined variable, and we understand
        # it's a function call -- either builtin or user-defined.
        name = self.func_expr.name
#    if name not in builtins:
#        # User-defined function
#        return
#    builtins[name](self,problem)
#
#@extend(expr)
#def rank(self,problem):
#    try:
#        builtins[self.op](self,problem)
#    except:
#        pass
    """

    problem = Problem(RecursiveBacktrackingSolver())
    for v in node.postorder(tree):
        for u in v:
            try:
                u._rank()
            except AttributeError:
                pass
    s = problem.getSolution()
    if not s:
        print "No solutions"
    else:
        d = set()
        #for k in sorted(G.nodes(), key=lambda t: (t.name,t.lexpos)):
        for k in node.postorder(tree):
            if isinstance(k, node.ident):
                print k.name, k.lineno, s.get(id(k), -1)