当前位置: 首页>>代码示例>>Python>>正文


Python Scheduler.schedule_all方法代码示例

本文整理汇总了Python中Scheduler.Scheduler.schedule_all方法的典型用法代码示例。如果您正苦于以下问题:Python Scheduler.schedule_all方法的具体用法?Python Scheduler.schedule_all怎么用?Python Scheduler.schedule_all使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Scheduler.Scheduler的用法示例。


在下文中一共展示了Scheduler.schedule_all方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: n_map

# 需要导入模块: from Scheduler import Scheduler [as 别名]
# 或者: from Scheduler.Scheduler import schedule_all [as 别名]

#.........这里部分代码省略.........
        min_cost = float("inf")
        node_candidates = []
        for unallocated_node in unallocated_nodes:
            cost = 0
            reachable = True
            for mapped_task in mapped_tasks:
                com_weight = 0
                if (chosen_task, mapped_task) in tg.edges():
                    # print ("TASK CONNECTED TO MAPPED TASK:", mapped_task)
                    com_weight += tg.edge[chosen_task][mapped_task]["ComWeight"]
                    destination_node = tg.node[mapped_task]['task'].node
                    # here we check if this node is even reachable from the chosen node?
                    if Calculate_Reachability.is_destination_reachable_from_source(noc_rg, unallocated_node,
                                                                                   destination_node):
                        manhatan_distance = AG_Functions.manhattan_distance(unallocated_node, destination_node)
                        cost += manhatan_distance * com_weight
                    else:
                        reachable = False
                elif (mapped_task, chosen_task) in tg.edges():
                    # print ("TASK CONNECTED TO MAPPED TASK:", mapped_task)
                    com_weight += tg.edge[mapped_task][chosen_task]["ComWeight"]
                    destination_node = tg.node[mapped_task]['task'].node
                    # here we check if this node is even reachable from the chosen node?
                    if Calculate_Reachability.is_destination_reachable_from_source(noc_rg, destination_node,
                                                                                   unallocated_node):
                        manhatan_distance = AG_Functions.manhattan_distance(unallocated_node, destination_node)
                        cost += manhatan_distance * com_weight
                    else:
                        reachable = False
            if reachable:
                if cost < min_cost:
                    node_candidates = [unallocated_node]
                    min_cost = cost
                elif cost == min_cost:
                    node_candidates.append(unallocated_node)
            else:
                print ("\t \033[33m* NOTE::\033[0m NODE "+str(unallocated_node)+" CAN NOT REACH...")
                pass
        print ("\t CANDIDATE NODES: "+str(node_candidates)+" MIN COST: "+str(min_cost))

        if len(node_candidates) == 0:
            raise ValueError("COULD NOT FIND A REACHABLE CANDIDATE NODE...")
        elif len(node_candidates) > 1:
            chosen_node = random.choice(node_candidates)
        elif len(node_candidates) == 1:
            chosen_node = node_candidates[0]
        else:
            # this means that the chosen task is not connected to any other task... so its cost is infinity
            chosen_node = random.choice(unallocated_nodes)

        mapped_tasks.append(chosen_task)
        print ("\t ADDED TASK "+str(chosen_task)+" TO MAPPED TASKS LIST")
        unmapped_tasks.remove(chosen_task)
        print ("\t REMOVED TASK "+str(chosen_task)+" FROM UN-MAPPED TASKS LIST")

        allocated_nodes.append(chosen_node)
        print ("\t ADDED NODE "+str(chosen_node)+" TO ALLOCATED NODES LIST")
        unallocated_nodes.remove(chosen_node)
        print ("\t REMOVED NODE "+str(chosen_node)+" FROM UN-ALLOCATED NODES LIST")

        if Mapping_Functions.map_task_to_node(tg, ag, shm, noc_rg, critical_rg,
                                              non_critical_rg, chosen_task, chosen_node, logging):
            print ("\t \033[32m* NOTE::\033[0mTASK "+str(chosen_task)+" MAPPED ON NODE "+str(chosen_node))
        else:
            raise ValueError("Mapping task on node failed...")

    # Added by Behrad (Still under development)
    # Swapping phase
    print "-----------------------"
    print "PHASE ONE IS DONE... STARTING SWAP PROCESS..."
    for node_id_1 in range(0, len(ag.nodes())-1):
        for node_id_2 in range(node_id_1+1, len(ag.nodes())-1):
            pass
            # Save current mapping in an array
            # Also save the mapping's csomm_cost in a variable
            comm_cost = calculate_com_cost(tg)

            # Swap (node_id_1 , node_id_2)
            swap_nodes(tg, ag, shm, noc_rg, critical_rg, non_critical_rg, node_id_1, node_id_2, logging)
            # Check and calculate communication cost for all communication flows in the task graph
            #   (which is equal to the total number of edges in the application graph
            #   starting from the communication flow with the largest communication volume first
            comm_cost_new = calculate_com_cost(tg)
            # If comm_cost of current mapping is the same or bigger than the previous mapping, discard mapping
            #   Revert back to previous mapping with better comm_cost
            # Else
            #   Save new mapping as better mapping with less comm_cost
            if comm_cost_new < comm_cost:
                print "\033[32m* NOTE::\033[0m BETTER SOLUTION FOUND WITH COST:", comm_cost_new
            else:
                pass
                # print "Reverting to old solution"
                swap_nodes(tg, ag, shm, noc_rg, critical_rg, non_critical_rg,
                           node_id_2, node_id_1, logging)
            # Reset the comm_cost after each swapping

    # End of Swapping phase
    print "SWAP PROCESS FINISHED..."
    Scheduler.schedule_all(tg, ag, shm, True, logging)
    return tg, ag
开发者ID:siavooshpayandehazad,项目名称:SoCDep2,代码行数:104,代码来源:NMap.py

示例2: mapping

# 需要导入模块: from Scheduler import Scheduler [as 别名]
# 或者: from Scheduler.Scheduler import schedule_all [as 别名]
def mapping(tg, ag, noc_rg, critical_rg, non_critical_rg, shm, logging, iteration=None
            , initial_mapping_string = None):
    """
    Calculate different mapping algorithms
    Returns tg And ag after Mapping in case of success
    :param tg: Task Graph
    :param ag: Architecture Graph
    :param noc_rg: NoC Routing Graph
    :param critical_rg: NoC Routing Graph for Critical Region
    :param non_critical_rg: NoC Routing Graph for non-Critical Region
    :param shm: System Health Map! (Please note that mapper should not even have access to ful SHMU info)
    :param logging: logging file
    :return: (tg, ag) in case of failing returns (None, None)
    """
    # to run the following heuristics (Min_Min,Max_Min), one needs to use independent
    # tasks... Please use: generate_random_independent_tg
    if Config.Mapping_Function == 'MinMin':
        if Config.tg.type == 'RandomIndependent':
            return SimpleGreedy.min_min_mapping(tg, ag, shm, logging)
        else:
            raise ValueError('WRONG TG TYPE FOR THIS MAPPING FUNCTION. SHOULD USE::RandomIndependent')

    elif Config.Mapping_Function == 'MaxMin':
        if Config.tg.type == 'RandomIndependent':
            return SimpleGreedy.max_min_mapping(tg, ag, shm, logging)
        else:
            raise ValueError('WRONG TG TYPE FOR THIS MAPPING FUNCTION. SHOULD USE::RandomIndependent')

    elif Config.Mapping_Function == 'MinExecutionTime':
        if Config.tg.type == 'RandomIndependent':
            return SimpleGreedy.min_execution_time(tg, ag, shm, logging)
        else:
            raise ValueError('WRONG TG TYPE FOR THIS MAPPING FUNCTION. SHOULD USE::RandomIndependent')

    elif Config.Mapping_Function == 'MinimumCompletionTime':
        if Config.tg.type == 'RandomIndependent':
            return SimpleGreedy.minimum_completion_time(tg, ag, shm, logging)
        else:
            raise ValueError('WRONG TG TYPE FOR THIS MAPPING FUNCTION. SHOULD USE::RandomIndependent')

    elif Config.Mapping_Function == 'NMap':
        return NMap.n_map(tg, ag, noc_rg, critical_rg, non_critical_rg, shm, logging)

    elif Config.Mapping_Function in ['LocalSearch', 'IterativeLocalSearch', 'SimulatedAnnealing']:
        if Config.tg.type in ['RandomDependent', 'Manual', 'FromDOTFile']:
            pass
        else:
            raise ValueError('WRONG TG TYPE FOR THIS MAPPING FUNCTION. SHOULD USE::RandomDependent')
        clustering_start_time = time.time()
        # clustered task graph
        if Config.task_clustering:
            ctg = copy.deepcopy(Clustering.generate_ctg(len(ag.nodes())))
            if Clustering.initial_clustering(tg, ctg):
                # Clustered Task Graph Optimization
                if Config.Clustering_Optimization:
                    (best_clustering, best_task_graph) = \
                        Clustering.ctg_opt_local_search(tg, ctg, Config.clustering.iterations, logging)
                    tg = copy.deepcopy(best_task_graph)
                    ctg = copy.deepcopy(best_clustering)
                    del best_clustering, best_task_graph
                    # Clustering_Test.double_check_ctg(tg, ctg)
                    Clustering_Reports.report_ctg(ctg, "CTG_PostOpt.png")
                    Clustering_Reports.viz_clustering_opt()
                else:
                    print ("CLUSTERING OPTIMIZATION TURNED OFF...")
                    print ("REMOVING EMPTY CLUSTERS...")
                    Clustering_Functions.remove_empty_clusters(ctg)
                    Clustering_Reports.report_ctg(ctg, "CTG_PostCleaning.png")

                print ("\033[92mTIME::\033[0m CLUSTERING AND OPTIMIZATION TOOK: "
                       + str(round(time.time()-clustering_start_time))+" SECONDS")
            else:
                print ("Initial Clustering Failed....")
                raise ValueError("INITIAL CLUSTERING FAILED...")
        else:
            ctg = copy.deepcopy(Clustering.gen_transparent_clusters(tg))
        mapping_start_time = time.time()
        # Mapping CTG on AG
        random_seed = Config.mapping_random_seed
        if Mapping_Functions.make_initial_mapping(tg, ctg, ag, shm, noc_rg, critical_rg, non_critical_rg,
                                                  True, logging, random_seed, iteration):
            #if Config.DistanceBetweenMapping:
            #    init_mapping_string = Mapping_Functions.mapping_into_string(tg)
                # print (init_mapping_string)
            #else:
            #    init_mapping_string = None

            Mapping_Reports.report_mapping(ag, logging)
            # Schedule all tasks
            Scheduling_Functions.clear_scheduling(ag)
            Scheduler.schedule_all(tg, ag, shm, Config.DebugDetails, logging)
            Scheduling_Reports.report_mapped_tasks(ag, logging)
            Mapping_Functions.mapping_cost_function(tg, ag, shm, Config.DebugInfo)
            if Config.Mapping_Function == 'LocalSearch':
                mapping_cost_file = open('Generated_Files/Internal/LocalSearchMappingCost.txt', 'w')
                current_cost = Mapping_Functions.mapping_cost_function(tg, ag, shm, False, initial_mapping_string=initial_mapping_string)
                mapping_cost_file.write(str(current_cost)+"\n")
                mapping_cost_file.close()

                mapping_process_file = open('Generated_Files/Internal/MappingProcess.txt', 'w')
#.........这里部分代码省略.........
开发者ID:siavooshpayandehazad,项目名称:SoCDep2,代码行数:103,代码来源:Mapping.py

示例3: initialize_system

# 需要导入模块: from Scheduler import Scheduler [as 别名]
# 或者: from Scheduler.Scheduler import schedule_all [as 别名]
def initialize_system(logging):
    """
    Generates the Task graph, Architecture Graph, System Health Monitoring Unit, NoC routing graph(s) and
    Test Task Graphs and does the mapping and scheduling and returns to the user the initial system
    :param logging: logging file
    :return:  tg, ag, shmu, noc_rg, critical_rg, noncritical_rg, pmcg
    """
    tg = copy.deepcopy(TG_Functions.generate_tg())
    if Config.DebugInfo:
        Task_Graph_Reports.report_task_graph(tg, logging)
    Task_Graph_Reports.draw_task_graph(tg)
    if Config.TestMode:
        TG_Test.check_acyclic(tg, logging)
    ####################################################################
    ag = copy.deepcopy(AG_Functions.generate_ag(logging))
    AG_Functions.update_ag_regions(ag)
    AG_Functions.random_darkness(ag)
    if Config.EnablePartitioning:
        AG_Functions.setup_network_partitioning(ag)
    if Config.FindOptimumAG:
        Arch_Graph_Reports.draw_ag(ag, "AG_Full")
    else:
        Arch_Graph_Reports.draw_ag(ag, "AG")
    ####################################################################
    Config.setup_turns_health()

    shmu = SystemHealthMonitoringUnit.SystemHealthMonitoringUnit()
    shmu.setup_noc_shm(ag, Config.TurnsHealth, True)
    # Here we are injecting initial faults of the system: we assume these fault
    # information is obtained by post manufacturing system diagnosis
    if Config.FindOptimumAG:
        vl_opt.optimize_ag_vertical_links(ag, shmu, logging)
        vl_opt_functions.cleanup_ag(ag, shmu)
        Arch_Graph_Reports.draw_ag(ag, "AG_VLOpt")
    SHMU_Functions.apply_initial_faults(shmu)
    if Config.viz.shm:
        SHMU_Reports.draw_shm(shmu.SHM)
        SHMU_Reports.draw_temp_distribution(shmu.SHM)
    # SHM_Reports.report_noc_shm()
    ####################################################################
    routing_graph_start_time = time.time()
    if Config.SetRoutingFromFile:
        noc_rg = copy.deepcopy(Routing.gen_noc_route_graph_from_file(ag, shmu, Config.RoutingFilePath,
                                                                     Config.DebugInfo, Config.DebugDetails))
    else:
        noc_rg = copy.deepcopy(Routing.generate_noc_route_graph(ag, shmu, Config.UsedTurnModel,
                                                                Config.DebugInfo, Config.DebugDetails))
    Routing_Functions.check_deadlock_freeness(noc_rg)
    print ("\033[92mTIME::\033[0m ROUTING GRAPH GENERATION TOOK: " +
           str(round(time.time()-routing_graph_start_time))+" SECONDS")
    # this is for double checking...
    if Config.FindOptimumAG:
        Calculate_Reachability.reachability_metric(ag, noc_rg, True)
    # Some visualization...
    if Config.viz.rg:
        RoutingGraph_Reports.draw_rg(noc_rg)
    ####################################################################
    # in case of partitioning, we have to route based on different Route-graphs
    if Config.EnablePartitioning:
        critical_rg, noncritical_rg = Calculate_Reachability.calculate_reachability_with_regions(ag, shmu)
        ReachabilityReports.report_gsnoc_friendly_reachability_in_file(ag)
    else:
        critical_rg, noncritical_rg = None, None
        Calculate_Reachability.calculate_reachability(ag, noc_rg)
        Calculate_Reachability.optimize_reachability_rectangles(ag, Config.NumberOfRects)
        # ReachabilityReports.report_reachability(ag)
        ReachabilityReports.report_reachability_in_file(ag, "ReachAbilityNodeReport")
        ReachabilityReports.report_gsnoc_friendly_reachability_in_file(ag)
    ####################################################################
    if Config.read_mapping_from_file:
        Mapping_Functions.read_mapping_from_file(tg, ag, shmu.SHM, noc_rg, critical_rg, noncritical_rg,
                                                 Config.mapping_file_path, logging)
        Scheduler.schedule_all(tg, ag, shmu.SHM, False, logging)
    else:
        best_tg, best_ag = Mapping.mapping(tg, ag, noc_rg, critical_rg, noncritical_rg, shmu.SHM, logging)
        if best_ag is not None and best_tg is not None:
            tg = copy.deepcopy(best_tg)
            ag = copy.deepcopy(best_ag)
            del best_tg, best_ag
            # SHM.add_current_mapping_to_mpm(tg)
            Mapping_Functions.write_mapping_to_file(ag, "mapping_report")
    if Config.viz.mapping_distribution:
        Mapping_Reports.draw_mapping_distribution(ag, shmu)
    if Config.viz.mapping:
        Mapping_Reports.draw_mapping(tg, ag, shmu.SHM, "Mapping_post_opt")
    if Config.viz.scheduling:
        Scheduling_Reports.generate_gantt_charts(tg, ag, "SchedulingTG")
    ####################################################################
    # PMC-Graph
    # at this point we assume that the system health map knows about the initial faults from
    # the diagnosis process
    if Config.GeneratePMCG:
        pmcg_start_time = time.time()
        if Config.OneStepDiagnosable:
            pmcg = TestSchedulingUnit.gen_one_step_diagnosable_pmcg(ag, shmu.SHM)
        else:
            pmcg = TestSchedulingUnit.gen_sequentially_diagnosable_pmcg(ag, shmu.SHM)
        test_tg = TestSchedulingUnit.generate_test_tg_from_pmcg(pmcg)
        print ("\033[92mTIME::\033[0m PMCG AND TTG GENERATION TOOK: " +
               str(round(time.time()-pmcg_start_time)) + " SECONDS")
#.........这里部分代码省略.........
开发者ID:siavooshpayandehazad,项目名称:SoCDep2,代码行数:103,代码来源:SystemInitialization.py

示例4: mapping_opt_local_search

# 需要导入模块: from Scheduler import Scheduler [as 别名]
# 或者: from Scheduler.Scheduler import schedule_all [as 别名]
def mapping_opt_local_search(tg, ctg, ag, noc_rg, critical_rg, noncritical_rg, shm,
                             iteration_num, report, detailed_report, logging,
                             cost_data_file_name, mapping_process_file_name, random_seed,
                             initial_mapping_string=None):
    random.seed(random_seed)
    if report:
        print ("===========================================")
        print ("STARTING MAPPING OPTIMIZATION...USING LOCAL SEARCH...")
        print ("NUMBER OF ITERATIONS: "+str(iteration_num))

    if type(cost_data_file_name) is str:
        mapping_cost_file = open('Generated_Files/Internal/'+cost_data_file_name+'.txt', 'a')
    else:
        raise ValueError("cost_data_file_name name is not string: "+str(cost_data_file_name))

    if type(mapping_process_file_name) is str:
        mapping_process_file = open('Generated_Files/Internal/'+mapping_process_file_name+'.txt', 'a')
    else:
        raise ValueError("mapping_process_file name is not string: "+str(mapping_process_file_name))

    best_tg = copy.deepcopy(tg)
    best_ag = copy.deepcopy(ag)
    best_ctg = copy.deepcopy(ctg)
    best_cost = Mapping_Functions.mapping_cost_function(tg, ag, shm, False, initial_mapping_string=initial_mapping_string)
    starting_cost = best_cost
    for iteration in range(0, iteration_num):
        logging.info("       ITERATION:"+str(iteration))
        cluster_to_move = random.choice(ctg.nodes())
        current_node = ctg.node[cluster_to_move]['Node']
        Mapping_Functions.remove_cluster_from_node(tg, ctg, ag, noc_rg, critical_rg, noncritical_rg,
                                                   cluster_to_move, current_node, logging)
        destination_node = random.choice(ag.nodes())
        if Config.EnablePartitioning:
            while ctg.node[cluster_to_move]['Criticality'] != ag.node[destination_node]['Region']:
                destination_node = random.choice(ag.nodes())
        # print (ctg.node[cluster_to_move]['Criticality'],AG.node[destination_node]['Region'])

        try_counter = 0
        while not Mapping_Functions.add_cluster_to_node(tg, ctg, ag, shm, noc_rg, critical_rg, noncritical_rg,
                                                        cluster_to_move, destination_node, logging):

            # If add_cluster_to_node fails it automatically removes all the connections...
            # we need to add the cluster to the old place...
            Mapping_Functions.add_cluster_to_node(tg, ctg, ag, shm, noc_rg, critical_rg, noncritical_rg,
                                                  cluster_to_move, current_node, logging)

            # choosing another cluster to move
            cluster_to_move = random.choice(ctg.nodes())
            current_node = ctg.node[cluster_to_move]['Node']
            Mapping_Functions.remove_cluster_from_node(tg, ctg, ag, noc_rg, critical_rg, noncritical_rg,
                                                       cluster_to_move, current_node, logging)
            destination_node = random.choice(ag.nodes())
            if Config.EnablePartitioning:
                while ctg.node[cluster_to_move]['Criticality'] != ag.node[destination_node]['Region']:
                    destination_node = random.choice(ag.nodes())
            # print (ctg.node[cluster_to_move]['Criticality'],AG.node[destination_node]['Region'])

            if try_counter >= 3*len(ag.nodes()):
                if report:
                    print ("CAN NOT FIND ANY FEASIBLE SOLUTION... ABORTING LOCAL SEARCH...")
                logging.info("CAN NOT FIND ANY FEASIBLE SOLUTION... ABORTING LOCAL SEARCH...")
                tg = copy.deepcopy(best_tg)
                ag = copy.deepcopy(best_ag)
                ctg = copy.deepcopy(ctg)
                if report:
                    Scheduling_Reports.report_mapped_tasks(ag, logging)
                    Mapping_Functions.mapping_cost_function(tg, ag, shm, True, initial_mapping_string=initial_mapping_string)
                return best_tg, best_ctg, best_ag
            try_counter += 1

        Scheduling_Functions.clear_scheduling(ag)
        Scheduler.schedule_all(tg, ag, shm, False, logging)

        current_cost = Mapping_Functions.mapping_cost_function(tg, ag, shm, detailed_report, initial_mapping_string= initial_mapping_string)
        mapping_process_file.write(Mapping_Functions.mapping_into_string(tg)+"\n")
        mapping_cost_file.write(str(current_cost)+"\n")
        if current_cost <= best_cost:
            if current_cost < best_cost:
                if report:
                    print ("\033[32m* NOTE::\033[0mBETTER SOLUTION FOUND WITH COST: "+str(current_cost) +
                           "\t ITERATION:"+str(iteration))
                logging.info("NOTE:: MOVED TO SOLUTION WITH COST: "+str(current_cost)+"ITERATION: "+str(iteration))
            else:
                logging.info("NOTE:: MOVED TO SOLUTION WITH COST: "+str(current_cost)+"ITERATION: "+str(iteration))

            best_tg = copy.deepcopy(tg)
            best_ag = copy.deepcopy(ag)
            best_ctg = copy.deepcopy(ctg)
            best_cost = current_cost
        else:
            tg = copy.deepcopy(best_tg)
            ag = copy.deepcopy(best_ag)
            ctg = copy.deepcopy(best_ctg)
            mapping_process_file.write(Mapping_Functions.mapping_into_string(tg)+"\n")

    Scheduling_Functions.clear_scheduling(ag)
    Scheduler.schedule_all(tg, ag, shm, False, logging)
    mapping_process_file.close()
    mapping_cost_file.close()
    if report:
#.........这里部分代码省略.........
开发者ID:siavooshpayandehazad,项目名称:SoCDep2,代码行数:103,代码来源:Local_Search.py

示例5: mapping_opt_iterative_local_search

# 需要导入模块: from Scheduler import Scheduler [as 别名]
# 或者: from Scheduler.Scheduler import schedule_all [as 别名]
def mapping_opt_iterative_local_search(tg, ctg, ag, noc_rg, critical_rg, noncritical_rg, shm, iteration_num,
                                       sub_iteration, report, detailed_report, logging):
    if report:
        print ("===========================================")
        print ("STARTING MAPPING OPTIMIZATION...USING ITERATIVE LOCAL SEARCH...")

    best_tg = copy.deepcopy(tg)
    best_ag = copy.deepcopy(ag)
    best_ctg = copy.deepcopy(ctg)
    best_cost = Mapping_Functions.mapping_cost_function(tg, ag, shm, False)
    starting_cost = best_cost
    if report:
        print ("INITIAL COST:"+str(starting_cost))
    mapping_cost_file = open('Generated_Files/Internal/LocalSearchMappingCost.txt', 'w')
    mapping_cost_file.close()
    mapping_process_file = open('Generated_Files/Internal/MappingProcess.txt', 'w')
    mapping_process_file.close()
    for Iteration in range(0, iteration_num):
        logging.info("        ITERATION:"+str(Iteration))
        random_seed = Config.mapping_random_seed
        random.seed(Config.mapping_random_seed)
        for i in range(0, Iteration):
            random_seed = random.randint(1, 100000)
        (current_tg, current_ctg, current_ag) = mapping_opt_local_search(tg, ctg, ag, noc_rg, critical_rg,
                                                                         noncritical_rg, shm, sub_iteration,
                                                                         False, detailed_report, logging,
                                                                         "LocalSearchMappingCost",
                                                                         "mapping_process_file_name", random_seed)
        if current_tg is not False:
            current_cost = Mapping_Functions.mapping_cost_function(current_tg, current_ag, shm, False)
            if current_cost <= best_cost:
                if current_cost < best_cost:
                    if report:
                        print ("\033[32m* NOTE::\033[0mBETTER SOLUTION FOUND WITH COST: "+str(current_cost) +
                               "\t ITERATION: "+str(Iteration))
                    logging.info("NOTE:: MOVED TO SOLUTION WITH COST: "+str(current_cost)+"ITERATION: "+str(Iteration))
                else:
                    logging.info("NOTE:: MOVED TO SOLUTION WITH COST: "+str(current_cost)+"ITERATION: "+str(Iteration))
                best_tg = copy.deepcopy(current_tg)
                best_ag = copy.deepcopy(current_ag)
                best_ctg = copy.deepcopy(current_ctg)
                best_cost = current_cost
        del current_tg
        del current_ag
        del current_ctg
        Mapping_Functions.clear_mapping(tg, ctg, ag)
        counter = 0
        schedule = True
        random_seed = Config.mapping_random_seed
        random.seed(Config.mapping_random_seed)
        for i in range(0, Iteration):
            random_seed = random.randint(1, 100000)
        while not Mapping_Functions.make_initial_mapping(tg, ctg, ag, shm, noc_rg, critical_rg,
                                                         noncritical_rg, False, logging, random_seed):
            if counter == 10:   # we try 10 times to find some initial solution... how ever if it fails...
                schedule = False
                break
            counter += 1
        if schedule:
            Scheduling_Functions.clear_scheduling(ag)
            Scheduler.schedule_all(tg, ag, shm, False, logging)
        else:
            if report:
                print ("\033[33mWARNING::\033[0m CAN NOT FIND ANOTHER FEASIBLE SOLUTION... ",
                       "ABORTING ITERATIVE LOCAL SEARCH...")
            logging.info("CAN NOT FIND ANOTHER FEASIBLE SOLUTION... ABORTING ITERATIVE LOCAL SEARCH...")
            if report:
                print ("-------------------------------------")
                print ("STARTING COST: "+str(starting_cost)+"\tFINAL COST: "+str(best_cost))
                print ("IMPROVEMENT:"+str("{0:.2f}".format(100*(starting_cost-best_cost)/starting_cost))+" %")
            return best_tg, best_ctg, best_ag

    if report:
        print ("-------------------------------------")
        print ("STARTING COST:"+str(starting_cost)+"\tFINAL COST:"+str(best_cost))
        print ("IMPROVEMENT:"+str("{0:.2f}".format(100*(starting_cost-best_cost)/starting_cost))+" %")
    return best_tg, best_ctg, best_ag
开发者ID:siavooshpayandehazad,项目名称:SoCDep2,代码行数:79,代码来源:Local_Search.py

示例6: optimize_mapping_sa

# 需要导入模块: from Scheduler import Scheduler [as 别名]
# 或者: from Scheduler.Scheduler import schedule_all [as 别名]
def optimize_mapping_sa(tg, ctg, ag, noc_rg, critical_rg, noncritical_rg,
                        shm, cost_data_file, logging):
    print ("===========================================")
    print ("STARTING MAPPING OPTIMIZATION...USING SIMULATED ANNEALING...")
    print ("STARTING TEMPERATURE: "+str(Config.SA_InitialTemp))
    print ("ANNEALING SCHEDULE: "+Config.SA_AnnealingSchedule)
    print ("TERMINATION CRITERIA: "+Config.TerminationCriteria)
    print ("================")

    if type(cost_data_file) is str:
        mapping_cost_file = open('Generated_Files/Internal/'+cost_data_file+'.txt', 'a')
    else:
        raise ValueError("cost_data_file name is not string: "+str(cost_data_file))

    mapping_process_file = open('Generated_Files/Internal/MappingProcess.txt', 'w')
    sa_temperature_file = open('Generated_Files/Internal/SATemp.txt', 'w')
    sa_cost_slop_file = open('Generated_Files/Internal/SACostSlope.txt', 'w')
    sa_huang_race_file = open('Generated_Files/Internal/SAHuangRace.txt', 'w')

    if Config.SA_AnnealingSchedule in ['Adaptive', 'Aart', 'Huang']:
        cost_monitor = deque([])
    else:
        cost_monitor = []

    if Config.DistanceBetweenMapping:
        init_map_string = Mapping_Functions.mapping_into_string(tg)
        if Config.Mapping_CostFunctionType == 'CONSTANT':
            Mapping_Functions.clear_mapping(tg, ctg, ag)
            if not Mapping_Functions.make_initial_mapping(tg, ctg, ag, shm, noc_rg, critical_rg,
                                                          noncritical_rg, True, logging,
                                                          Config.mapping_random_seed):
                raise ValueError("FEASIBLE MAPPING NOT FOUND...")
    else:
        init_map_string = None

    current_tg = copy.deepcopy(tg)
    current_ag = copy.deepcopy(ag)
    current_ctg = copy.deepcopy(ctg)
    current_cost = Mapping_Functions.mapping_cost_function(tg, ag, shm, False, initial_mapping_string=init_map_string)
    starting_cost = current_cost

    best_tg = copy.deepcopy(tg)
    best_ag = copy.deepcopy(ag)
    best_ctg = copy.deepcopy(ctg)
    best_cost = current_cost

    initial_temp = Config.SA_InitialTemp
    sa_temperature_file.write(str(initial_temp)+"\n")
    temperature = initial_temp
    slope = None
    zero_slope_counter = 0
    standard_deviation = None

    # for Huang Annealing schedule
    huang_counter1 = 0
    huang_counter2 = 0
    huang_steady_counter = 0
    iteration_num = Config.SimulatedAnnealingIteration
    # for i in range(0, iteration_num):
    #       move to another solution
    i = 0
    while True:
        i += 1
        new_tg, new_ctg, new_ag = move_to_next_solution(i, current_tg, current_ctg, current_ag,  noc_rg,
                                                        shm, critical_rg, noncritical_rg, logging)
        Scheduling_Functions.clear_scheduling(new_ag)
        Scheduler.schedule_all(new_tg, new_ag, shm, False, logging)

        # calculate the cost of new solution
        new_cost = Mapping_Functions.mapping_cost_function(new_tg, new_ag, shm, False,
                                                           initial_mapping_string=init_map_string)

        if new_cost < best_cost:
            best_tg = copy.deepcopy(new_tg)
            best_ag = copy.deepcopy(new_ag)
            best_ctg = copy.deepcopy(new_ctg)
            best_cost = new_cost
            print ("\033[33m* NOTE::\033[0mFOUND BETTER SOLUTION WITH COST:"+"{0:.2f}".format(new_cost) +
                   "\t ITERATION:"+str(i)+"\tIMPROVEMENT:" +
                   "{0:.2f}".format(100*(starting_cost-new_cost)/starting_cost)+" %")
        # calculate the probability P of accepting the solution
        prob = metropolis(current_cost, new_cost, temperature)
        # print ("prob:", prob)
        # throw the coin with probability P
        random_seed = Config.mapping_random_seed
        random.seed(Config.mapping_random_seed)
        for j in range(0, i):
            random_seed = random.randint(1, 100000)
        random.seed(random_seed)
        logging.info("Throwing Dice: random_seed: "+str(random_seed)+"    iteration: "+str(i))
        if prob > random.random():
            # accept the new solution
            move_accepted = True
            current_tg = copy.deepcopy(new_tg)
            current_ag = copy.deepcopy(new_ag)
            current_ctg = copy.deepcopy(new_ctg)
            current_cost = new_cost
            if Config.SA_ReportSolutions:
                if slope is not None:
                    print ("\033[32m* NOTE::\033[0mMOVED TO SOLUTION WITH COST:", "{0:.2f}".format(current_cost),
#.........这里部分代码省略.........
开发者ID:siavooshpayandehazad,项目名称:SoCDep2,代码行数:103,代码来源:SimulatedAnnealing.py


注:本文中的Scheduler.Scheduler.schedule_all方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。