Пример #1
0
def importPhases(file, names=[], loglevel=0):
    """Import multiple phases from one file. The phase names should be
    entered as a list of strings. See: importPhase """
    s = []
    for nm in names:
        s.append(solution.Solution(src=file, id=nm, loglevel=loglevel))
    return s
Пример #2
0
    def run_solve(self, z3_context, elements_json, prev_solutions_json,
                  results, i):
        """ Launch the solving process inside a thread to get a new design solution 

			Parameters: 
				z3_context: Z3 context objects
				elements_json: JSOn string of the elements tree 
				previous_solutions_json: JSON string of the previous soluitons to avoid producing again 
				results: Results collection to store the checked solution 
				i: index to store in the results collection 
		"""
        # Get the element shapes from the commmand line
        elements = json.loads(elements_json)
        prev_solutions = json.loads(prev_solutions_json)

        # Construct the solver instance
        solver = z3_solver.Solver(z3_context, elements, prev_solutions)

        # Solve for a design solution
        state = sln.Solution()
        time_start = time.time()
        solution = solver.branch_and_bound(state)

        time_end = time.time()
        logging.debug("Time in z3 " + str(i) + ": " + str(solver.time_z3))
        logging.debug("Time to generate a solution " + str(i) + ": " +
                      str(time_end - time_start))
        if solution is None:
            logging.debug("----No solution found---")
        results[i] = solution
Пример #3
0
def test_SingleNumber():
	c = solution.Solution()
	lstA = [2,2,2,3,3,3,4,4,5,5,6,6,1,1,1,4,5,7,6]
	eq_(c.SingleNumber(lstA),7)

	lstB = [1,2,3,1,2,3,1,2,4,5,6,4,5,6,4,5,6,3,3]
	eq_(c.SingleNumber(lstB),3)
 def canonical_solution(self, time_left):
     sol = solution.Solution(self.instance)
     t0 = time.clock()
     route = [0]
     q = 0
     for i in range(1, len(self.instance.nodes)):  # we bypass the depot 0
         if q + self.instance.nodes[i]["rq"] <= self.instance.capacity:
             q += self.instance.nodes[i]["rq"]
             # Calculate distance between previous and current node added to the route
             # > 0 is to ensure no IndexOutOfBounds Exception
             if len(route) > 0:
                 self.total_distance += round(
                     abs(self.instance.nodes[i - 1]["pt"] -
                         self.instance.nodes[i]["pt"]), 0)
             route += [i]
         else:
             self.total_distance += round(
                 abs(self.instance.nodes[i - 1]["pt"] -
                     self.instance.nodes[i]["pt"]), 0)
             sol.routes += [route + [0]]
             route = [0, i]
             q = self.instance.nodes[i]["rq"]
         if time.clock() - t0 > time_left:
             sys.stdout.write("Time expired")
             return sol
     sol.routes += [route + [0]]
     solution.routes = sol.routes
     return sol
Пример #5
0
 def canonical_solution(self):
     self.solution = solution.Solution(self.instance)
     self.solution = self.alg(self.instance,
                              self.solution,
                              seed=self.seed,
                              output_file=self.output_file)
     return self.solution
Пример #6
0
    def get_solution(self, source):
        if source['file'] not in self.all_solutions:
            s = solution.Solution(self, filename=source['file'])
            self.all_solutions[source['file']] = s
            self.drop_cache()

        return self.all_solutions[source['file']]
Пример #7
0
 def __init__(self, instance=None, algorithm=None, time_limit=60):
     assert instance is not None
     assert algorithm is not None
     self.instance = instance
     self.algorithm = algorithm
     self.time_limit = time_limit
     self.solution = solution.Solution(self.instance)
Пример #8
0
def Main(GeneticRules, extracting=0):
    print "main"
    start = timeit.default_timer()
    #GeneticRules=[]

    #flexible=[0.2,0.5,1]
    flexible = [0.2]
    dueDateParameter = [1.2, 1.5, 2, 0]
    #dueDateParameter=[1.2]
    jobAndMachine = [[10, 5], [20, 5], [50, 5], [20, 10], [50, 10], [100, 10],
                     [50, 15], [100, 15], [200, 15]]
    '''
    flexible=[0.5]
    dueDateParameter=[1.5]
    jobAndMachine=[[10,3]]
    '''
    data = [[0, 0, 0, 0] for i in xrange(len(GeneticRules))]

    repetition = 1
    for h in range(0, repetition):
        for i in flexible:
            for j in dueDateParameter:
                for index, k in enumerate(jobAndMachine):
                    pr1 = SP.FJSSP(k[1], k[0], j, i)  #generate problem
                    #pr1.printTable()#call print function from schedulingProblem file
                    s1 = SS.Solution(
                        pr1)  #call solution function from solution file
                    cs1 = CS.createSolution(pr1, s1, index, GeneticRules,
                                            extracting)
                    #s2 = cs1.randomSolution(s1)
                    #cs1.initialization()
                    Result = cs1.simulatedSolution()

                    for index, t in enumerate(data):
                        for l in range(0, 4):
                            if l == 0:
                                data[index][l] = Result[index][l]
                            else:
                                data[index][l] += Result[index][l]

                    #a=TS.tranformation(pr1,ab)#call transformation function from TranformPermutationToSolution file
                    #print s1.order, "\n"#print solution
                #print timeit.default_timer()-start

    for index, t in enumerate(
            data):  #it is used for calculate mean value of objectives
        for l in range(0, 4):
            if l == 0:
                data[index][l] = data[index][l]
            else:
                data[index][l] = data[index][l] / (
                    len(flexible) * len(dueDateParameter) *
                    len(jobAndMachine) * repetition)

    print data
    # print "oldu bu is"
    stop = timeit.default_timer()
    print stop - start
    return data
Пример #9
0
def main():
    cases = ["A man, a plan, a canal: Panama", "race a car"]

    op = solution.Solution().isPalindrome
    for _ in xrange(10000):
        for item in cases:
            #print op(item), "\t", item
            op(item)
Пример #10
0
 def __init__(self, path, alert_file):
     self.file_name = alert_file
     self.path = path
     self.observer = Observer()
     self.text_operations = text_operations.TextOperations(self.file_name)
     self.solution = solution.Solution()
     self.end_program = end_program.EndProgram()
     self.today_events = []
Пример #11
0
def test_singlenumber():
    lstA = [1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 1]  # output 7
    lstB = [23, 25, 27, 29, 31, 29, 27, 25, 23]  # output 31

    c = solution.Solution()

    eq_(c.SingleNumber(lstA), 7)
    eq_(c.SingleNumber(lstB), 31)
Пример #12
0
 def __init__(self, instance=None, alg=None, seed=4, output_file=None):
     assert instance is not None
     assert alg is not None
     self.instance = instance
     self.alg = alg
     self.solution = solution.Solution(self.instance)
     self.seed = seed
     self.output_file = output_file
Пример #13
0
 def __init__(self, file_name):
     self.solution = solution.Solution()
     self.file_name = file_name
     self.alert_file = open(self.file_name, 'r')
     self.alert_file.seek(0, 2)
     self.high_sid_alert_number = 100000
     self.alert_message = ''
     self.ips_report_name = 'IPS_report_' + date.today().strftime('%d_%m_%y') + '.txt'
Пример #14
0
def main():
    A = [
        [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
        [[2, 3]],
    ]
    op = solution.Solution().spiralOrder
    for item in A:
        print "-" * 20
        print item
        print op(item)
Пример #15
0
def main():
    op = solution.Solution().candy
    A = [1, 2, 3, 3, 4, 4, 3, 2, 1]
    print A
    for _ in xrange(10000):
        op(A)

    A = [4, 2, 3, 4, 1]
    print A
    for _ in xrange(10000):
        op(A)
Пример #16
0
def main():
    left = ListNode.build_num(99)
    right = ListNode.build_num(1)
    op = solution.Solution().addTwoNumbers
    sum = op(left, right)
    left.print_r()
    print ""
    right.print_r()
    print ""
    sum.print_r()
    print ""
Пример #17
0
 def __init__(self):
     super().__init__()
     # 记录所有模块
     self.labels = []
     self.order = [x for x in range(9)]
     self.group = QSequentialAnimationGroup()
     self.solutions = []
     self.positions = []
     # 求解器
     self.sol = solution.Solution()
     self.initUI()
    def execute(nx_graph: nx.Graph, parameters: SimulatedAnnealingParameters):

        observations = []

        start_time = time.time()

        # STEP 1
        t = parameters.T_max
        i_s2 = 0
        i_s3 = 0
        crnt_s = solution.Solution(nx_graph)
        crnt_est = crnt_s.get_estimate()

        while t > parameters.T_min:
            i_s3 += 1

            # STEP 2
            while True:
                i_s2 += 1

                next_s = crnt_s.get_neighbour()
                next_est = next_s.get_estimate()

                if next_est < crnt_est:
                    crnt_s = next_s
                    crnt_est = next_est
                elif random.random() > math.exp((next_est - crnt_est) / t):
                    crnt_s = next_s
                    crnt_est = next_est

                if parameters.i_s2_observation_interval is not None and i_s2 % parameters.i_s2_observation_interval == 0:
                    observations.append(
                        SimulatedAnnealingObservation('s2', crnt_est,
                                                      time.time() - start_time,
                                                      i_s2, i_s3))

                if i_s2 % parameters.k_t == 0:
                    break

            # STEP 3
            t = parameters.cooling_scheme.step(t, i_s3)

            if parameters.i_s3_observation_interval is not None and i_s3 % parameters.i_s3_observation_interval == 0:
                observations.append(
                    SimulatedAnnealingObservation('s3', crnt_est,
                                                  time.time() - start_time,
                                                  i_s2, i_s3))

        end_time = time.time()
        total_time = end_time - start_time

        return SimulatedAnnealingResult(crnt_s, total_time, observations)
Пример #19
0
 def create_feasible_solution(self):
     """Build a feasible, greedy solution for the problem."""
     self._solution = solution.Solution(self._abstract_g, self._cache)
     # While customers are not all served:
     while self._solution.missing_customers():
         self._customer = list(self._solution.missing_customers())
         self._temp_route = solution.Route(self._cache, greenest=True)
         self.create_feasible_route()
         self._solution.routes.append(self._temp_route)
     assert not self._solution.missing_customers(), 'self._customer is ' \
                                                    'empty even if sol.' \
                                                    'missing_customers(' \
                                                    ') is not'
     return self._solution
Пример #20
0
    def algorithm(self, start_time, k=3):
        sol = solution.Solution(self.instance)

        route = [0]  # Our route
        capacity = 0  # Our capacity for each vehicle
        unvisited_nodes = list(self.instance.nodes)
        current_node = self.instance.nodes[0]  # Starting a depot 0
        unvisited_nodes.remove(current_node)
        distances = {}

        # While there are still nodes to visit, continue
        while unvisited_nodes:
            # Loop through the unvisited nodes
            for index, p in enumerate(unvisited_nodes):
                dist = sol.instance.distance(current_node['pt'], p['pt'])
                distances.update({dist: p})

            distances = {
                k: v
                for k, v in sorted(distances.items(), key=lambda item: item[0])
            }
            shortest_distances = dict(itertools.islice(distances.items(), k))

            randomly_picked_node = random.choice(
                list(shortest_distances.keys()))
            node = distances.get(randomly_picked_node)
            current_node = node
            if capacity + node['rq'] <= self.instance.capacity:
                capacity += node['rq']
                route += [self.instance.nodes.index(node)]
                unvisited_nodes.remove(current_node)

            else:
                sol.routes += [route + [0]]
                route = [0, self.instance.nodes.index(node)]
                capacity = node['rq']
                unvisited_nodes.remove(node)

            t1 = time.time()  # End time
            if t1 - start_time > self.time_limit:
                sys.stdout.write("Time Expired\n")
                return sol

            distances = {}
            node = None
            randomly_picked_node = None

        sol.routes += [route + [0]]
        return sol
Пример #21
0
    def solve(self, prob=None):
        # Préparer l'exécution
        self._prepare()

        # Boucle d'exécution
        while (self._continue()):
            ampl_solver.FrpAmplMipSolver.solve()
#            pass (je crois que ca devrais plus être là)

# Finaliser l'exécution
        self._terminate()

        # Retourner une solution
        # TODO Le code ci-dessous est un code temporaire
        return solution.Solution()
Пример #22
0
 def canonical_solution(self, time_left):
     sol = solution.Solution(self.instance)
     t0 = time.clock()
     route = [0]
     q=0
     for i in range(1,len(self.instance.nodes)): # we bypass the depot 0
         if q+self.instance.nodes[i]["rq"] <= self.instance.capacity:
             q+=self.instance.nodes[i]["rq"]
             route += [i]
         else:
             sol.routes += [route+[0]]
             route = [0,i]
             q=self.instance.nodes[i]["rq"]
         if time.clock() - t0 > time_left:
             sys.stdout.write("Time expired")
             return sol
     sol.routes += [route+[0]]
     return sol
Пример #23
0
    def algorithm(self, start_time):
        sol = solution.Solution(self.instance)
        route = [0]  # Our route
        capacity = 0  # Our capacity for each vehicle
        unvisited_nodes = list(self.instance.nodes)
        current_node = self.instance.nodes[0]  # Starting a depot 0
        unvisited_nodes.remove(current_node)
        shortest_distance = 0
        closest_node = None

        # While there are still nodes to visit, continue
        while unvisited_nodes:
            # Loop through the unvisited nodes
            for index, p in enumerate(unvisited_nodes):

                dist = sol.instance.distance(current_node['pt'], p['pt'])
                if dist < shortest_distance or shortest_distance == 0:
                    shortest_distance = dist
                    closest_node = p

            current_node = closest_node
            if capacity + closest_node['rq'] <= self.instance.capacity:
                capacity += closest_node['rq']
                route += [self.instance.nodes.index(closest_node)]
                unvisited_nodes.remove(current_node)

            else:

                sol.routes += [route + [0]]
                route = [0, self.instance.nodes.index(closest_node)]
                capacity = closest_node['rq']
                unvisited_nodes.remove(closest_node)

            t1 = time.time()
            if t1 - start_time > self.time_limit:
                sys.stdout.write("Time Expired\n")
                return sol

            shortest_distance = 0
            closest_node = None

        sol.routes += [route + [0]]

        return sol
    def clusterAlgorithm(self, time_left):
        # To implement
        "This heuristic algorithm makes a several clusters of points, where each cluster is <= maxCapacity. When clusters"
        " have been found for all points, then we send a vehicle out to each cluster and find the routes."
        "1 ) Pick a (random) point"
        "2 ) Calculate the euclidean distance to all points to find a cluster, which does not exceed maximum capacity"
        "3 ) Send a vehicle to the cluster and find the shortest route in the cluster"
        "4 ) Repeat"
        "Hvordan håndterer vi kunder, som ikke er i clusters?"
        sol = solution.Solution(self.instance)
        t0 = time.clock()
        route = [0]
        q = 0
        visited = []
        clusters = []
        for i in range(len(self.instance.nodes) - 1):
            for j in range(1, len(self.instance.nodes)):
                temp = self.euclideanDistance(
                    self.instance.nodes[current]["pt"],
                    self.instance.nodes[j]["pt"])
                if j not in visited:
                    if temp <= shortestDistance:
                        shortestDistance = temp
                        current = j
                        visited += [j]
                        if q + self.instance.nodes[current][
                                "rq"] <= self.instance.capacity:
                            q += self.instance.nodes[current]["rq"]
                            if len(route) > 0:
                                self.total_distance += shortestDistance
                            route += [current]
                        else:
                            self.total_distance += shortestDistance
                            sol.routes += [route + [0]]
                            route = [0, current]
                            q = self.instance.nodes[current]["rq"]
            shortestDistance = 10000000
            if time.clock() - t0 > time_left:
                sys.stdout.write("Time expired")
                return sol

        sol.routes += [route + [0]]
        solution.routes = sol.routes
        return sol
Пример #25
0
def multiCrossOver(solutions, flag,number_of_guards, myMap):

    guard_and_solutions=[]

    for i in range(number_of_guards):

        temp=[]
        for s in solutions:
            temp.append(s.guardsPath[i])

        guard_and_solutions.append(temp)

    check = zip(*guard_and_solutions)
    res=[]
    for elem in check:
        newSol = solution.Solution(_map=myMap, _numberOfGuards=number_of_guards, _guardsPath=list(list(elem)))
        res.append(newSol)

    return res
Пример #26
0
    def z3_solve(self):
        # Solve for solutions only using Z3, rather than the branch and bound (experimental)
        solutions = []
        num_solutions = 1
        slns_found = 0
        while slns_found < num_solutions:
            self.solver.push()

            result = self.solver.check()
            if str(result) == 'sat':
                solution = sln.Solution()
                model = self.solver.model()
                json_sln = solution.convert_to_json(self.root, model)
                solutions.append(json_sln)

                self.encode_previous_solution_from_model(model, json_sln['id'])

            slns_found += 1
        return solutions
Пример #27
0
    def run_reflow(self, z3_context, elements, solution, changed_element_id,
                   changed_property, changed_value, keep_or_prevent, results,
                   i):
        """ Launch a reflow thread. 

			Parameters: 
				z3_context: A Z3 context object 
				elements: JSON string of the element tree 
				solution: The currrent solution tree from the previous soluiton with the values. 
				changed_element_id: ID of the changed element
				changed_property: Name of the variable that was changed 
				changed_value: The value that the variable was changed to 
				keep_or_prevent: Whether the update was to "keep" or "prevent" the value.
				results: collection for the results of reflow 
				i: Index to store in the results collection 
		"""
        elements = json.loads(elements)

        # Construct the solver instance
        solver = z3_solver.Solver(z3_context, elements, prune_domains=False)

        time_start = time.time()

        # Solver class repairs the soluiton
        repaired_solution = solver.repair_solution(solution,
                                                   changed_element_id,
                                                   changed_property,
                                                   changed_value,
                                                   keep_or_prevent)
        if repaired_solution is None:
            # This means the solution could not be repaired, so we request a new one to replace it.
            print("Getting brand new solution")
            solver = z3_solver.Solver(z3_context, elements)
            # Get a new soltuion to replace the invalid one
            state = sln.Solution()
            time_start = time.time()
            repaired_solution = solver.branch_and_bound(state)

        time_end = time.time()
        logging.debug("Time to check validity of solution " + str(i) + ": " +
                      str(time_end - time_start))

        results[i] = repaired_solution
Пример #28
0
    def __init__(self, **kwargs):
        self.tests = {}
        self.all_solutions = {}
        self.name = 'NO NAME'
        self.cached_solutions = None
        self.skip_count = 0
        self.clusters = {}
        self.cluster_size = 0
        self.dimentions = None
        self.output = None
        self.is_tl_hidden = True
        self.is_rt_hidden = True
        self.is_wa_hidden = True
        self.is_changed = False
        self.sources_path = ''
        self.tests_path = ''

        if 'file' in kwargs:
            data = json.load(kwargs['file'])
            self.clusters = dict(
                (key, [cluster.Cluster(obj=c) for c in data['clusters'][key]])
                for key in data['clusters'])
            self.all_solutions = dict(
                (e['name']['file'], solution.Solution(self, obj=e))
                for e in data['solutions'])
            self.tests = dict(
                (e['name'], testf.Test(obj=e)) for e in data['tests'])
            self.is_tl_hidden = data.get('is_tl_hidden', True)
            self.is_rt_hidden = data.get('is_rt_hidden', True)
            self.is_wa_hidden = data.get('is_wa_hidden', True)
            self.cluster_size = data.get('cluster_size', 0)
            self.name = data.get('name', 'NO NAME')
            self.sources_path = data.get(
                'sources_path',
                os.path.split(list(
                    self.all_solutions.values())[0].filepath)[0])
            self.tests_path = data.get(
                'tests_path',
                os.path.split(list(self.tests.values())[0].name)[0])

        if 'output' in kwargs:
            self.output = kwargs['output']
Пример #29
0
def test_evalRPN():
    lstA = [
        "10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"
    ]  # output 22
    lstB = [
        "-78", "-33", "196", "+", "-19", "-", "115", "+", "-", "-99", "/",
        "-18", "8", "*", "-86", "-", "-", "16", "/", "26", "-14", "-", "-",
        "47", "-", "101", "-", "163", "*", "143", "-", "0", "-", "171", "+",
        "120", "*", "-60", "+", "156", "/", "173", "/", "-24", "11", "+", "21",
        "/", "*", "44", "*", "180", "70", "-40", "-", "*", "86", "132", "-84",
        "+", "*", "-", "38", "/", "/", "21", "28", "/", "+", "83", "/", "-31",
        "156", "-", "+", "28", "/", "95", "-", "120", "+", "8", "*", "90", "-",
        "-94", "*", "-73", "/", "-62", "/", "93", "*", "196", "-", "-59", "+",
        "187", "-", "143", "/", "-79", "-89", "+", "-"
    ]  # output 165

    c = solution.Solution()

    eq_(c.evalRPN(lstA), 22)
    eq_(c.evalRPN(lstB), 165)
Пример #30
0
def test_maxDepth():

    root = leetcode.TreeNode(1)
    leaf_1 = leetcode.TreeNode(2)
    leaf_2 = leetcode.TreeNode(3)
    leaf_3 = leetcode.TreeNode(4)
    leaf_4 = leetcode.TreeNode(5)
    leaf_5 = leetcode.TreeNode(6)

    root.left = leaf_1
    root.right = leaf_2

    leaf_1.left = leaf_3
    leaf_2.right = leaf_4

    leaf_3.right = leaf_5

    c = solution.Solution()

    eq_(c.maxDepth(root), 4)
    eq_(c.maxDepth(leaf_3), 2)