def qq_06(): c_t = 525 c_e = 1.25 rc = RawCosts(unit_cost=1.00, ordering_cost=c_t, holding_cost=c_e, holding_time_unit='M') d = Demand(quantity=120, time_unit='M') Q = EOQ.optimal_order_quantity(raw_costs=rc, demand=d) print("EOQ: {}".format(Q)) B = 170 L = 1 mu_dl = 30 sigma_dl = 9 inner_value = (B * d.quantity) / (c_e * sigma_dl * Q * sqrt(2 * pi)) print("inner value: {}".format(inner_value)) k = sqrt(2 * log(inner_value)) print("k: {}".format(k)) s = mu_dl + k * sigma_dl print("s: {}".format(s))
def calc_eoq(row): cost = row['cost'] demand = row['demand'] rc = RawCosts(unit_cost=cost, ordering_cost=c_t, holding_rate=h) d = Demand(quantity=demand) return EOQ.optimal_order_quantity(rc, d)
def __init__(self, scenario_id, api_run=False): self.scenario_id = scenario_id self.scenario = Scenario(self.scenario_id) self.api_run = api_run self.outputs = Output() self.demand = Demand(self.scenario) self.supply = None self.demand_solved, self.supply_solved = False, False
def configure_energy_system(self): print 'configuring energy system' self.demand = Demand(self.cfgfile_path, self.custom_pint_definitions_path) self.supply = Supply(os.path.join(os.getcwd(), 'outputs'), self.cfgfile_path, self.custom_pint_definitions_path) self.configure_demand() self.configure_supply()
def arrival_demand(times: Clock, system: Configuration) -> None: print("I. Arrival demand", times.current, end="\t###\t") demand = Demand(times.arrival) print("demand ID:", demand.id) if system.queue.empty() and not system.device.serves: times.service_start = times.current system.queue.put(demand) times.update_arrival_time(system.lambd)
def __init__(self): super().__init__([pin_number1, pin_number2]) self.demand = Demand(mode='', event='key', pulse_time=0.0001) self.user_methodd = [user_method1, user_method2] self.handler = [handler1, handler2] # key指定し、self.sensor_valueにkeyと同じ値が入ったとき # user_methodを逐次的に呼び出していく super().add_event_handler(key, handler)
def __init__(self): self.demand = Demand(mode='double', edge=1, pulse_time=0.00001) super().__init__([20, 21]) self.user_methods = [self.sensor_method, self.user_method1] self.event_handler.add_event_handler(20, self.user_method2) self.pulse_start = 0 self.pulse_end = 0 self.pulse_duration = 0 self.distance = 0
def __init__(self, scenario_id, api_run=False): self.scenario_id = scenario_id self.api_run = api_run self.scenario = cfg.scenario_dict[self.scenario_id] self.demand_case_id = util.sql_read_table('Scenarios', 'demand_case', id=self.scenario_id) self.supply_case_id = util.sql_read_table('Scenarios', 'supply_case', id=self.scenario_id) self.outputs = Output() self.demand = Demand() self.supply = None self.demand_solved, self.supply_solved = False, False
def part3(): d = Demand(240, 'M') rc = RawCosts(50.0, 100.0, 0.01, holding_time_unit='M') Q = EOQ.optimal_order_quantity(rc, d) print(Q) T = EOQ.optimal_cycle_time(rc, d) print(T) print(T * 4)
def test_create_path(): """Test creation of a path.""" network = Network() demand = Demand(network) alice = Router(network, "alice") bob = Router(network, "bob") _path = Path(demand=demand, name="alice-to-bob", end_point_1=alice, end_point_2=bob, bandwidth=10, fidelity=0.95)
def part01(): sigma_dl = calc_sigma_dl() g_k = (0.0211 + 0.0206) / 2 # from table d = Demand(quantity=D) rc = RawCosts(unit_cost=c, ordering_cost=c_t, holding_rate=h) Q = EOQ.optimal_order_quantity(rc, d) IFR = 1 - ((sigma_dl * g_k) / Q) print("IFR: {}".format(IFR)) return Q
def part01(): sku = '3206-BO1' item = df.loc[sku] rc = RawCosts(unit_cost=item['cost'], ordering_cost=c_t, holding_rate=h) d = Demand(quantity=item['demand']) Q = EOQ.optimal_order_quantity(rc, d) print("Q: {}".format(Q)) sigma = item['rmse'] print("sigma: {}".format(sigma)) print("sigma_dl: {}".format(sigma * math.sqrt(1 / 12)))
def __init__(self, db_path, cfgfile_path, custom_pint_definitions_path=None, name=None, author=None): self.model_config(db_path, cfgfile_path, custom_pint_definitions_path) self.name = cfg.cfgfile.get('case', 'scenario') if name is None else name self.author = cfg.cfgfile.get('case', 'author') if author is None else author self.demand = Demand() self.supply = Supply()
def test_demand(): from demand import Demand dm = Demand() # in-home activities and out-of-home activities # madantory activities: work/business, school/college # maintenance activities: escort passengers, shopping # discretionary activities: eating out, visiting friends activity_data = [['home', 1.0, 600, -0.010, 1.0, 720, (0, 1440), 360], ['work', 0.0, 1600, 0.010, 1.0, 720, (240, 1440), 240], ['school', 0.0, 1600, 0.010, 1.0, 720, (240, 1440), 240], ['eating', 0.0, 420, 0.010, 1.0, 1170, (720, 1440), 10], ['shopping', 0.0, 500, 0.010, 1.0, 1110, (720, 1440), 10], ['visiting', 0.0, 500, 0.010, 1.0, 1110, (720, 1440), 10], [ 'escorting', 0.0, 500, 0.010, 1.0, 1110, (720, 1440), 10 ]] create_objects(dm.add_activity, activity_data) print 'activities:' pprint(dm.activities.items()) print "building activity utility..." dm.build_activity_util() logger.info('activity utility: home') logger.debug(pformat(dm.get_activity_util(dm.activities["home"]))) logger.info('activity utility: work') logger.debug(pformat(dm.get_activity_util(dm.activities["work"]))) logger.info('activity utility: shopping') logger.debug(pformat(dm.get_activity_util(dm.activities["shopping"]))) # intra-household interactions # entire day level: # staying at home, absent together # non-madantory DAP together (day-off for major shopping) # episode level: # shared activity # escorting (children to school) # allocation of maintenance task (shopping) # car allocation # types of joint travel # fully-joint tour, joint outbound, joint inbound # drop-off/get-off, pick-up/get-in program_data = [[0, []], [1, ['shopping']], [3, ['eating']], [2, ['visiting']], [4, ['shopping', 'visiting']], [5, ['shopping', 'eating']]] create_objects(dm.add_program, program_data) print 'programs:' pprint(dm.programs.items()) return dm
def add_demand(self, source: str, target: str, demand: float): source_node = self.get_node_based_on_label(source) target_node = self.get_node_based_on_label(target) if source_node not in self.nodes or target_node not in self.nodes: raise Exception(f"{source} or {target} not in the Graph") damand_exists = False for existing_demand in self.demands: if (source_node == existing_demand.source and target_node == existing_demand.target): existing_demand.demand += demand damand_exists = True if not damand_exists: demand_object = Demand(source_node, target_node, demand) self.demands.append(demand_object)
def part02(): sku = '3206-BO1' item = df.loc[sku] cost = item['cost'] demand = item['demand'] rc = RawCosts(unit_cost=cost, ordering_cost=c_t, holding_rate=h) d = Demand(quantity=demand) Q = EOQ.optimal_order_quantity(rc, d) sigma = item['rmse'] sigma_dl = sigma * math.sqrt(1 / 12) print("sigma_dl * ci: {}".format(sigma_dl * cost)) print("D/Q: {}".format(demand / Q)) print("(D/Q) * (sigma_dl * ci): {}".format((demand / Q) * sigma_dl * cost))
def test_init_with_invalid_time_unit_raises(): with pytest.raises(ValueError): Demand(quantity=1, time_unit='X')
def test_init_with_missing_quantity_raises(): with pytest.raises(ValueError): Demand(quantity=None)
def test_init_with_positive_quantity_captures(): d = Demand(quantity=1) assert d.quantity == 1
def test_init_with_valid_time_unit_captures(): d = Demand(quantity=1, time_unit='W') assert d.time_unit == 'W'
def get_demand(): return Demand(1000)
def readInputData(): net = Network() demands = Demand() signal_manager = SignalManager() print('Reading input data...') # ------------------Meso Node--------------------# print(' loading mesoscopic nodes') mesonode_filepath = os.path.join(_working_directory, r'mesonet\node.csv') with open(mesonode_filepath, 'r') as fp: reader = csv.DictReader(fp) for i, line in enumerate(reader): mesonode = MesoNode() mesonode.node_id = int(line['node_id']) mesonode.x = float(line['x_coord']) mesonode.y = float(line['y_coord']) mesonode.node_seq_no = i net.meso_node_list.append(mesonode) net.meso_node_id_to_seq_no_dict[ mesonode.node_id] = mesonode.node_seq_no net.number_of_meso_nodes = len(net.meso_node_list) # ------------------Meso Link--------------------# print(' loading mesoscopic links') mesolink_filepath = os.path.join(_working_directory, r'mesonet\link.csv') with open(mesolink_filepath, 'r') as fp: reader = csv.DictReader(fp) for i, line in enumerate(reader): mesolink = MesoLink() mesolink.link_id = line['link_id'] mesolink.from_node_id = int(line['from_node_id']) mesolink.to_node_id = int(line['to_node_id']) mesolink.length = float(line['length']) mesolink.number_of_lanes = int(line['lanes']) mesolink.speed_limit = float(line['free_speed']) lane_cap = line['capacity'] mesolink.lane_cap = float(lane_cap) if lane_cap else 1200 mesolink.geometry = line['geometry'] mesolink.link_seq_no = i from_node = net.meso_node_list[net.meso_node_id_to_seq_no_dict[ mesolink.from_node_id]] from_node.m_outgoing_link_list.append(mesolink.link_id) to_node = net.meso_node_list[net.meso_node_id_to_seq_no_dict[ mesolink.to_node_id]] to_node.m_incoming_link_list.append(mesolink.link_id) mesolink.setLinkKey() mesolink.initializeMicroNodeList() net.meso_link_list.append(mesolink) net.meso_link_id_to_seq_no_dict[ mesolink.link_id] = mesolink.link_seq_no net.meso_link_key_to_seq_no_dict[ mesolink.link_key] = mesolink.link_seq_no net.number_of_meso_links = len(net.meso_link_list) # ------------------Micro Node--------------------# print(' loading microscopic nodes') micronode_filepath = os.path.join(_working_directory, r'micronet\node.csv') with open(micronode_filepath, 'r') as fp: reader = csv.DictReader(fp) for i, line in enumerate(reader): micronode = MicroNode() micronode.node_id = int(line['node_id']) micronode.x = float(line['x_coord']) micronode.y = float(line['y_coord']) micronode.meso_link_id = line['meso_link_id'] micronode.lane_no = int(line['lane_no']) micronode.node_seq_no = i net.micro_node_list.append(micronode) net.micro_node_id_to_seq_no_dict[ micronode.node_id] = micronode.node_seq_no meso_link = net.meso_link_list[net.meso_link_id_to_seq_no_dict[ micronode.meso_link_id]] meso_link.micro_node_list[micronode.lane_no - 1].append( micronode.node_id) net.number_of_micro_nodes = len(net.micro_node_list) # ------------------Micro Link--------------------# print(' loading microscopic links') microlink_filepath = os.path.join(_working_directory, r'micronet\link.csv') with open(microlink_filepath, 'r') as fp: reader = csv.DictReader(fp) for i, line in enumerate(reader): microlink = MicroLink() microlink.link_id = line['link_id'] microlink.from_node_id = int(line['from_node_id']) microlink.to_node_id = int(line['to_node_id']) microlink.meso_link_id = line['meso_link_id'] microlink.cell_type = int(line['cell_type']) microlink.length = float(line['length']) microlink.speed_limit = float(line['free_speed']) microlink.additional_cost = float(line['additional_cost']) microlink.link_seq_no = i # microlink.Initialization() net.micro_link_list.append(microlink) from_node = net.micro_node_list[net.micro_node_id_to_seq_no_dict[ microlink.from_node_id]] from_node.m_outgoing_link_list.append(microlink.link_id) to_node = net.micro_node_list[net.micro_node_id_to_seq_no_dict[ microlink.to_node_id]] to_node.m_incoming_link_list.append(microlink.link_id) mesolink = net.meso_link_list[net.meso_link_id_to_seq_no_dict[ microlink.meso_link_id]] mesolink.micro_link_list.append(microlink.link_id) mesolink.graph.add_edge( microlink.to_node_id, microlink.from_node_id, weight=microlink.cost ) # reverse link direction to reduce shortest path searching time net.micro_link_id_to_seq_no_dict[ microlink.link_id] = microlink.link_seq_no net.number_of_micro_links = len(net.micro_link_list) print( f' net: {net.number_of_meso_nodes} meso nodes, {net.number_of_meso_links} meso links, ' f'{net.number_of_micro_nodes} micro nodes, {net.number_of_micro_links} micro links' ) # ------------------Demand--------------------# print(' loading demands') demand_filepath = os.path.join(_working_directory, r'input_demand.csv') demand_record_list = demands.demand_record_list total_demands = 0 with open(demand_filepath, 'r') as fp: reader = csv.DictReader(fp) for line in reader: demand_record = { 'o_node_id': int(line['o_node_id']), 'd_node_id': int(line['d_node_id']), 'volume': int(line['volume']), 'time_start': float(line['time_start']), 'time_end': float(line['time_end']) } demand_record_list.append(demand_record) total_demands += int(line['volume']) print(f' demand: {total_demands} agents') # ------------------Signal--------------------# signal_filepath = os.path.join(_working_directory, r'input_signal.csv') if not os.path.isfile(signal_filepath): return print(' loading signal') controller_data_dict = signal_manager.controller_data_dict with open(signal_filepath, 'r') as fp: reader = csv.DictReader(fp) for line in reader: controller_id = line['controller_id'] phase_id = int(line['phase_id']) movements = line['movements'] duration = int(line['duration']) if controller_id not in controller_data_dict.keys(): controller_data_dict[controller_id] = [] controller = controller_data_dict[controller_id] controller.append({ 'phase_id': phase_id, 'movements': movements, 'duration': duration }) print(f' signal: {len(controller_data_dict)} controllers') return net, demands, signal_manager
np.random.seed(42) # Reproducibility MPR # Initializing vehicles Tampere.reset() # ============================================================================== # Defaults # ============================================================================== # Traffic Network trf_net = {"lengths_per_link": (20000, 10000), "lanes_per_link": (1, 2)} traffic_network = TrafficNetwork(**trf_net) # Demand demands = Demand((C / 2, ), (12, )) trf_dmd = {"lks": (1, ), "demands": (demands, demands)} traffic_demand = TrafficDemand(**trf_dmd) # ============================================================================== # Classes # ============================================================================== class Scenario: def __init__( self, traffic_network=traffic_network, traffic_demand=traffic_demand, mpr=MPR,
def get_demand(quantity=1000): return Demand(quantity)
def demand_read(): obj = Demand(file, 'demand') print('imported') dmd_df = obj.read() print('return to base') print(dmd_df)
def test_init_with_negative_quantity_raises(): with pytest.raises(ValueError): Demand(quantity=-1)
from smbus_sensor_conf import SmbusSensorConf from demand_driven_io import DemandDrivenIo from sensor_exception import SensorException from demand import Demand class DemandSmbusSensor(SmbusSensorConf, DemandDrivenIo, SensorException): """This class is for the demand driven sensors""" def __init__(self, address=None, bus=1): super().__init__(self, address, bus) self.event_handlers = EventHandler() def demand_issue(self, demand, **catch_event) self.sensor_data = [] # 読み取ってとってくる値を格納する箱 if isinstance(demand, Demand()): self.demand = demand else: print('Please give a Demand object.') return False if catch_event != {}: # cath_eventは{'1011':method} これがもらえるとよそう # main処理 書 -> 読 -> コールバック(値に応じた) for event in catch_event: self.event_handlers.add(event, catch_event[event]) for write in demand.write_methods(): write() time.sleep(demand.interval)
from demand_driven_io import DemandDrivenIo from sensor_exception import SensorException from demand import Demand from event_handler import EventHandler class DemandSpiSensor(SpiSensorConf, DemandtDrivenIo, SensorException): """This class is for the demand driven sensors""" def __init__(self, device=0, bus=0): super().__init__(self, device, bus) self.event_handlers = EventHandler() def demand_issue(self, demand, **catch_event) self.sensor_data = [] # 読み取ってとってくる値を取得 if isinstance(demand, Demand): demand = Demand() else: print('Please give a Demand object.') return False if catch_event != {}: # cath_eventは{'1011':method} これがもらえるとよそう # main処理 書 -> 読 -> コールバック(値に応じた) for event in catch_event: self.event_handlers.add(event, catch_event[event]) for write in demand.write_methods(): write() time.sleep(demand.interval)
def do_single_test(self, traffic, test): print("Started test " + str(traffic) + " - " + str(test) + " - storage: " + str(self.storage_size)) # handle files file_name = str(traffic) + "_0" + str(test) + ".dem" result_file_name = str(traffic) + "_0" + str(test) + "_result.dem" if test > 9: file_name = str(traffic) + "_" + str(test) + ".dem" result_file_name = str(traffic) + "_" + str(test) + "_result.dem" dem_file = open(self.data_directory + "/" + file_name, "r") demands_lines = dem_file.readlines() dem_file.close() # save solution dem_result_file = open(self.result_directory + "/" + result_file_name, "a+") dem_result_file.write( "Demand;Time in Storage;Start Processing Iteration;Chosen Path;Chosen Core;Chosen Slice\n" ) # read all demands demands = [] for demand_line in demands_lines: demand_data = list(map(int, findall('[0-9]+', demand_line))) if len(demand_data) == 5: new_demand = Demand(demand_data[0], demand_data[1], demand_data[2], demand_data[3], demand_data[4]) new_demand.add_paths(self.P_i_j[new_demand.s][new_demand.t], self.candidate_paths, self.E_amount) demands.append(new_demand) else: print("There is wrong data in file " + file_name + ". Demand line: " + demand_line) # prepare variables r_d, b_d, x_d_p, c_d_k_s, delta_e_d_p, y_n_e_k_s, B_v print("\tPreparing variables") demands_amount = len(demands) x_d_p = numpy.zeros((demands_amount, self.candidate_paths), dtype=int) c_d_k_s = numpy.zeros((demands_amount, self.K, self.S), dtype=int) delta_e_d_p = numpy.zeros( (self.E_amount, demands_amount, self.candidate_paths), dtype=int) B_v = numpy.full((self.V_amount), self.storage_size, dtype=int) y_n_e_k_s = numpy.zeros( (self.iterations_amount, self.E_amount, self.K, self.S), dtype=int) all_gbps = 0 rejected_demands_counter = 0 rejected_demands_bitrate = 0 served_in_iteration_counter = [ 0 for n in range(self.iterations_amount) ] served_in_iteration_bitrate = [ 0 for n in range(self.iterations_amount) ] for d in demands: all_gbps += d.h print("\tCalculating delta_e_d_p") for e in self.E: for d_index in range(demands_amount): d = demands[d_index] for p_index in range(d.P_d_amount): p = d.P_d[p_index] if e in p.edges: delta_e_d_p[e][d_index][p_index] = 1 np_delta_e_d_p = numpy.array(delta_e_d_p) print("\tStart iterations") # do iterations iteration_demands_indices = set() stored_demands_indices = set() start_demand_index = 0 for n in tqdm(range(self.iterations_amount)): ####################################################################### # method - equation 9 - calculate D_e_k_s # print("\n\t\tEquation 9/21") ####################################################################### # there are 9 conditions to check iteration_demands_indices = set() for d_index in range(start_demand_index, demands_amount): # stop if future demands d = demands[d_index] if d.a > n: break start_demand_index += 1 iteration_demands_indices.add(d_index) iteration_demands_indices = iteration_demands_indices.union( stored_demands_indices) iteration_demands_indices_amount = len(iteration_demands_indices) if iteration_demands_indices_amount == 0: continue D_e_k_s = [[[[ False for d in range(iteration_demands_indices_amount) ] for s in range(self.S)] for k in range(self.K)] for e in self.E] iteration_demands_indices_copy = numpy.array( list(iteration_demands_indices)) for e in self.E: if not numpy.any( np_delta_e_d_p[e, list(iteration_demands_indices), :]): continue for k in range(self.K): for s in range(self.S): # if y_n_e_k_s = 1, then D_e_k_s is empty if y_n_e_k_s[n][e][k][s] == 1: D_e_k_s[-1][-1][-1] = [ False for i in range(len(iteration_demands_indices)) ] else: d_index_in_iteration_demands = 0 for d_index in iteration_demands_indices: is_chosen = False d = demands[d_index] # calculate f_e_h_d # (assumption, that for this edge we take min f_e_h_d value of all paths) f_e_h_d = d.slices_on_edge[e] # check y_n_e_k_(s-1) = 0 (8-th condition) if (s > 0 and y_n_e_k_s[n][e][k][s - 1] == 0) or (s == 0): # check: s + f_e_h_d < |S| (6-th condition) if s + f_e_h_d < self.S: # check: y_n_e_k_(s+1) = 0 (9-th condition) if (s + f_e_h_d < self.S - 1 and y_n_e_k_s[n][e][k][s + f_e_h_d] == 0) \ or s + f_e_h_d == self.S - 1: y_n_e_k_s_sum = 0 for s_prim in range( s, s + f_e_h_d): y_n_e_k_s_sum += y_n_e_k_s[n][ e][k][s_prim] # check: sum of y_n_e_k_s (7-th condition) if y_n_e_k_s_sum == 0: is_chosen = True if is_chosen: D_e_k_s[e][k][s][ d_index_in_iteration_demands] = True d_index_in_iteration_demands += 1 # print("\t\tDONE Equation 9/21") # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # repeating equalations 10-17 # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% np_D_e_k_s = numpy.array(D_e_k_s) it_is_possible_to_choose_demand = True while it_is_possible_to_choose_demand and len( iteration_demands_indices) > 0: D_e_k_s_prim = [[[[] for i in range(self.S)] for j in range(self.K)] for k in self.E] ####################################################################### # method - equation 10 - calculate c_d_prim # print("\t\tEquation 10/21") ####################################################################### c_d_prim = [[] for i in range(demands_amount)] for d_index in iteration_demands_indices: d = demands[d_index] index_in_iteration_demands = list( iteration_demands_indices_copy).index(d_index) for p_index in range(d.P_d_amount): p = d.P_d[p_index] for k in range(self.K): for s in range(self.S): if all(np_D_e_k_s[p.edges, k, s, index_in_iteration_demands]): c_d_prim[d_index].append([p_index, k, s]) # print("\t\tDONE Equation 10/21") ####################################################################### # method - equation 11 - calculate D_e_k_s_prim # print("\t\tEquations 11/21") ####################################################################### for d_index in iteration_demands_indices: d = demands[d_index] for [p_index, k, s] in c_d_prim[d_index]: p = d.P_d[p_index] for e in p.edges: if not (d_index in D_e_k_s_prim[e][k][s]): D_e_k_s_prim[e][k][s].append(d_index) ####################################################################### # method - equation 12 - choose min D_e_k_s_prim # method - equation 13 - choose demand with shortest delay # print("\t\tEquations 12-13/21") ####################################################################### founded_min_D_e_k_s_prim = False D_e_k_s_prim_min_e = -1 D_e_k_s_prim_min_k = -1 D_e_k_s_prim_min_s = -1 min_D_e_k_s_prim = [] chosen_demand = demands[0] chosen_demand_index = -1 for e in self.E: if len(D_e_k_s_prim[e]) == 0: continue for k in range(self.K): for s in range(self.S): if len(D_e_k_s_prim[e][k][s]) == 0: continue # choosing min_D_e_k_s_prim if not founded_min_D_e_k_s_prim: founded_min_D_e_k_s_prim = True D_e_k_s_prim_min_e = e D_e_k_s_prim_min_k = k D_e_k_s_prim_min_s = s min_D_e_k_s_prim = D_e_k_s_prim[e][k][s] chosen_demand_index = min_D_e_k_s_prim[0] chosen_d = demands[chosen_demand_index] # choose demand with shortest delay for another_demand_index in min_D_e_k_s_prim[ 1:]: another_d = demands[another_demand_index] if another_d.l < chosen_d.l: chosen_demand_index = another_demand_index chosen_d = another_d else: if len(D_e_k_s_prim[e][k][s]) < len( min_D_e_k_s_prim): D_e_k_s_prim_min_e = e D_e_k_s_prim_min_k = k D_e_k_s_prim_min_s = s min_D_e_k_s_prim = D_e_k_s_prim[e][k][s] chosen_demand_index = min_D_e_k_s_prim[0] chosen_d = demands[chosen_demand_index] # choose demand with shortest delay for another_demand_index in min_D_e_k_s_prim[ 1:]: another_d = demands[ another_demand_index] if another_d.l < chosen_d.l: chosen_demand_index = another_demand_index chosen_d = another_d elif len(D_e_k_s_prim[e][k][s]) == len( min_D_e_k_s_prim): # choose resource with demand with shortest delay for another_demand_index in D_e_k_s_prim[ e][k][s]: another_d = demands[ another_demand_index] if another_d.l < chosen_d.l: chosen_demand_index = another_demand_index chosen_d = another_d D_e_k_s_prim_min_e = e D_e_k_s_prim_min_k = k D_e_k_s_prim_min_s = s min_D_e_k_s_prim = D_e_k_s_prim[ D_e_k_s_prim_min_e][ D_e_k_s_prim_min_k][ D_e_k_s_prim_min_s] chosen_d = demands[chosen_demand_index] # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # break loop, it is impossible to choose demand # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if chosen_demand_index == -1: it_is_possible_to_choose_demand = False break ####################################################################### # method - equation 14 - select possible paths for this demand # print("\t\tEquation 14/21") ####################################################################### possible_paths = [] for [p_index, k, s] in c_d_prim[chosen_demand_index]: if k == D_e_k_s_prim_min_k: if s == D_e_k_s_prim_min_s: if delta_e_d_p[D_e_k_s_prim_min_e][ chosen_demand_index][p_index]: possible_paths.append(p_index) # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # break loop, it is impossible to choose demand # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if len(possible_paths) == 0: it_is_possible_to_choose_demand = False break ####################################################################### # method - equation 15 - select the best path from possibles # print("\t\tEquation 15/21") ####################################################################### chosen_path_index = possible_paths[0] chosen_path = chosen_d.P_d[chosen_path_index] demands_on_chosen_path = set() for e in chosen_path.edges: for d_on_path in D_e_k_s_prim[e][D_e_k_s_prim_min_k][ D_e_k_s_prim_min_s]: demands_on_chosen_path.add(d_on_path) for other_possible_path_index in possible_paths[1:]: other_path = chosen_d.P_d[other_possible_path_index] demands_on_other_path = set() for e in other_path.edges: for d_on_path in D_e_k_s_prim[e][D_e_k_s_prim_min_k][ D_e_k_s_prim_min_s]: demands_on_other_path.add(d_on_path) if len(demands_on_other_path) < len( demands_on_chosen_path): chosen_path_index = other_possible_path_index chosen_path = other_path demands_on_chosen_path = demands_on_other_path ####################################################################### # method - equation 16 - allocate resources # print("\t\tEquation 16/21") ####################################################################### x_d_p[chosen_demand_index][chosen_path_index] = 1 for j in range(chosen_d.l): if n + j >= self.iterations_amount: break for i in range(chosen_d.slices_on_path[chosen_path_index]): if D_e_k_s_prim_min_s + i >= self.S: print("\n\tError: ") print("\t\tAllocating demand: " + str(chosen_demand_index)) print("\t\tPath: " + str(chosen_path_index)) print("\t\tCore: " + str(D_e_k_s_prim_min_k)) print("\t\tSlices from: " + str(D_e_k_s_prim_min_s)) print("\t\tSlices to: " + str( D_e_k_s_prim_min_s + chosen_d.slices_on_path[chosen_path_index])) break y_n_e_k_s[n + j][D_e_k_s_prim_min_e][D_e_k_s_prim_min_k][ D_e_k_s_prim_min_s + i] = 1 chosen_d.q = 1 if n + chosen_d.l < self.iterations_amount: served_in_iteration_counter[n + chosen_d.l] += 1 served_in_iteration_bitrate[n + chosen_d.l] += chosen_d.h ####################################################################### # method - equation 17 - update D_e_k_s # print("\t\tEquation 17/21") ####################################################################### np_D_e_k_s[:, :, :, list(iteration_demands_indices_copy). index(chosen_demand_index)] = False np_D_e_k_s[chosen_path.edges, D_e_k_s_prim_min_k, D_e_k_s_prim_min_s, :] = False iteration_demands_indices.remove(chosen_demand_index) if chosen_demand_index in stored_demands_indices: stored_demands_indices.remove(chosen_demand_index) # print("\n Chosen demand: " + str(chosen_demand_index)) # print("\t Chosen e: " + str(D_e_k_s_prim_min_e)) # print("\t Chosen k: " + str(D_e_k_s_prim_min_k)) # print("\t Chosen s: " + str(D_e_k_s_prim_min_s)) # print("\t Chosen path: " + str(chosen_path_index)) # save solution # dem_result_file.write(str(chosen_demand_index) + ";" + str(chosen_d.b) + ";" + str(n) + ";" + str(chosen_path_index) + ";" + str(D_e_k_s_prim_min_k) + ";" + str(D_e_k_s_prim_min_s) + ";\n") ####################################################################### # method - equation 18 - select demands that can be stored # print("\t\tEquation 18/21") ####################################################################### D_prim_prim = iteration_demands_indices ####################################################################### # method - equation 19 - select demands that can be stored on source node # print("\t\tEquation 19/21") ####################################################################### D_prim_prim_v = [[] for i in self.V] for d_index in D_prim_prim: d = demands[d_index] D_prim_prim_v[d.s].append(d_index) ####################################################################### # method - equation 20 - reject demands # print("\t\tEquation 20/21") ####################################################################### stored_demands_indices = set() for v_index in self.V: demands_sorted_by_l = sorted(D_prim_prim_v[v_index], key=lambda x: demands[x].l) stored_demands_indices = demands_sorted_by_l[:self. storage_size] for stored_demand in demands_sorted_by_l[:self.storage_size]: demands[stored_demand].b += 1 for rejected_demand in demands_sorted_by_l[self.storage_size:]: rejected_demands_counter += 1 rejected_demands_bitrate += demands[rejected_demand].h demands[rejected_demand].r = 1 ####################################################################### # method - equation 21 - set demands as completed # print("\t\tEquation 21/21") ####################################################################### if n % 10 == 0: print( "\nTraffic;\tTest;\tStorage;\tAll bitrate;\tServed bitrate;\tRejected bitrate;\tAll demands;\tServed demands;\tRejected demands;\n" ) print("Tr:\t" + str(traffic) + ";\tTe:\t" + str(test) + ";\tSt:\t" + str(self.storage_size) + ";\tAG: " + str(all_gbps) + ";\tSG:\t" + str(sum(served_in_iteration_bitrate[:n])) + ";\tRG:\t" + str(rejected_demands_bitrate) + ";\tAD: " + str(demands_amount) + ";\tSD:\t" + str(sum(served_in_iteration_counter[:n])) + ";\tRD:\t" + str(rejected_demands_counter) + ";\n\n") ####################################################################### # end of test - saving results # print("\t\tSAVINGS RESULTS") ####################################################################### dem_result_file.close() results_file = open( self.result_directory + "/summarized_result_" + str(traffic) + "_" + str(test) + "_" + str(self.storage_size) + ".txt", "a+") results_file.write( str(traffic) + ";" + str(test) + ";" + str(self.storage_size) + ";;" + str(all_gbps) + ";" + str(sum(served_in_iteration_bitrate)) + ";" + str(rejected_demands_bitrate) + ";" + str(demands_amount) + ";" + str(sum(served_in_iteration_counter)) + ";" + str(rejected_demands_counter) + ";\n") results_file.close()