Exemplo n.º 1
0
def run(provided):

    alg_base = algorithm.Algorithm(clients_number=100,
                                   restaurants_number=50,
                                   mutation_probability=0.66,
                                   isDataProvided=provided)
    for i in range(5):
        alg1 = algorithm.Algorithm(clients_number=100,
                                   restaurants_number=50,
                                   mutation_probability=0.12)
        alg1.generate_workers(96)
        alg1.genetic_alg(50)
        mtop1.append(alg1.best[-1])
        alg2 = algorithm.Algorithm(clients_number=100,
                                   restaurants_number=50,
                                   mutation_probability=0.3)
        alg2.generate_workers(96)
        alg2.genetic_alg(50)
        mtop2.append(alg2.best[-1])
        alg3 = algorithm.Algorithm(clients_number=100,
                                   restaurants_number=50,
                                   mutation_probability=0.66)
        alg3.generate_workers(96)
        alg3.genetic_alg(50)
        mtop3.append(alg3.best[-1])
        alg4 = algorithm.Algorithm(clients_number=100,
                                   restaurants_number=50,
                                   mutation_probability=0.9)
        alg4.generate_workers(96)
        alg4.genetic_alg(50)
        mtop4.append(alg4.best[-1])

    plt.title("Prawdopodobieństwo mutacji = 0,66")
    plt.ylabel("koszty")
    plt.xlabel("losowe dane")
    plt.scatter(range(1, 6), mtop3)
    plt.show()
    plt.xticks(range(1, 6))

    mmeans.append(numpy.mean(mtop1))
    mmeans.append(numpy.mean(mtop2))
    mmeans.append(numpy.mean(mtop3))
    mmeans.append(numpy.mean(mtop4))

    plt.title("Średnia dla rosnącego prawdopodobieństwa mutacji")
    plt.ylabel("koszty")
    plt.xlabel("prawdopodobieństwo mutacji")
    plt.scatter(mutation_count, mmeans)
    plt.xticks(mutation_count)
    plt.show()
Exemplo n.º 2
0
    def __init__(self, parent):
        Gtk.Box.__init__(self, False, 0)
        self.parent = parent

        try:
            current_locale, encoding = locale.getdefaultlocale()
            locale_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'locale')
            translate = gettext.translation (cn.App.application_shortname, locale_path, [current_locale] )
            _ = translate.gettext
        except FileNotFoundError:
            _ = str

        chart = ch.Chart()
        self.function = fn.Function()
        algo = al.Algorithm()
        self.algo_parameters = apm.AlgorithmParameters(self.function, algo, chart)
        self.func_parameters = fpm.FunctionParameters(self.function, algo, chart)
        self.result = rsl.Result(self.function, algo)
        hpaned = Gtk.Paned()
        hpaned.set_position(800)
        hpaned.add1(chart.sw)

        vbox = Gtk.VBox()
        vbox.add(self.algo_parameters.frame)
        vbox.add(self.func_parameters.frame)
        vbox.add(self.result.frame)



        hpaned.add2(vbox)

        self.pack_start(hpaned, True, True, 0)
    def __init__(self, geneticGrid=None, chromosome=None):

        self.simulationRunning = True
        self.showStatistics = True
        self.currentLoop = 0
        self.size = self.weight, self.height = config.screenWidth, config.screenHeight
        self.animationSpeed = config.animationStartSpeed
        self.pathNetwork = network.PathNetwork(config.drawGraph)
        if chromosome:
            self.chromosome = chromosome
            self.podFleet = podhandler.PodFleet(self.pathNetwork,
                                                self.chromosome)
        else:
            self.podFleet = podhandler.PodFleet(self.pathNetwork)

        if (geneticGrid):
            self.grid = geneticGrid

        else:
            self.grid = None

        self.algorithm = algorithm.Algorithm(self.podFleet)
        self.statistics = systemstatistics.SystemStatistics(self.podFleet)
        self.simulationTimeStep = config.simulationTimeStep

        self.FPS = None
Exemplo n.º 4
0
    def create_sub_frame(self):
        self.sub_frame1 = tk.Frame(self.master,
                                   width=1000,
                                   height=550,
                                   borderwidth=5,
                                   relief="groove")
        self.sub_frame3 = tk.Frame(self.master,
                                   width=1000,
                                   height=550,
                                   borderwidth=5,
                                   relief="groove")
        self.sub_frame4 = tk.Frame(self.master,
                                   width=1000,
                                   height=550,
                                   borderwidth=5,
                                   relief="groove")
        self.sub_frame2 = tk.Frame(self.master,
                                   width=1000,
                                   height=550,
                                   borderwidth=5,
                                   relief="groove")

        self.simulation_module = SimulationModule(self.sub_frame1)
        self.sub_frame1.pack(fill="both", expand=True)
        self.current_frame = self.sub_frame1
        # self.turtle_screen = self.simulation_module.turtle_screen
        # self.setup_env = SetupENV(self.sub_frame3)
        self.setup_agent = SetupAgent(self.sub_frame4)
        self.setup_algorithm = al.Algorithm(self.sub_frame2, self.setup_agent)
        # self.setup_association = SetupAssociation(self.sub_frame3, self.setup_agent)
        self.control = Controlmodule(self.simulation_module, self.setup_agent,
                                     self.setup_algorithm)
Exemplo n.º 5
0
def subProcess():
    '''
    get the image and send to algorithm to get result, then publish by mqtt publisher
    '''
    global flg_start
    global frame
    global MQTT_TopicName

    cur_th = threading.currentThread()
    while getattr(cur_th, "do_algorithm", True):
        if (flg_start):
            start = time.time()
            flg_start = False

            ins_algorithm = algorithm.Algorithm(frame)
            result = int(ins_algorithm.run())  # get result from algorithm

            # publish
            client.publish(MQTT_TopicName, result)

            # fps
            end = time.time()
            t = end - start
            fps = 1 / t
            print("{} image process done, result: {:4}, procTime: {:4.2} ms".
                  format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                         result, (t * 1000)))
Exemplo n.º 6
0
def mapping():
	global scan, scan_recieved, robot_ready
	nr = 4
	pub = rospy.Publisher('map', matrix, queue_size=1)
	rospy.Subscriber("/PIONIER" + nr + "/RosAria/pose", Odometry, callback_pose, queue_size=1)
	rospy.Subscriber("/PIONIER"+nr+"/scan", LaserScan, callback_scan,queue_size=1)
	rospy.Subscriber("ready", Bool, callback_ready, queue_size=1)
	grid_map = Map()
	data = Parser(scan, POSE).global_coordinates
	x, y = list(map(list, zip(*data['coordinates'])))
	robot_position = (data['pose'][0], data['pose'][1])
	a = algorithm.Algorithm(grid_map, (x, y), robot_position,WORLDWIDTH,CELLSIZE)        
	while True:
		rospy.sleep(0.001)
		if scan_received && robot_ready:
			rospy.loginfo("Scan handling!")
			## extract ranges from message
			data = Parser(scan, WORLDWIDTH/2,WORLDWIDTH/2,0).global_coordinates
			x, y = list(map(list, zip(*data['coordinates'])))
			robot_position = (data['pose'][0], data['pose'][1])
			a.robot_position = (data['pose'][0],data['pose'][1])
			a.hits = list(map(list, zip(*data['coordinates'])))
			a.run()
			a.grid_map.update()
			pub.publish(a.grid_map.return_map())
			scan_received = False
			robot_ready = False
Exemplo n.º 7
0
def evaluate_KT(data, model_dir, metric, stride=5):
    """ function to evaluate framewise matches """

    # get training algorithm
    algo = algorithm.Algorithm()
    # restore the latest checkpoint of the trained model
    _, optimizer, _ = get_lr_opt_global_step()
    ckpt_manager, status, chekpoint = restore_ckpt(logdir=model_dir,
                                                   optimizer=optimizer,
                                                   **algo.model)
    if status.assert_existing_objects_matched():
        print(ckpt_manager.latest_checkpoint)
        #input('CHEKPOINT RESTORED')
    # get model
    model = algo.model

    # initialize
    taus_all = np.zeros((len(CONFIG.DATASETS), ), dtype=np.float32)
    count = 0
    for dataset_name in CONFIG.DATASETS:
        # extract emneddings
        embs_list, _, _, _, _ = extract_embeddings(data, dataset_name, model)
        num_seqs = len(embs_list)
        # get kendall's tau for dataset_name
        print(num_seqs)
        taus = np.zeros((num_seqs * (num_seqs - 1)))
        taus_cosine = np.zeros((num_seqs * (num_seqs - 1)))
        idx = 0
        for i in range(num_seqs):
            query_feats = embs_list[i][::stride]
            print(query_feats.shape)
            for j in range(num_seqs):
                if i == j:
                    continue
                candidate_feats = embs_list[j][::stride]
                dists = cdist(query_feats, candidate_feats,
                              metric)  #CONFIG.EVAL.KENDALLS_TAU_DISTANCE)
                dists_cosine = cdist(
                    query_feats, candidate_feats,
                    'cosine')  #CONFIG.EVAL.KENDALLS_TAU_DISTANCE)
                nns = np.argmin(dists, axis=1)
                nns_cosine = np.argmin(dists_cosine, axis=1)
                taus[idx] = kendalltau(np.arange(len(nns)), nns).correlation
                taus_cosine[idx] = kendalltau(np.arange(len(nns)),
                                              nns_cosine).correlation
                print('tau=%0.5f/ %0.5f' % (taus[idx], taus_cosine[idx]))

                idx += 1
        taus = taus[~np.isnan(taus)]
        taus_cosine = taus_cosine[~np.isnan(taus_cosine)]
        print(dataset_name, taus.mean(), taus_cosine.mean())
        del embs_list
        taus_all[count] = taus.mean()
        count += 1
    # get kendall's tau for all visited classes
    tau = taus_all.mean()
    print(taus_all)
    print('datatset-wise tau=%0.5f' % tau)
Exemplo n.º 8
0
    def create_vis_labels(self, graph_number):
        """
        Creates vis/neigh/unvis labels for graph.
        :return: The created labels.
        """
        if graph_number == 1:
            nx_graph = self.nx_graph_1
            backend_graph = self.backend_graph_1
        elif graph_number == 2:
            nx_graph = self.nx_graph_2
            backend_graph = self.backend_graph_2
        else:
            return None

        algorithm = alg.Algorithm()
        node_ranking = algorithm.greatest_constraints_first(backend_graph.edge_count_list)

        # Set graph labels based off of associated ranking type.
        # Label all vis.
        if isinstance(node_ranking[0], graph.Node):
            nx_graph.nodes[node_ranking[0].identifier]['attr_dict']['node'].graph_label = 'vis'
        else:
            for visitor in node_ranking[0]:
                nx_graph.nodes[visitor.identifier]['attr_dict']['node'].graph_label = 'vis'

        # Label all neigh.
        try:
            if isinstance(node_ranking[1], graph.Node):
                nx_graph.nodes[node_ranking[1].identifier]['attr_dict']['node'].graph_label = 'neigh'
            else:
                for neighbor in node_ranking[1]:
                    nx_graph.nodes[neighbor.identifier]['attr_dict']['node'].graph_label = 'neigh'
        except IndexError:
            pass

        # Label all unvis.
        try:
            if isinstance(node_ranking[2], graph.Node):
                nx_graph.nodes[node_ranking[2].identifier]['attr_dict']['node'].graph_label = 'unvis'
            else:
                for unvisited in node_ranking[2]:
                    nx_graph.nodes[unvisited.identifier]['attr_dict']['node'].graph_label = 'unvis'
        except IndexError:
            pass

        # Actually set label dict based on data value.
        label_dict = {}
        backend_graph.edge_count_list[0].graph_label = 'root'
        for node in nx_graph.nodes().values():
            # logger.info('Node Value: {0}'.format(node))
            if node is not {}:
                label_dict[node['attr_dict']['node'].identifier] = node['attr_dict']['node'].graph_label

        return label_dict
Exemplo n.º 9
0
    def transcript_preprocess(
            self, transcript
    ):  #pre-process the transcript files to extract the words
        self.stop_word_t = algorithm.Algorithm("SmartStoplist.txt", 4, 1, 3)
        self.transcript = open(transcript, 'r')
        self.t_text = self.transcript.read()

        self.t_keywords = self.stop_word_t.run(
            self.t_text)  #first find the keywords
        self.t_keywords = sorted(self.t_keywords,
                                 key=lambda l: l[1],
                                 reverse=True)
        return self.t_keywords
Exemplo n.º 10
0
def mapping():
	global scan, scan_received, robot_ready
	nr = 4
        rospy.init_node("mapping",anonymous = True)
        pub = rospy.Publisher('map', matrix, queue_size=1)
        pub_pose = rospy.Publisher('planning_time',cell,queue_size=1)
	rospy.Subscriber("/PIONIER4/RosAria/pose", Odometry, callback_pose, queue_size=1)
	rospy.Subscriber("/PIONIER4/scan", LaserScan, callback_scan,queue_size=1)
	rospy.Subscriber("ready", Bool, callback_ready, queue_size=1)
	grid_map = Map()
        while len(scan) == 0:
                print("I'm waiting")
        data = Parser(scan, WORLDWIDTH/2,WORLDWIDTH/2,0).global_coordinates
        print(data)
	x, y = list(map(list, zip(*data[0]['coordinates'])))
	robot_position = (data[0]['pose'][0], data[0]['pose'][1])
	a = algorithm.Algorithm(grid_map, (x, y), robot_position,WORLDWIDTH,CELLSIZE)
        vec = []
        mat = []
	while True:
		rospy.sleep(0.001)
		if scan_received and robot_ready:
			rospy.loginfo("Scan handling!")
			## extract ranges from message
                        data = Parser(scan, POSE[0], POSE[1], POSE[2]).global_coordinates
			x, y = list(map(list, zip(*data[0]['coordinates'])))
			robot_position = (data[0]['pose'][0], data[0]['pose'][1])
			a.robot_position = (data[0]['pose'][0],data[0]['pose'][1])
			a.hits = list(map(list, zip(*data[0]['coordinates'])))
			a.run()
			a.grid_map.update()
                        print(a.grid_map.return_map())
                        size_x = len(a.grid_map.return_map())
                        size_y = len(a.grid_map.return_map()[0])
                        for i in range(size_x):
                                for j in range(size_y):
                                        vec.append(a.grid_map.return_map()[i][j])
                                vec1 = vector()
                                vec1 = vec
                                mat.append(vec1)
                                vec = []
			pub.publish(mat)
                        pub_pose.publish(a.robot_positon)
			scan_received = False
			robot_ready = False
Exemplo n.º 11
0
    def main(self, *args, **kwargs):
        """
        This brings together the etsy data and chooses the format for the
        data.
        """
        help = kwargs.get("help_messages", True)
        etsyrequest = request.Requestor(self.api_key, help)
        for code in self.CODES:
            self.listings.extend(etsyrequest.get_listings(code))
            word_processor = algorithm.Algorithm(self.listings, code)
            important_word = word_processor.process_data()
            self.word_list.append(important_word)
        html_path = kwargs.get("html_file_path", None)
        if html_path:
            out = outputformatter.HTMLOutput(self.word_list, html_path)
            out.output_html()

        if kwargs.get("json", None):
            out = outputformatter.JSONOutput(self.word_list)
            out.output_json()
Exemplo n.º 12
0
 def main(self):
     """
     Call functions for selecting dataset and algorithm.
     :return:
 """
     cached_stamp = 0
     self.filename = 'watch/user_intention.json'
     stamp = os.stat(self.filename).st_mtime
     if stamp != cached_stamp:
         cached_stamp = stamp
         print("user intention file updated", file=sys.stderr)
         obj1 = attr.Attribute()
         self.learning_problem = obj1.determine_learning_problem()
         if self.learning_problem is 1:
             obj1.supervised_attribute_set()
         else:
             obj1.unsupervised_attribute_set()
         obj1.generate_attribute_set()
         obj2 = alg.Algorithm()
         obj2.generate_algorithm_info(output=self.learning_problem)
Exemplo n.º 13
0
def main():
    if len(sys.argv) < 2:
        print('Nie podano pliku')
        sys.exit(-1)
    data = Parser(sys.argv[1], WORLDWIDTH / 2, WORLDWIDTH / 2,
                  0).global_coordinates
    grid_map = Map(len_x=int(WORLDWIDTH / CELLSIZE),
                   len_y=int(WORLDWIDTH / CELLSIZE))
    #pdb.set_trace()
    print(data[0]['coordinates'])
    x, y = list(map(list, zip(*data[0]['coordinates'])))
    robot_position = (data[0]['pose'][0], data[0]['pose'][1])
    a = algorithm.Algorithm(grid_map, (x, y), robot_position, WORLDWIDTH,
                            CELLSIZE)
    for dat in data:
        a.robot_position = (dat['pose'][0], dat['pose'][1])
        a.hits = list(map(list, zip(*dat['coordinates'])))
        # pdb.set_trace()
        a.run()
    a.grid_map.map_plot()
    input()
Exemplo n.º 14
0
def experiment():
    expResult = []

    for i in range(40):
        print(i)
        rowResult = []
        map = Map.Map(100, 100)
        mapData = map.createMap()
        initialX, initialY = Action.createIntialPoints(map)
        pointX, pointY, sensorReading, alpha = Action.generateConsecutivePoints(
            initialX, initialY, map, steps=100)
        Action.saveTraj(initialX, initialY, pointX, pointY, sensorReading,
                        alpha)
        actions = [0 for i in range(100)]
        for i in range(len(alpha)):
            if alpha[i] == 'R':
                actions[i] = (0, 1)
            if alpha[i] == 'D':
                actions[i] = (1, 0)
            if alpha[i] == 'L':
                actions[i] = (0, -1)
            if alpha[i] == 'U':
                actions[i] = (-1, 0)
        observation = sensorReading
        al = algorithm.Algorithm(mapData, actions, observation)
        proMap, maxResult = al.start(True)
        for i in range(5, len(maxResult)):
            diff = abs(maxResult[i]["location"][0] -
                       pointY[i]) + abs(maxResult[i]["location"][1] -
                                        pointX[i])
            rowResult.append(diff)
        expResult.append(rowResult)

    avarage_result = []
    for i in range(0, len(expResult[0])):
        total = 0.0
        for row in expResult:
            total += row[i]
        avarage_result.append(total / len(expResult))
    print(avarage_result)
Exemplo n.º 15
0
    def run(self):
        game = Game.TicTacToe()
        alg = Algorithm.Algorithm()

        print('Welcome to TicTacToe')
        while True:
            game.printGame()

            breaker = False
            while not breaker:
                moveStr = input(
                    '\nMake your move! ex) "1 3" where 1 is row and 3 is column.\n'
                )
                move = (int(moveStr[0]), int(moveStr[2]))
                print('You chose ({0}, {1})!'.format(move[0], move[1]))
                if game.makeMove(move):
                    breaker = True
                else:
                    print('Invalid move!')
                game.printGame()

            if game.gameOver():
                break

            print('\nAI is thinking...')
            bestMove = alg.findBestMove(game.getGameState(), game.getIndex(),
                                        -1)
            print('AI chose ({0}, {1})!'.format(bestMove[0], bestMove[1]))
            game.makeMove(bestMove)

            if game.gameOver():
                break

        if game.getWinner() == 1:
            print("You've won!")
        elif game.getWinner() == -1:
            print("You've lost!")
        else:
            print('Game tied!')
Exemplo n.º 16
0
def draw_full_algorithm():
    """
    Full algorithm and comparison drawing test.
    """
    random_grapher = randomized_grapher.RandomizedGrapher()
    algorithm = alg.Algorithm()

    # Create graph 1.
    graph_orig = random_grapher.create_graph(min_nodes=2,
                                             max_nodes=10,
                                             min_edges=1,
                                             max_edges=5)

    # Create graph 2. Done via copying graph one, with random nodes removed.
    graph_copy = random_grapher.copy_graph(graph_orig, remove_nodes=True)

    # # Extra values for graph 2.
    # a_node = graph_copy.get_node(0)
    # graph_copy.add_node(edges_in=[a_node, ])
    # graph_copy.add_node()

    graph_orig.sort_node_edge_lists()
    graph_copy.sort_node_edge_lists()

    # Compute first half of algorithm.
    graph_orig_ranking = algorithm.greatest_constraints_first(
        graph_orig.edge_count_list)
    graph_copy_ranking = algorithm.greatest_constraints_first(
        graph_copy.edge_count_list)

    # Format list values.
    graph_orig_ranking = algorithm.condense_list(graph_orig_ranking)
    graph_copy_ranking = algorithm.condense_list(graph_copy_ranking)

    logger.info('Formatted Graph Orig Ranking: {0}'.format(graph_orig_ranking))
    logger.info('Formatted Graph Copy Ranking: {0}'.format(graph_copy_ranking))

    graph_1 = random_grapher.copy_graph(graph_orig)
    graph_2 = random_grapher.copy_graph(graph_copy)
    list_1 = list(graph_orig_ranking)
    list_2 = list(graph_copy_ranking)

    # Compute second half of algorithm with 'loose' edge matching.
    match_list = algorithm.matching(list_1, list_2, edge_strictness='loose')
    logger.info('Match List: {0}'.format(match_list))

    # Draw data.
    mapper_1 = data_mapping.DataMapping(graph_1, graph_2)
    mapper_1.draw_side_by_side_color_maps(vis_labels=True, key=True)
    mapper_1.draw_matching_comparison(match_list)

    # Try again with 'strict' edge matching.
    logger.info('Formatted Graph Orig Ranking: {0}'.format(graph_orig_ranking))
    logger.info('Formatted Graph Copy Ranking: {0}'.format(graph_copy_ranking))

    match_list = algorithm.matching(graph_orig_ranking,
                                    graph_copy_ranking,
                                    edge_strictness='strict')
    logger.info('Match List: {0}'.format(match_list))

    # Draw data again.
    mapper_2 = data_mapping.DataMapping(graph_orig, graph_copy)
    mapper_2.draw_side_by_side_color_maps(vis_labels=True, key=True)
    mapper_2.draw_matching_comparison(match_list)
Exemplo n.º 17
0
import algorithm as h
import output
from datetime import datetime
'''[Summary]
this is a question which is slove N-queen question by Hill-Climbing
'''

if __name__ == "__main__":

    num = input('pls in put queen number : ')
    print(str(datetime.now()))
    HC = h.Algorithm(int(num))
    times = HC.hillSearch()
    print('do ...', times, ' times')
    print(str(datetime.now()))
    output.oupput2Txt(HC.pieceNode)
    print('--------------Another-------------')
    #SA = h.Algorithm(10)
    #times = SA.simulatedAnnleaing()
    #print('do ...', times, ' times')
Exemplo n.º 18
0
def start():
    orderVal.set('None')
    formulaVal.set('None')
    distanceVal.set('None')

    errorKeys = ('seq', 'curr', 'prev', 'cylinder')
    errors = {}

    seq = None
    cylinder = None
    head = None
    prev = None

    resetErrors()

    # Field validations
    if seqVal.get() == '':
        errors['seq'] = 'Sequences field is required!'
    elif seqVal.get().find(',') == -1:
        errors[
            'seq'] = 'Sequence field requires integers separated with commas.'
    else:
        try:
            seq = [int(i) for i in seqVal.get().strip().split(',')]
        except:
            errors[
                'seq'] = 'Sequence field requires multiple integer separated with commas.'

    if currVal.get() == '':
        errors['curr'] = 'Current field is required!'
    else:
        try:
            head = int(currVal.get())
        except ValueError:
            errors['curr'] = 'Current field to be an integer.'

    if prevVal.get() == '':
        errors['prev'] = 'Previous field is required!'
    else:
        try:
            prev = int(prevVal.get())
        except ValueError:
            errors['prev'] = 'Previous field has to be an integer.'

    if cylinderVal.get() == '':
        errors['cylinder'] = 'Cylinder field is required!'
    else:
        try:
            cylinder = int(cylinderVal.get())
        except ValueError:
            errors['cylinder'] = 'Cylinder field has to be an integer.'

    # If any errors, display error message
    if any([x in errorKeys for x in errors]):
        if 'seq' in errors:
            seqErrorLbl.config(fg='red')
            seqError.set(errors['seq'])
        if 'curr' in errors:
            currError.set(errors['curr'])
        if 'prev' in errors:
            prevError.set(errors['prev'])
        if 'cylinder' in errors:
            cylinderError.set(errors['cylinder'])

        ax.clear()
        plot.title('Sequences')
        canvas.draw()
    else:  # else attempt to start selected algorithm
        resetErrors()

        alg = algorithm.Algorithm(seq, cylinder, head, prev)
        results = alg.start(algVal.get())

        if results:
            orderVal.set(', '.join(str(v) for v in results['sequence']))
            formulaVal.set(results['formula'])
            distanceVal.set(results['distance'])

            # Plot graph
            y = results['sequence']
            x = [i for i in range(len(results['sequence']))]

            ax.clear()
            plot.tight_layout()
            plot.title('Sequences')
            ax.plot(x,
                    y,
                    color='#78909C',
                    marker='o',
                    markerfacecolor='#00BCD4',
                    markersize=10)

            # Assign plot label
            for i in range(len(results['sequence'])):
                ax.text(x[i] + 0.1, y[i] - 0.15, str(y[i]))

            canvas.draw()
Exemplo n.º 19
0
def train():
    """Trains model."""

    # define path to log dir
    logdir = CONFIG.LOGDIR

    setup_train_dir(logdir)

    # Common code for multigpu and single gpu
    strategy = tf.distribute.MirroredStrategy()
    with strategy.scope():
        # get training algorithm
        algo = train_algo.Algorithm()

        # Setup summary writer.
        summary_writer = tf.summary.create_file_writer(os.path.join(
            logdir, 'train_logs'),
                                                       flush_millis=10000)

        # setup learning_rate schedule, optimizer ...
        learning_rate, optimizer, global_step = get_lr_opt_global_step()
        ckpt_manager, status, _ = restore_ckpt(logdir=logdir,
                                               optimizer=optimizer,
                                               **algo.model)

        global_step_value = global_step.numpy()

        lr_fn = get_lr_fn(CONFIG.OPTIMIZER)

        # Setup Dataset Iterators.
        batch_size_per_replica = CONFIG.TRAIN.BATCH_SIZE
        total_batch_size = batch_size_per_replica * strategy.num_replicas_in_sync
        # Setup train iterator
        train_ds = create_dataset(split='train',
                                  mode=CONFIG.MODE,
                                  batch_size=total_batch_size)
        train_iterator = strategy.make_dataset_iterator(train_ds)

        # define one training step
        def train_step(data):
            loss = algo.train_one_iter(data, global_step, optimizer)
            return loss

        # gathering loss across different GPUs
        def dist_train(it):
            total_loss = strategy.reduce(tf.distribute.ReduceOp.SUM,
                                         strategy.experimental_run(
                                             train_step, it),
                                         axis=None)
            return total_loss

        dist_train = tf.function(dist_train)

        stopwatch = Stopwatch()

        try:
            while global_step_value < CONFIG.TRAIN.MAX_ITERS:
                with summary_writer.as_default():
                    with tf.summary.record_if(
                            global_step_value %
                            CONFIG.LOGGING.REPORT_INTERVAL == 0):

                        # training loss
                        loss = dist_train(train_iterator)
                        # Update learning rate based in lr_fn.
                        learning_rate.assign(lr_fn(learning_rate, global_step))

                        tf.summary.scalar('loss', loss, step=global_step)
                        tf.summary.scalar('learning_rate',
                                          learning_rate,
                                          step=global_step)

                        # Save checkpoint.
                        if global_step_value % CONFIG.CHECKPOINT.SAVE_INTERVAL == 0:
                            ckpt_manager.save()
                            logging.info('Checkpoint saved at iter %d.',
                                         global_step_value)

                        # Update global step.
                        global_step_value = global_step.numpy()

                        time_per_iter = stopwatch.elapsed()

                        tf.summary.scalar('timing/time_per_iter',
                                          time_per_iter,
                                          step=global_step)

                        logging.info(
                            'Iter[{}/{}], {:.1f}s/iter, Loss: {:.3f}'.format(
                                global_step_value, CONFIG.TRAIN.MAX_ITERS,
                                time_per_iter, loss.numpy()))

                        # Reset stopwatch after iter is complete.
                        stopwatch.reset()

        except KeyboardInterrupt:
            logging.info(
                'Caught keyboard interrupt. Saving model before quitting.')

        finally:
            # Save the final checkpoint.
            ckpt_manager.save()
            logging.info('Checkpoint saved at iter %d', global_step_value)
Exemplo n.º 20
0
def MultifloorCheck(EndStartPositions, grid, startRoom, win, ROWS, width):
    """This file will handle multifloor requests

    Args:
        EndStartPositions (list): The positions of the start and end
        grid (list): The 2d list that stores all the spots in there row and column
        startRoom (int): The room number that the user is starting algorithm
        win (pygame surface): The surface to draw on the
        ROWS (int): The amount of rows in the grid that
        width (int): The width of each spot

    Returns:
        bool or list: False if not multifoor if multifloor returns the floor grid for the floor we move to next and the starting spot on that floor.
    """

    # This dict stores the closest stair to each room.
    ClosestStair = {
        "34": "1",
        "p1": "1",
        "33": "2",
        "35": "2",
        "p2": "1",
        "31": "1",
        "32": "1",
        "1": "1",
        "2a": "3",
        "2": "3",
        "3": "3",
        "4": "3",
        "5": "3",
        "6": "3",
        "7": "4",
        "8": "4",
        "9": "4",
        "18": "4",
        "19": "4",
        "20": "2",
        "27": "4",
        "26": "2",
        "21": "2",
        "24": "2",
        "25": "2",
        "22": "2",
        "23": "2",
        "37": "5",
        "38": "5",
        "p3": "6",
        "39": "6",
        "40": "6",
        "41": "6",
        "10": "7",
        "10a": "7",
        "11": "8",
        "12": "8",
        "13": "8",
        "14": "8",
        "15": "8",
        "16": "8",
        "16a": "8",
        "17": "7"
    }

    # This dict stores each stairs locations and the location it comes out.
    StairLocations = {
        "1": "21 38 18 41",
        "2": "53 39 49 40",
        "3": "34 93 32 95",
        "4": "45 73 32 95",
        "5": "18 41 21 38",
        "6": "49 40 53 39",
        "7": "37 75 34 93",
        "8": "32 95 45 73"
    }

    # If the floor value of the starting and ending positions are different
    if EndStartPositions[2] != EndStartPositions[3]:
        start = EndStartPositions[0]

        end = StairLocations[ClosestStair[startRoom]]  # Get the stair location
        end = end.split(" ")
        Endx = int(end[0])
        Endy = int(end[1])
        end = grid[Endx][Endy]
        end.make_end()

        for row in grid:
            for spot in row:
                # Update that spots neighbors
                spot.update_neighbors(grid)
        # Make the algorithm start
        algorithm.Algorithm(lambda: draw(win, grid, ROWS, width), grid, start,
                            end)
        ScreenShot()

        # This section works out where the stair it led you to comes out.
        ofloorEnd = ClosestStair[startRoom]
        ofloorEnd = StairLocations[ofloorEnd]
        ofloorEnd = ofloorEnd.split(" ")

        # Remake the grid for the other floor
        grid = make_grid(ROWS, width)
        grid = make_barrier(grid, ROWS, EndStartPositions[3])

        return [grid[int(ofloorEnd[2])][int(ofloorEnd[3])], grid]

    else:
        return False
Exemplo n.º 21
0
def main():
    if len(sys.argv) < 2:
        print('Nie podano pliku')
        sys.exit(-1)
    data = Parser(sys.argv[1], WORLDWIDTH / 2, WORLDWIDTH / 2,
                  0).global_coordinates
    grid_map = Map(len_x=int(WORLDWIDTH / CELLSIZE),
                   len_y=int(WORLDWIDTH / CELLSIZE))
    #pdb.set_trace()
    #print(data[0]['coordinates'])
    x, y = list(map(list, zip(*data[0]['coordinates'])))
    robot_position = (data[0]['pose'][0], data[0]['pose'][1])
    a = algorithm.Algorithm(grid_map, (x, y), robot_position, WORLDWIDTH,
                            CELLSIZE)
    for dat in data:
        a.robot_position = (dat['pose'][0], dat['pose'][1])
        a.hits = list(map(list, zip(*dat['coordinates'])))
        # pdb.set_trace()
        a.run()
    a.grid_map.map_plot()
    occup_map = a.grid_map.return_map()
    kernel = np.ones((KERNEL, KERNEL), np.uint8)
    dilation = cv2.dilate(occup_map, kernel, iterations=1)
    plt.figure(4)
    plt.imshow(dilation, interpolation="nearest", cmap='Blues', origin='upper')
    plt.show()

    #print(occup_map)

    arr = wavefront_map(dilation, GOAL, ROBOT, THRESHOLD)
    arr1 = wavefront_map(occup_map, GOAL, ROBOT, THRESHOLD)
    #print(arr)

    plt.figure(5)
    plt.imshow(arr, interpolation="nearest", cmap='Blues', origin='upper')
    plt.colorbar()
    plt.plot(ROBOT[0], ROBOT[1], 'ro')
    plt.plot(GOAL[0], GOAL[1], 'rx')
    plt.show()

    path, moves_list = path_planning(arr, ROBOT)
    plt.figure(2)
    plt.imshow(occup_map,
               interpolation="nearest",
               cmap='Blues',
               origin='upper')
    plt.plot([i[1] for i in path], [i[0] for i in path], 'ro')
    plt.plot(ROBOT[0], ROBOT[1], 'bo')
    plt.plot(GOAL[0], GOAL[1], 'bx')
    plt.title("Ścieżka wyznaczona z zastosowaniem dylatacji")
    path1, moves_list1 = path_planning(arr1, ROBOT)
    #    print(path)
    plt.figure(3)
    plt.imshow(occup_map,
               interpolation="nearest",
               cmap='Blues',
               origin='upper')
    plt.plot([i[1] for i in path1], [i[0] for i in path1], 'ro')
    plt.plot(ROBOT[0], ROBOT[1], 'bo')
    plt.plot(GOAL[0], GOAL[1], 'bx')
    plt.title("Ścieżka wyznaczona bez wykorzystania dylatacji")
    plt.show()
Exemplo n.º 22
0
def main(StartRoom, EndRoom, win=WIN, width=WIDTH):
    """This is the main function were everything will be managed by

    Args:
        StartRoom (int): The room number of the start room
        EndRoom (int): The room number of the end room
        win (pygame surface):, optional): The pygame surface to draw one. Defaults to WIN.
        width (int, optional): The width of each spot. Defaults to WIDTH.

    Returns:
        list: A list of paths to the screenshots so the main file can send them
    """
    ROWS = 100
    # Make the grid
    grid = make_grid(ROWS, width)
    # Start and end position
    start = None
    end = None
    done = False

    run = True

    global ScreenshotList
    ScreenshotList = []

    # The room coordinates the last didget is the floor number.
    RoomLocations = {
        "34": "32 35 0",
        "p1": "42 35 0",
        "33": "51 35 0",
        "35": "45 36 0",
        "p2": "37 36 0",
        "31": "25 48 0",
        "32": "25 55 0",
        "1": "25 67 0",
        "2a": "23 74 0",
        "2": "23 74 0",
        "3": "27 80 0",
        "4": "27 86 0",
        "5": "25 92 0",
        "6": "29 92 0",
        "7": "47 92 0",
        "8": "47 87 0",
        "9": "47 84 0",
        "18": "80 72 0",
        "19": "80 72 0",
        "20": "71 51 0",
        "27": "70 65 0",
        "26": "70 54 0",
        "21": "78 47 0",
        "24": "66 47 0",
        "25": "75 47 0",
        "22": "71 47 0",
        "23": "71 47 0",
        "37": "19 37 1",
        "38": "26 37 1",
        "p3": "33 37 1",
        "39": "42 37 1",
        "40": "44 38 1",
        "41": "36 38 1",
        "10": "26 82 1",
        "10a": "26 87 1",
        "11": "26 91 1",
        "12": "28 92 1",
        "13": "28 92 1",
        "14": "37 92 1",
        "15": "42 95 1",
        "16": "43 90 1",
        "16a": "43 86 1",
        "17": "43 81 1"
    }

    EndStartSpots = GetStartAndEndPosition(
        RoomLocations, StartRoom, EndRoom,
        grid)  # Get the start and end spots.

    if isinstance(
            EndStartSpots, str
    ):  # If file returned a string. In my case that means a exception happend.
        return EndStartSpots
    start = EndStartSpots[0]
    end = EndStartSpots[1]

    grid = make_barrier(grid, ROWS, EndStartSpots[2])

    NewFloorData = MultifloorCheck(EndStartSpots, grid, StartRoom, WIN, ROWS,
                                   width)
    if NewFloorData:
        start = NewFloorData[0]
        start.make_start()
        grid = NewFloorData[1]
        end = grid[end.get_pos()[0]][end.get_pos()[1]]
        end.make_end()

    # Infinate loop
    while run:
        draw(win, grid, ROWS, width)
        # Loop through all event that have happend in this frame
        for event in pygame.event.get():
            # If the event is a certain event
            if event.type == pygame.QUIT:  # If pressed X exit infinate loop
                run = False

            # If left mouse clicked
            if pygame.mouse.get_pressed()[0]:
                # Get x and y coordinate of mouse
                pos = pygame.mouse.get_pos()
                # Translate mouse pos into row and col
                row, col = get_clicked_pos(pos, ROWS, width)
                # Get the spot you clicked
                spot = grid[row][col]

    # Update all neighbors of all of the spots
    # Loop through the rows of the grid
        for row in grid:
            for spot in row:
                # Update that spots neighbors
                spot.update_neighbors(grid)
        # Make the algorithm start
        if not done:
            algorithm.Algorithm(lambda: draw(win, grid, ROWS, width), grid,
                                start, end)
            done = True
            ScreenShot()
            return ScreenshotList

    # When while loop breaks end game
    pygame.quit()
Exemplo n.º 23
0
def run(provided=False):

    alg_base = algorithm.Algorithm(clients_number=100,
                                   restaurants_number=50,
                                   mutation_probability=0.66,
                                   isDataProvided=provided)
    for i in range(5):
        alg1 = copy.deepcopy(alg_base)
        alg1.generate_workers(96)
        alg1.genetic_alg(50)
        ctop1.append(alg1.best[-1])
        alg2 = copy.deepcopy(alg_base)
        alg2.generate_workers(96)
        alg2.genetic_alg(100)
        ctop2.append(alg2.best[-1])
        alg3 = copy.deepcopy(alg_base)
        alg3.generate_workers(96)
        alg3.genetic_alg(150)
        ctop3.append(alg3.best[-1])
        alg4 = copy.deepcopy(alg_base)
        alg4.generate_workers(96)
        alg4.genetic_alg(200)
        ctop4.append(alg4.best[-1])
        alg5 = copy.deepcopy(alg_base)
        alg5.generate_workers(96)
        alg5.genetic_alg(250)
        ctop5.append(alg5.best[-1])
        alg6 = copy.deepcopy(alg_base)
        alg6.generate_workers(96)
        alg6.genetic_alg(300)
        ctop6.append(alg6.best[-1])
        alg7 = copy.deepcopy(alg_base)
        alg7.generate_workers(96)
        alg7.genetic_alg(350)
        ctop7.append(alg7.best[-1])
        alg8 = copy.deepcopy(alg_base)
        alg8.generate_workers(96)
        alg8.genetic_alg(400)
        ctop8.append(alg8.best[-1])
        alg9 = copy.deepcopy(alg_base)
        alg9.generate_workers(96)
        alg9.genetic_alg(450)
        ctop9.append(alg9.best[-1])
        alg10 = copy.deepcopy(alg_base)
        alg10.generate_workers(96)
        alg10.genetic_alg(500)
        ctop10.append(alg10.best[-1])

    plt.title("Liczba cykli = 50")
    plt.ylabel("koszty")
    plt.xlabel("losowe dane")
    plt.scatter(range(1, 6), ctop1)
    plt.show()
    plt.xticks(range(1, 6))

    cmeans.append(numpy.mean(ctop1))
    cmeans.append(numpy.mean(ctop2))
    cmeans.append(numpy.mean(ctop3))
    cmeans.append(numpy.mean(ctop4))
    cmeans.append(numpy.mean(ctop5))
    cmeans.append(numpy.mean(ctop6))
    cmeans.append(numpy.mean(ctop7))
    cmeans.append(numpy.mean(ctop8))
    cmeans.append(numpy.mean(ctop9))
    cmeans.append(numpy.mean(ctop10))

    plt.title("Średnia dla rosnącej liczby cykli")
    plt.ylabel("koszty")
    plt.xlabel("liczba cykli")
    plt.scatter(cycles_count, cmeans)
    plt.xticks(cycles_count)
    plt.show()
Exemplo n.º 24
0
def run(provided=False):

    alg_base = algorithm.Algorithm(clients_number=100,
                                   restaurants_number=50,
                                   mutation_probability=0.66,
                                   isDataProvided=provided)

    for i in range(5):
        alg1 = copy.deepcopy(alg_base)
        alg1.generate_workers(workers_count[0])
        alg1.genetic_alg(50)
        ptop1.append(alg1.best[-1])
        alg2 = copy.deepcopy(alg_base)
        alg2.generate_workers(workers_count[1])
        alg2.genetic_alg(50)
        ptop2.append(alg2.best[-1])
        alg3 = copy.deepcopy(alg_base)
        alg3.generate_workers(workers_count[2])
        alg3.genetic_alg(50)
        ptop3.append(alg3.best[-1])
        alg4 = copy.deepcopy(alg_base)
        alg4.generate_workers(workers_count[3])
        alg4.genetic_alg(50)
        ptop4.append(alg4.best[-1])
        alg5 = copy.deepcopy(alg_base)
        alg5.generate_workers(workers_count[4])
        alg5.genetic_alg(50)
        ptop5.append(alg5.best[-1])
        alg6 = copy.deepcopy(alg_base)
        alg6.generate_workers(workers_count[5])
        alg6.genetic_alg(50)
        ptop6.append(alg6.best[-1])
        alg7 = copy.deepcopy(alg_base)
        alg7.generate_workers(workers_count[6])
        alg7.genetic_alg(50)
        ptop7.append(alg7.best[-1])
        alg8 = copy.deepcopy(alg_base)
        alg8.generate_workers(workers_count[7])
        alg8.genetic_alg(50)
        ptop8.append(alg8.best[-1])
        alg9 = copy.deepcopy(alg_base)
        alg9.generate_workers(workers_count[8])
        alg9.genetic_alg(50)
        ptop9.append(alg9.best[-1])
        alg10 = copy.deepcopy(alg_base)
        alg10.generate_workers(workers_count[9])
        alg10.genetic_alg(50)
        ptop10.append(alg10.best[-1])

    pmeans.append(numpy.mean(ptop1))
    pmeans.append(numpy.mean(ptop2))
    pmeans.append(numpy.mean(ptop3))
    pmeans.append(numpy.mean(ptop4))
    pmeans.append(numpy.mean(ptop5))
    pmeans.append(numpy.mean(ptop6))
    pmeans.append(numpy.mean(ptop7))
    pmeans.append(numpy.mean(ptop8))
    pmeans.append(numpy.mean(ptop9))
    pmeans.append(numpy.mean(ptop10))

    print("done")

    plt.title("Populacja = 96")
    plt.ylabel("koszty")
    plt.xlabel("losowe dane")
    plt.scatter(range(1, 6), ptop3)
    plt.show()
    plt.xticks(range(1, 6))

    plt.title("Średnia dla rosnących populacji")
    plt.ylabel("koszty")
    plt.xlabel("zwiekszajaca sie populacja")
    plt.scatter(workers_count, pmeans)
    plt.xticks(workers_count)
    plt.show()
Exemplo n.º 25
0
])
df = pandas.DataFrame(index=range(N_experiments),
                      columns=pars.keys() + [
                          'mean_var_R',
                      ])

# get = scipy.load('q0.npz')
# N_skip = get['q0'].shape[0]/pars['N']
# assert N_skip*pars['N'] == get['q0'].shape[0]
# q0 = get['q0'][::N_skip]


algs = (algorithm.AlgorithmOUConstraintsHamiltonian(pot, pars), \
        algorithm.AlgorithmTaylor(pot, pars), \
        algorithm.AlgorithmTaylorBAOAB(pot, pars), \
        algorithm.Algorithm(pot, pars), \
        algorithm.AlgorithmPseudospectralSemiImplicit(pot, pars), \
        algorithm.AlgorithmOUConstraints(pot, pars), \
        algorithm.AlgorithmQuasiPseudospectralSemiImplicit(pot, pars), \
        algorithm.AlgorithmSemiImplicit(pot, pars),\
        algorithm.AlgorithmInversePseudospectralSemiImplicit(pot, pars))

fig, axs = plt.subplots(1, 2)

# for experiment in range(N_experiments):
experiment = 0
for alg_i in [
        0,
]:
    alg = algs[alg_i]
    print experiment
Exemplo n.º 26
0
 def stop_word_removal(self):
     self.stop_word = algorithm.Algorithm(
         "SmartStoplist.txt", 4, 3,
         3)  #stop word removal using the smart stopword list
Exemplo n.º 27
0
def run_algorithm_with_result_log(min_nodes=2,
                                  max_nodes=10,
                                  min_edges=1,
                                  max_edges=5,
                                  remove_nodes=False,
                                  min_percent_removal=10,
                                  max_percent_removal=90,
                                  edge_strictness='loose'):
    """
    Actually runs iterations of algorithm and logs results.
    """
    # Initialize necessary classes.
    random_grapher = randomized_grapher.RandomizedGrapher()
    algorithm = alg.Algorithm()

    # Do 100 iterations of current values.
    index = 0
    while index < 100:

        # Start Timer
        start_time = time.time()

        # Create graphs and sort edge lists.
        # First graph.
        graph_orig = random_grapher.create_graph(min_nodes=min_nodes,
                                                 max_nodes=max_nodes,
                                                 min_edges=min_edges,
                                                 max_edges=max_edges)
        first_graph_creation_time = time.time()
        node_count = len(graph_orig.nodes)

        # Second graph.
        graph_copy = random_grapher.copy_graph(
            graph_orig,
            remove_nodes=remove_nodes,
            min_percent_removal=min_percent_removal,
            max_percent_removal=max_percent_removal)
        second_graph_creation_time = time.time()

        # Sort graph edges for algorithm.
        graph_orig.sort_node_edge_lists()
        graph_copy.sort_node_edge_lists()
        graph_edge_sort_time = time.time()

        # Run first half of algorithm and format for second half.
        graph_orig_ranking = algorithm.greatest_constraints_first(
            graph_orig.edge_count_list)
        graph_copy_ranking = algorithm.greatest_constraints_first(
            graph_copy.edge_count_list)
        graph_orig_ranking = algorithm.condense_list(graph_orig_ranking)
        graph_copy_ranking = algorithm.condense_list(graph_copy_ranking)
        greatest_constraints_time = time.time()

        # Run second half of algorithm.
        match_list = algorithm.matching(graph_copy_ranking,
                                        graph_orig_ranking,
                                        edge_strictness=edge_strictness)
        matching_time = time.time()

        # Record info.
        # logger.info(match_list)
        algorithm_results = {
            'node_count': node_count,
            'start_time': start_time,
            'first_graph_creation_time': first_graph_creation_time,
            'second_graph_creation_time': second_graph_creation_time,
            'graph_edge_sort_time': graph_edge_sort_time,
            'greatest_constraints_time': greatest_constraints_time,
            'matching_time': matching_time,
            'number_of_matches': len(match_list),
        }
        logger.testresult(algorithm_results)
        index += 1
Exemplo n.º 28
0
def main():
    if os.path.exists("result"):
        os.remove("result")
    #clear and recreate the result file
    result_ = open("result", "w")
    args = parser.parse_args()
    alg = algorithm.Algorithm()

    if args.input_mode == "files_tsp225":
        #result_.write("Instance\tOPT\tFarthest\t3-opt\tCheapest\tchristofides\tNearest\tDT\n")
        data_path = "data/"
        TSP_START_LINE = 6
        TSP_END_LINE = -1
        TOUR_STAT_LINE = 5
        TOUR_END_LINE = -2
        node_list = []
        route = []
        name = "tsp225"
        tfile_name = data_path + name + ".tsp"
        sfile_name = data_path + name + ".opt.tour"
        tfile_ = open(tfile_name, "r")
        sfile_ = open(sfile_name, "r")
        tfile = tfile_.readlines()
        sfile = sfile_.readlines()
        result_dic = {}
        for j in tfile[TSP_START_LINE:TSP_END_LINE]:
            node_coord = j.lstrip().rstrip("\n").split(" ")
            node_list.append((float(node_coord[1]), float(node_coord[2])))
        for j in sfile[TOUR_STAT_LINE:TOUR_END_LINE]:
            node_coord = j.rstrip("\n")
            route.append(int(node_coord) - 1)
        g1 = graph.Graph("input_point", input_data=node_list)
        result_.write(name + "\t")
        g1.route = route
        result_dic["opt"] = g1.cal()
        alg.farthest(g1)
        result_dic["farthest"] = g1.cal()
        alg.k_opt(3, g1)
        result_dic["k_opt"] = g1.cal()
        alg.cheapest(g1)
        result_dic["cheapest"] = g1.cal()
        alg.christofides(g1)
        result_dic["christofides"] = g1.cal()
        alg.nearest(g1)
        result_dic["nearest"] = g1.cal()
        alg.double_tree(g1)
        result_dic["DT"] = g1.cal()
        for i in result_dic:
            result_.write(i + "\t" + str(result_dic[i]) + "\t" +
                          str(result_dic[i] / result_dic["opt"]) + "\n")
        tfile_.close()
        sfile_.close()
    elif args.input_mode == "input_weight":
        with open('2dmatrix.data') as f:
            array = [[float(x) for x in next(f).split()]]  # read first line
            for line in f:  # read rest of lines
                array.append([float(x) for x in line.split()])
        k = len(array[-1])
        nparray = np.zeros((k, k))
        for i in range(k):
            for j in range(i):
                nparray[i, j] = array[i][j]
        g1 = graph.Graph("input_weight", input_data=nparray)
        result_dic = {
            "double_tree": 0,
            "christofides": 0,
            "greed": 0,
            "cheapest": 0,
            "nearest": 0,
            "farthest": 0,
            "k_opt": 0
        }
        alg.double_tree(g1)
        result_dic["double_tree"] = g1.cal()
        alg.christofides(g1)
        result_dic["christofides"] = g1.cal()
        alg.greed(g1)
        result_dic["greed"] = g1.cal()
        alg.cheapest(g1)
        result_dic["cheapest"] = g1.cal()
        alg.nearest(g1)
        result_dic["nearest"] = g1.cal()
        alg.farthest(g1)
        result_dic["farthest"] = g1.cal()
        alg.k_opt(3, g1)
        result_dic["k_opt"] = g1.cal()
        for i in result_dic:
            result_.write(i + "\t" + str(result_dic[i]) + "\n")
        """
        sfile_name="data/pa561.opt.tour"
        sfile_ = open(sfile_name, "r")
        sfile=sfile_.readlines()
        route = []
        for j in sfile[5:-2]:
            node_coord=j.rstrip("\n")
            route.append(int(node_coord)-1)
        g1.route=route
        opt=g1.cal()
        for i in result_dic:
            result_.write(i+"\t"+str(result_dic[i])+"\t"+str(result_dic[i]/opt)+"\n")
        """
    elif args.input_mode == "input_point":
        with open('coordinates.data') as f:
            array = [[float(x) for x in next(f).split()]]  # read first line
            for line in f:  # read rest of lines
                array.append([float(x) for x in line.split()])
        g1 = graph.Graph("input_point", input_data=array)
        result_dic = {
            "double_tree": 0,
            "christofides": 0,
            "greed": 0,
            "cheapest": 0,
            "nearest": 0,
            "farthest": 0,
            "k_opt": 0
        }
        alg.double_tree(g1)
        result_dic["double_tree"] = g1.cal()
        alg.christofides(g1)
        result_dic["christofides"] = g1.cal()
        alg.greed(g1)
        result_dic["greed"] = g1.cal()
        alg.cheapest(g1)
        result_dic["cheapest"] = g1.cal()
        alg.nearest(g1)
        result_dic["nearest"] = g1.cal()
        alg.farthest(g1)
        result_dic["farthest"] = g1.cal()
        alg.k_opt(3, g1)
        result_dic["k_opt"] = g1.cal()
        for i in result_dic:
            result_.write(i + "\t" + str(result_dic[i]) + "\n")
    elif args.input_mode == "random":  #in random generating, there is only so-called approx ratio
        n_test = 40
        cum_result_dic = {
            "double_tree": 0,
            "christofides": 0,
            "greed": 0,
            "cheapest": 0,
            "nearest": 0,
            "farthest": 0,
            "k_opt": 0
        }
        for i in range(n_test):
            g1 = graph.Graph('random', args.node_min, args.node_max)
            alg.double_tree(g1)
            cum_result_dic["double_tree"] += g1.cal()
            alg.christofides(g1)
            cum_result_dic["christofides"] += g1.cal()
            alg.greed(g1)
            cum_result_dic["greed"] += g1.cal()
            alg.cheapest(g1)
            cum_result_dic["cheapest"] += g1.cal()
            alg.nearest(g1)
            cum_result_dic["nearest"] += g1.cal()
            alg.farthest(g1)
            cum_result_dic["farthest"] += g1.cal()
            alg.k_opt(3, g1)
            cum_result_dic["k_opt"] += g1.cal()
        for i in cum_result_dic:
            result_.write(i + "\t" + str(cum_result_dic[i] / n_test) + "\n")
    else:
        exit(0)

    result_.close()