Best Python code snippet using prospector_python
Problem.py
Source:Problem.py
1import csv2import os3import pandas as pd4import numpy as np5from Display import Display6# Function that can create random instances7def gen_instance(seed, num_s, num_d, num_c, num_p, T):8 np.random.seed(seed)9 n = num_s + num_d + num_c10 s_coordinates = (1 / 10) * np.random.randint(0, 10 * n, (num_s, 2))11 d_coordinates = (1 / 10) * np.random.randint(2.5 * n, 7.5 * n, (num_d, 2))12 c_coordinates = (1 / 10) * np.random.randint(0, 10 * n, (num_c, 2))13 # Sheet 1 - Suppliers14 supplier_data = pd.DataFrame(index=['S' + str(i + 1) for i in range(num_s)],15 columns=['LocationX', 'LocationY'])16 supplier_data.index.name = 'SupplierID'17 for i in range(num_s):18 supplier_data.loc['S' + str(i + 1), :] = [s_coordinates[i][0], s_coordinates[i][1]]19 print(supplier_data)20 # Sheet 2 - Depots21 depot_data = pd.DataFrame(index=['D' + str(i + 1) for i in range(num_d)],22 columns=['LocationX', 'LocationY', 'Capacity', 'Holding Cost'])23 depot_data.index.name = 'DepotID'24 for i in range(num_d):25 capacity = round(7 + 20 * np.random.random(), 2)26 holding_cost = round(0.3 + 0.3 * np.random.random(), 2)27 depot_data.loc['D' + str(i + 1), :] = [d_coordinates[i][0], d_coordinates[i][1],28 capacity, holding_cost]29 print(depot_data)30 # Sheet 3 - Customers31 customer_data = pd.DataFrame(index=['C' + str(i + 1) for i in range(num_c)],32 columns=['LocationX', 'LocationY'])33 customer_data.index.name = 'CustomerID'34 for i in range(num_c):35 customer_data.loc['C' + str(i + 1), :] = [c_coordinates[i][0], c_coordinates[i][1]]36 print(customer_data)37 # Sheet 4 - Products38 product_data = pd.DataFrame(index=['P' + str(i + 1) for i in range(num_p)],39 columns=['Size'])40 product_data.index.name = 'ProductID'41 for i in range(num_p):42 product_data.loc['P' + str(i + 1), :] = round(0.2 + 0.8 * np.random.random(), 2)43 print(product_data)44 # Sheet 5 - Links45 origins = ['S' + str(i + 1) for i in range(num_s)] + ['D' + str(i + 1) for i in range(num_d)]46 destinations = ['D' + str(i + 1) for i in range(num_d)] + ['C' + str(i + 1) for i in range(num_c)]47 links = [(i, j) for i in origins for j in destinations if i != j]48 link_data = pd.DataFrame(index=pd.MultiIndex.from_tuples(links),49 columns=['Opening Cost', 'Capacity Cost', 'Duration'])50 link_data.index.names = ['Origin', 'Destination']51 # Determine all distances52 locations = pd.concat([supplier_data.iloc[:, :3].rename(columns={'SupplierID': 'Location'}),53 depot_data.iloc[:, :3].rename(columns={'DepotID': 'Location'}),54 customer_data.iloc[:, :3].rename(columns={'CustomerID': 'Location'})])55 distance = {a: np.hypot(locations.loc[a[0]]['LocationX'] - locations.loc[a[1]]['LocationX'],56 locations.loc[a[0]]['LocationY'] - locations.loc[a[1]]['LocationY']) for a in links}57 bins = [np.quantile(list(distance.values()), q) for q in [0.25, 0.5, 0.75]]58 durations = np.digitize(list(distance.values()), bins)59 link_index = 060 for i in origins:61 for j in destinations:62 if i != j:63 opening_cost = round(50 + 100 * np.random.random(), 2)64 capacity_cost = round(5 + 10 * np.random.random(), 2)65 link_data.loc[i, j] = [opening_cost, capacity_cost, durations[link_index] + 1]66 link_index += 167 print(link_data)68 # Sheet 6 - Demand69 demand_data = pd.DataFrame(index=pd.MultiIndex.from_product([['C' + str(i + 1) for i in range(num_c)],70 ['P' + str(j + 1) for j in range(num_p)],71 ['T' + str(t) for t in range(5, T + 1)]], ),72 columns=['Amount'])73 demand_data.index.names = ['Customer', 'Product', 'Time']74 for i in range(1, num_c + 1):75 for j in range(1, num_p + 1):76 for t in range(5, T + 1):77 if np.random.random() > 0.7:78 demand_data.loc['C' + str(i), 'P' + str(j), 'T' + str(t)] = round(18 * np.random.random(), 2)79 else:80 demand_data.loc['C' + str(i), 'P' + str(j), 'T' + str(t)] = 081 print(demand_data)82 # Sheet 7 - Backlogs83 backlog_data = pd.DataFrame(index=pd.MultiIndex.from_product([['C' + str(i + 1) for i in range(num_c)],84 ['P' + str(j + 1) for j in range(num_p)]]),85 columns=['Amount'])86 backlog_data.index.names = ['Customer', 'Product']87 for i in range(num_c):88 for j in range(num_p):89 backlog_data.loc['C' + str(i + 1), 'P' + str(j + 1)] = round(7 + 10 * np.random.random(), 2)90 print(backlog_data)91 # Sheet 8 - Production92 production_data = pd.DataFrame(index=pd.MultiIndex.from_product([['S' + str(i + 1) for i in range(num_s)],93 ['P' + str(j + 1) for j in range(num_p)]]),94 columns=['Minimum', 'Maximum'])95 production_data.index.names = ['Supplier', 'Product']96 for i in range(num_s):97 for j in range(num_p):98 if np.random.random() <= 0.8:99 min_production = round(7 + 10 * np.random.random(), 2)100 max_production = round(min_production + 5 + 5 * np.random.random(), 2)101 else:102 min_production = 0103 max_production = 0104 production_data.loc['S' + str(i + 1), 'P' + str(j + 1)] = [min_production, max_production]105 print(production_data)106 # Sheet 9 - Parameters107 parameter_data = pd.DataFrame(index=['Truck Size', 'Start Time Horizon', 'End Time Horizon'],108 columns=['Value'])109 parameter_data.index.name = 'Parameter'110 parameter_data.loc['Truck Size', :] = round(1 + 2 * np.random.random(), 2)111 parameter_data.loc['Start Time Horizon', :] = 'T1'112 parameter_data.loc['End Time Horizon', :] = 'T' + str(T)113 print(parameter_data)114 with pd.ExcelWriter('Instances/' + str(seed) + '.xlsx') as writer:115 supplier_data.to_excel(writer, sheet_name='Suppliers', merge_cells=False)116 depot_data.to_excel(writer, sheet_name='Depots', merge_cells=False)117 customer_data.to_excel(writer, sheet_name='Customers', merge_cells=False)118 product_data.to_excel(writer, sheet_name='Products', merge_cells=False)119 link_data.to_excel(writer, sheet_name='Links', merge_cells=False)120 demand_data.to_excel(writer, sheet_name='Demand', merge_cells=False)121 backlog_data.to_excel(writer, sheet_name='Backlog Penalty', merge_cells=False)122 production_data.to_excel(writer, sheet_name='Production', merge_cells=False)123 parameter_data.to_excel(writer, sheet_name='Parameters', merge_cells=False)124class Problem:125 def __init__(self, instance_name, random=False, seed=None, extra_time_periods=False):126 # Retrieve instance file from Instances directory127 self.instance_name = instance_name128 self.random = random129 if seed:130 np.random.seed(seed)131 cwd = os.getcwd()132 filename = os.path.join(cwd, 'Instances/' + instance_name + '.xlsx')133 data = pd.read_excel(filename, sheet_name=None, engine='openpyxl')134 # Data extraction135 # --------------------------------------------------------------------------------------136 supplier_data = data['Suppliers']137 depot_data = data['Depots']138 customer_data = data['Customers']139 product_data = data['Products']140 link_data = data['Links']141 demand_data = data['Demand']142 backlog_data = data['Backlog Penalty']143 production_data = data['Production']144 parameter_data = data['Parameters']145 self.truck_size = data['Parameters']['Value'][0]146 # Object- and index sets147 # --------------------------------------------------------------------------------------148 # Object sets149 self.S = supplier_data['SupplierID'].to_list()150 self.D = depot_data['DepotID'].to_list()151 self.C = customer_data['CustomerID'].to_list()152 self.S_and_D = self.S + self.D153 self.D_and_C = self.D + self.C154 self.P = product_data['ProductID'].to_list()155 self.start = int(parameter_data['Value'][1].replace('T', ''))156 self.end = int(parameter_data['Value'][2].replace('T', ''))157 if extra_time_periods:158 self.end = round(self.end * 1.1)159 self.T = [t for t in range(self.start, self.end + 1, 1)]160 self.links = [(link_data['Origin'][i], link_data['Destination'][i]) for i in range(len(link_data))]161 # Index sets162 self.customer_product = [(backlog_data['Customer'][i], backlog_data['Product'][i]) for i in163 range(len(backlog_data))]164 self.supplier_product = [(production_data['Supplier'][i], production_data['Product'][i])165 for i in range(len(production_data))]166 self.demand_set = [(demand_data['Customer'][i], demand_data['Product'][i],167 int(demand_data['Time'][i].replace('T', ''))) for i in range(len(demand_data))]168 self.link_product_time = []169 for a in self.links:170 for p in self.P:171 for t in self.T:172 self.link_product_time.append((a[0], a[1], p, t))173 self.link_time = []174 for a in self.links:175 for t in self.T:176 self.link_time.append((a[0], a[1], t))177 self.supplier_product_time = []178 for s in self.S:179 for p in self.P:180 for t in self.T:181 self.supplier_product_time.append((s, p, t))182 self.depot_time = []183 for d in self.D:184 for t in self.T:185 self.depot_time.append((d, t))186 self.depot_product_time = []187 for d in self.D:188 for p in self.P:189 for t in self.T:190 self.depot_product_time.append((d, p, t))191 self.customer_product_time = []192 for c in self.C:193 for p in self.P:194 for t in self.T:195 self.customer_product_time.append((c, p, t))196 self.dc_product_time = []197 for i in self.D_and_C:198 for p in self.P:199 for t in [0] + self.T:200 self.dc_product_time.append((i, p, t))201 # Parameter/data sets202 # --------------------------------------------------------------------------------------203 self.holding_cost = {self.D[i]: depot_data['Holding Cost'][i] for i in range(len(self.D))}204 self.capacity = {self.D[i]: depot_data['Capacity'][i] for i in range(len(self.D))}205 self.product_volume = {self.P[i]: product_data['Size'][i] for i in range(len(self.P))}206 self.opening_cost = {self.links[i]: link_data['Opening Cost'][i] for i in range(len(link_data))}207 self.capacity_cost = {self.links[i]: link_data['Capacity Cost'][i] for i in range(len(link_data))}208 self.duration = {self.links[i]: link_data['Duration'][i] for i in range(len(link_data))}209 self.locations = pd.concat([supplier_data.iloc[:, :3].rename(columns={'SupplierID': 'Location'}),210 depot_data.iloc[:, :3].rename(columns={'DepotID': 'Location'}),211 customer_data.iloc[:, :3].rename(columns={'CustomerID': 'Location'})])212 self.locations.set_index([self.locations['Location']], inplace=True)213 self.distance = {a: np.hypot(self.locations.loc[a[0]]['LocationX'] - self.locations.loc[a[1]]['LocationX'],214 self.locations.loc[a[0]]['LocationY'] - self.locations.loc[a[1]]['LocationY']) for215 a in216 self.links}217 if not random:218 self.demand = {self.demand_set[i]: demand_data['Amount'][i] for i in range(len(demand_data))}219 self.cum_demand = {(c, p, t): sum(self.demand[c, p, f] for f in range(self.start, t + 1)220 if (c, p, f) in self.demand_set) for (c, p, t) in221 self.customer_product_time}222 else:223 self.demand_mean = {self.demand_set[i]: demand_data['Expected Amount'][i] for i in range(len(demand_data))}224 self.demand_dev = {self.demand_set[i]: demand_data['Standard Deviation'][i] for i in225 range(len(demand_data))}226 self.backlog_pen = {self.customer_product[i]: backlog_data['Amount'][i] for i in227 range(len(backlog_data))}228 self.min_prod = {(s, p): 0 for s in self.S for p in self.P}229 self.max_prod = {(s, p): 0 for s in self.S for p in self.P}230 for i in range(len(production_data)):231 self.min_prod[self.supplier_product[i]] = production_data['Minimum'][i]232 self.max_prod[self.supplier_product[i]] = production_data['Maximum'][i]233 if random:234 self.supplier_availability = {self.supplier_product[i]: production_data['Availability rate'][i]235 for i in range(len(self.supplier_product))}236 self.solution = {}237 self.objective = np.inf238 if random:239 self.scenarios = []240 # Function that updates this problem object's solution based on a solution file241 def read_solution(self, instance_name):242 self.solution = {'x': {(i, j, p, str(t)): 0 for (i, j, p, t) in self.link_product_time},243 'l': {(i, j): 0 for (i, j) in self.links},244 'v': {(i, j): 0 for (i, j) in self.links},245 'k': {(i, j, str(t)): 0 for (i, j, t) in self.link_time},246 'r': {(s, p, str(t)): 0 for (s, p, t) in self.supplier_product_time},247 'I': {(i, p, str(t)): 0 for (i, p, t) in self.dc_product_time}}248 # Read solution249 with open('Solutions/' + instance_name + '.sol', newline='\n') as file:250 reader = csv.reader((line.replace(' ', ' ') for line in file), delimiter=' ')251 header = next(reader) # Skip header252 self.objective = header[-1]253 for var, value in reader:254 name = tuple(var[2:-1].split(','))255 if var[0] not in self.solution.keys():256 self.solution[var[0]] = {}257 self.solution[var[0]][name] = float(value)258 def generate_scenarios(self, N):259 self.scenarios = []260 for i in range(N):261 availability = {(s, p, t): np.random.binomial(n=1, p=self.supplier_availability[s, p])262 for s, p, t in self.supplier_product_time if (s, p) in self.supplier_product}263 demand = {(c, p, t): np.random.normal(loc=self.demand_mean[c, p, t], scale=self.demand_dev[c, p, t])264 for c, p, t in self.demand_set}265 cum_demand = {(c, p, t): sum([demand[c, p, f] for f in range(t) if (c, p, f) in self.demand_set])266 for c, p, t in self.customer_product_time}267 self.scenarios.append({268 'availability': availability,269 'demand': demand,270 'cum_demand': cum_demand271 })272 def compute_objective(self):273 # Opening + capacity costs274 tot_opening_costs = 0275 tot_capacity_costs = 0276 for link in self.links:277 if self.solution['v'][link] > 0:278 extra_opening_cost = self.opening_cost[link]279 tot_opening_costs += extra_opening_cost280 extra_capacity_cost = self.capacity_cost[link] * self.solution['v'][link]281 tot_capacity_costs += extra_capacity_cost282 if not self.random:283 # Distance costs284 tot_distance_costs = 0285 for link in self.links:286 if self.solution['v'][link] > 0:287 total_trucks_sent = sum([self.solution['k'][link + (str(t),)] for t in self.T])288 extra_distance_cost = total_trucks_sent * self.distance[link]289 tot_distance_costs += extra_distance_cost290 # Holding costs291 tot_holding_costs = 0292 for d in self.D:293 for p in self.P:294 extra_holding_cost = self.holding_cost[d] * sum([self.solution['I'][d, p, str(t)]295 * self.product_volume[p] for t in self.T])296 tot_holding_costs += extra_holding_cost297 # Backlog costs298 tot_backlog_costs = 0299 for c, p, t in self.customer_product_time:300 extra_backlog = self.backlog_pen[c, p] * (301 self.solution['I'][c, p, str(t)] - self.cum_demand[c, p, t]) ** 2302 tot_backlog_costs += extra_backlog303 return tot_opening_costs + tot_capacity_costs + tot_distance_costs + tot_holding_costs + tot_backlog_costs304 else:305 tot_distance_costs = 0306 tot_holding_costs = 0307 tot_backlog_costs = 0308 N = len(self.scenarios)309 for theta in range(N):310 # Distance costs311 for (i, j) in self.links:312 if self.solution['v'][i, j] > 0:313 total_trucks_sent = sum([self.solution['k'][i, j, str(t), str(theta)] for t in self.T])314 extra_distance_cost = total_trucks_sent * self.distance[i, j]315 tot_distance_costs += extra_distance_cost316 # Holding costs317 for d in self.D:318 for p in self.P:319 extra_holding_cost = self.holding_cost[d] * sum([self.solution['I'][d, p, str(t), str(theta)]320 * self.product_volume[p] for t in self.T])321 tot_holding_costs += extra_holding_cost322 # Backlog costs323 for c, p, t in self.customer_product_time:324 extra_backlog = self.backlog_pen[c, p] * abs((self.solution['I'][c, p, str(t), str(theta)]325 - self.scenarios[theta]['cum_demand'][c, p, t]))326 tot_backlog_costs += extra_backlog327 tot_objective = tot_opening_costs + tot_capacity_costs + \328 (1 / N) * (tot_distance_costs + tot_holding_costs + tot_backlog_costs)329 return tot_objective330 # Log the amount of trucks sent over each link at each point in time331 def log_k(self):332 k = {}333 for (i, j) in self.links:334 if self.solution['l'][i, j] == 1:335 k[i, j] = [round(self.solution['k'][i, j, str(t)]) for t in self.T]336 print()337 print('Amount of trucks sent over each link at each point in time:')338 print('-' * 70)339 for link, trucks in k.items():340 print(link, trucks)341 # Function that outputs the buildup of different cost types342 def log_objective(self, summary_only=False):343 print()344 print('Objective overview:')345 print('-' * 70)346 # Opening costs347 tot_opening_costs = 0348 for link in self.links:349 if link in self.solution['l'].keys():350 if self.solution['l'][link] == 1:351 extra_opening_cost = self.opening_cost[link]352 if not summary_only:353 print(link, '| Cost:', extra_opening_cost)354 tot_opening_costs += extra_opening_cost355 if not summary_only:356 print('Total opening costs:', round(tot_opening_costs, 2))357 print('-' * 70)358 # Capacity costs359 tot_capacity_costs = 0360 for link in self.links:361 if link in self.solution['v'].keys():362 if self.solution['v'][link] > 0:363 extra_capacity_cost = self.capacity_cost[link] * self.solution['v'][link]364 if not summary_only:365 print(link, '| Amount: ', round(self.solution['v'][link], 2), '| Cost per:',366 self.capacity_cost[link], '| Total cost:', round(extra_capacity_cost, 2))367 tot_capacity_costs += extra_capacity_cost368 if not summary_only:369 print('Total capacity costs:', round(tot_capacity_costs, 2))370 print('-' * 70)371 if not self.random:372 # Distance costs373 tot_distance_costs = 0374 for link in self.links:375 if link in self.solution['v'].keys():376 if self.solution['v'][link] > 0:377 total_trucks_sent = sum([self.solution['k'][link + (str(t),)] for t in self.T])378 extra_distance_cost = total_trucks_sent * self.distance[link]379 if not summary_only:380 print(link, '| Total trucks sent on link: ', round(total_trucks_sent),381 '| Cost per:', round(self.distance[link], 2), '| Total cost:',382 round(extra_distance_cost, 2))383 tot_distance_costs += extra_distance_cost384 if not summary_only:385 print('Total distance costs:', round(tot_distance_costs, 2))386 print('-' * 70)387 # Holding costs388 tot_holding_costs = 0389 for d in self.D:390 if not summary_only:391 print(d, '| Holding costs:', self.holding_cost[d], 'Capacity:', self.capacity[d])392 for p in self.P:393 if not summary_only:394 print(d, p, '| Inventory:', [round(self.solution['I'][d, p, str(t)] * self.product_volume[p], 2)395 for t in self.T])396 extra_holding_cost = self.holding_cost[d] * sum([self.solution['I'][d, p, str(t)]397 * self.product_volume[p] for t in self.T])398 if not summary_only:399 print(d, p, '| Total inventory:', round(sum([round(self.solution['I'][d, p, str(t)]400 * self.product_volume[p], 2)401 for t in self.T]), 2),402 '| Total cost:', round(extra_holding_cost, 2))403 tot_holding_costs += extra_holding_cost404 if not summary_only:405 print('Total holding costs:', round(tot_holding_costs, 2))406 print('-' * 70)407 # Backlog costs408 tot_backlog_costs = 0409 cum_demand = self.cum_demand if not self.random else self.scenarios[0]['cum_demand']410 for c in self.C:411 customer_backlog = 0412 if not summary_only:413 print(c, '|')414 print('-' * 70)415 for p in self.P:416 if not summary_only:417 print(c, p, '|', [round(cum_demand[c, p, t], 2) for t in self.T],418 '- Cumulative demand over time')419 print(c, p, '|', [round(self.solution['I'][c, p, str(t)], 2) for t in self.T],420 '- Total delivered over time')421 product_backlog = 0422 for t in self.T:423 product_backlog += self.backlog_pen[c, p] * ((self.solution['I'][c, p, str(t)]424 - cum_demand[c, p, t]) ** 2)425 customer_backlog += product_backlog426 if not summary_only:427 print(c, p, '| Product backlog costs:', product_backlog)428 print('-' * 70)429 if not summary_only:430 print(c, '| Customer backlog costs:', round(customer_backlog, 2))431 print('-' * 70)432 for c, p, t in self.customer_product_time:433 extra_backlog = self.backlog_pen[c, p] * (self.solution['I'][c, p, str(t)] - cum_demand[c, p, t]) ** 2434 tot_backlog_costs += extra_backlog435 if not summary_only:436 print('Total backlog costs:', round(tot_backlog_costs, 2))437 print('-' * 70)438 tot_objective = tot_opening_costs + tot_capacity_costs + tot_distance_costs \439 + tot_holding_costs + tot_backlog_costs440 else:441 tot_distance_costs = 0442 tot_holding_costs = 0443 tot_backlog_costs = 0444 N = len(self.scenarios)445 for theta in range(N):446 if not summary_only:447 print('SCENARIO', theta)448 print('-' * 70)449 # Distance costs450 tot_distance_costs = 0451 for (i, j) in self.links:452 if (i, j) in self.solution['v'].keys():453 if self.solution['v'][i, j] > 0:454 total_trucks_sent = sum([self.solution['k'][i, j, str(t), str(theta)] for t in self.T])455 extra_distance_cost = total_trucks_sent * self.distance[i, j]456 if not summary_only:457 print(i, j, '| Total trucks sent on link: ', round(total_trucks_sent),458 '| Cost per:', round(self.distance[i, j], 2), '| Total cost:',459 round(extra_distance_cost, 2))460 tot_distance_costs += extra_distance_cost / N461 if not summary_only:462 print('Total distance costs:', round(tot_distance_costs, 2))463 print('-' * 70)464 # Holding costs465 for d in self.D:466 if not summary_only:467 print(d, '| Holding costs:', self.holding_cost[d], 'Capacity:', self.capacity[d])468 for p in self.P:469 if not summary_only:470 print(d, p, '| Inventory:',471 [round(self.solution['I'][d, p, str(t), str(theta)] * self.product_volume[p], 2)472 for t in self.T])473 extra_holding_cost = self.holding_cost[d] * sum([self.solution['I'][d, p, str(t), str(theta)]474 * self.product_volume[p] for t in self.T])475 if not summary_only:476 print(d, p, '| Total inventory:',477 round(sum([round(self.solution['I'][d, p, str(t), str(theta)]478 * self.product_volume[p], 2)479 for t in self.T]), 2),480 '| Total cost:', round(extra_holding_cost, 2))481 tot_holding_costs += extra_holding_cost / N482 if not summary_only:483 print('Total holding costs:', round(tot_holding_costs, 2))484 print('-' * 70)485 # Backlog costs486 cum_demand = self.scenarios[theta]['cum_demand']487 for c in self.C:488 customer_backlog = 0489 if not summary_only:490 print(c, '|')491 print('-' * 70)492 for p in self.P:493 if not summary_only:494 print(c, p, '|', [round(cum_demand[c, p, t], 2) for t in self.T],495 '- Cumulative demand over time')496 print(c, p, '|', [round(self.solution['I'][c, p, str(t), str(theta)], 2) for t in self.T],497 '- Total delivered over time')498 product_backlog = 0499 for t in self.T:500 product_backlog += self.backlog_pen[c, p] * abs(self.solution['I'][c, p, str(t), str(theta)]501 - cum_demand[c, p, t])502 customer_backlog += product_backlog503 if not summary_only:504 print(c, p, '| Product backlog costs:', product_backlog)505 print('-' * 70)506 if not summary_only:507 print(c, '| Customer backlog costs:', round(customer_backlog, 2))508 print('-' * 70)509 for c, p, t in self.customer_product_time:510 extra_backlog = self.backlog_pen[c, p] * abs(511 self.solution['I'][c, p, str(t), str(theta)] - cum_demand[c, p, t])512 tot_backlog_costs += extra_backlog / N513 if not summary_only:514 print('Total backlog costs:', round(tot_backlog_costs, 2))515 print('-' * 70)516 tot_objective = tot_opening_costs + tot_capacity_costs + tot_distance_costs + tot_holding_costs + tot_backlog_costs517 print('Total opening costs |', round(tot_opening_costs, 2))518 print('Total capacity costs |', round(tot_capacity_costs, 2))519 print('Total distance costs |', round(tot_distance_costs, 2))520 print('Total holding costs |', round(tot_holding_costs, 2))521 print('Total backlog costs |', round(tot_backlog_costs, 2))522 print('-' * 70)523 print('Total costs |', round(tot_objective, 2))524 print('-' * 70)525 return {526 'backlog': tot_backlog_costs,527 'total': tot_objective528 }529 def log_production(self):530 if not self.random:531 for s in self.S:532 print(s, '|')533 print('-' * 70)534 for p in self.P:535 production = [round(sum(self.solution['x'][s, j, p, str(t)] for j in self.D_and_C), 2) for t in536 self.T]537 print(p, '|', production)538 print('-' * 70)539 else:540 for theta in range(len(self.scenarios)):541 for s in self.S:542 print(s, '|')543 print('-' * 70)544 for p in self.P:545 production = [round(sum(self.solution['x'][s, j, p, str(t), str(theta)]546 for j in self.D_and_C if (s, j, p, str(t), str(theta))547 in self.solution['x'].keys()), 2) for t in self.T]548 print(p, '|', production)549 print('-' * 70)550 def verify_constraints(self):551 # 1 - Link opening constraint552 for link in self.links:553 assert self.solution['l'][link] * 10000 >= self.solution['v'][link], 'Constraint 1 violation'554 # 2 - Link capacity constraint555 for link in self.links:556 for t in self.T:557 t = str(t)558 assert round(self.solution['k'][link[0], link[1], t]) <= round(self.solution['v'][link])559 # 3 - Required trucks constraint560 for i, j in self.links:561 for t in self.T:562 t = str(t)563 volume = sum([self.product_volume[p] * self.solution['x'][i, j, p, t] for p in self.P])564 assert self.solution['k'][i, j, t] >= round(volume / self.truck_size)565 # 4 - Min production constraint566 for s, p, t in self.supplier_product_time:567 t = str(t)568 production = sum([self.solution['x'][s, j, p, t] for j in self.D_and_C])569 assert round(production, 2) >= self.min_prod[s, p] * self.solution['r'][s, p, t]570 # 5 - Max production constraint571 for s, p, t in self.supplier_product_time:572 t = str(t)573 production = sum([self.solution['x'][s, j, p, t] for j in self.D_and_C])574 assert round(production, 2) <= self.max_prod[s, p] * self.solution['r'][s, p, t]575 # 6 - Depot outflow constraint576 for d, p, t in self.depot_product_time:577 outflow = sum([self.solution['x'][d, j, p, str(t)] for j in self.D_and_C if (d, j) in self.links])578 inflow = sum([self.solution['x'][j, d, p, str(t - self.duration[j, d])] for j in self.S_and_D579 if (j, d) in self.links and t - self.duration[j, d] >= self.start])580 assert round(outflow, 2) <= round(self.solution['I'][d, p, str(t - 1)] + inflow, 2) + 0.01581 # 7 - Depot capacity constraint582 for d in self.D:583 for t in self.T:584 t = str(t)585 volume = sum([self.product_volume[p] * self.solution['I'][d, p, t] for p in self.P])586 assert volume <= self.capacity[d]587 # 8 - Flow constraints588 for i, p, t in self.dc_product_time:589 if t > 0:590 outflow = sum([self.solution['x'][i, j, p, str(t)] for j in self.D_and_C if (i, j) in self.links])591 inflow = sum([self.solution['x'][j, i, p, str(t - self.duration[j, i])] for j in self.S_and_D592 if (j, i) in self.links and t - self.duration[j, i] >= self.start])593 assert round(self.solution['I'][i, p, str(t)], 4) - round(self.solution['I'][i, p, str(t - 1)] + inflow594 - outflow, 4) <= 0.0001595 # 9 - Inventories start at 0596 for i in self.D_and_C:597 for p in self.P:598 assert self.solution['I'][i, p, '0'] == 0599 # 10 - Total inventories must match cumulative demand600 for c in self.C:601 for p in self.P:602 assert round(self.solution['I'][c, p, str(self.end)], 5) == round(self.cum_demand[c, p, self.end], 5)603 print('Constraints succesfully verified.')604 return605 # Call display on this problem's solution showing only opened links and their capacities606 def display(self, integer=False):607 disp = Display(self)608 disp.draw(0, {'show_capacities': True, 'show_trucks': False, 'show_transport': False, 'show_inventory': False,...
html.py
Source:html.py
1import re2from .basic import BasicReport3class HtmlReport(BasicReport):4 templates = {5 'MAIN': '''6<!doctype html>7<html lang="en">8 <head>9 <meta charset="utf-8">10 <title>Python Environment Report</title>11 <meta name="generator" content="{analyzer}">12 <meta name="viewport" content="width=device-width, initial-scale=1">13 </head>14 <body>15 <h1>Python Environment Report</h1>16 <h2>Environment</h2>17 <ul>18 <li>Python: {python_version}</li>19 <li>Runtime: {runtime} {runtime_version}</li>20 <li>Platform: {platform}</li>21 <li>Pip: {pip_version}</li>22 <li>Location: {base_directory}</li>23 </ul>24 <h2>Summary</h2>25 <ul>26 <li>Total: {packages|len}</li>27 <li><span title="Installed packages that have newer versions available.">Outdated:</span> {?outdated}{outdated|len}28 {?outdated}29 <ul>30 {#outdated}31 <li>{?summary_only}{.}{:else}<a href="#{.}">{.}</a>{/summary_only}</li>32 {/outdated}33 </ul>34 {/outdated}{:else}0{/outdated}35 </li>36 <li><span title="Installed packages that have known vulnerabilities.">Vulnerable:</span> {?vulnerable}{vulnerable|len}37 {?vulnerable}38 <ul>39 {#vulnerable}40 <li>{?summary_only}{.}{:else}<a href="#{.}">{.}</a>{/summary_only}</li>41 {/vulnerable}42 </ul>43 {/vulnerable}{:else}0{/vulnerable}44 </li>45 <li><span title="Required packages that are not currently installed.">Missing:</span> {?missing}{missing|len}46 {?missing}47 <ul>48 {#missing}49 <li>{.}</li>50 {/missing}51 </ul>52 {/missing}{:else}0{/missing}53 </li>54 <li><span title="Installed packages whose version conflicts with another package's requirements.">Invalid:</span> {?invalid}{invalid|len}55 {?invalid}56 <ul>57 {#invalid}58 <li>{?summary_only}{.}{:else}<a href="#{.}">{.}</a>{/summary_only}</li>59 {/invalid}60 </ul>61 {/invalid}{:else}0{/invalid}62 </li>63 </ul>64 {?summary_only}{:else}65 {?problems_only}66 <h2>Problematic Packages</h2>67 <ul>68 {#problem_packages}{>PACKAGE/}{/problem_packages}69 </ul>70 {:else}71 <h2>Packages</h2>72 <ul>73 {#packages}{>PACKAGE/}{/packages}74 </ul>75 {/problems_only}76 {/summary_only}77 <p>Generated by <code><a href="{envrpt_home_page}">{analyzer}</a></code> on {date_analyzed|date} at {date_analyzed|time}</p>78 </body>79</html>''', # noqa80 'PACKAGE': '''81<li id="{key}"><strong>{?home_page}<a href="{home_page}">{name}</a>{:else}{name}{/home_page}</strong>82<ul>83 {?description}<li>{description}</li>{/description}84 <li>Version: {version}</li>85 <li>License: {?license}{license}{:else}Unknown{/license}</li>86{?issues}87 <li>Issues:88 <ul>89 {#issues}90 <li>{@eq key=type value="OUTDATED"}Package is outdated; <strong>{latest_version}</strong> is available{/eq}{@eq key=type value="REQ_MISSING"}Dependency <strong>{key}</strong> is missing{/eq}{@eq key=type value="REQ_INVALID"}Dependency <strong>{?summary_only}{key}{:else}<a href="#{key}">{key}</a>{/summary_only}</strong> is invalid; require <strong>{requirement}</strong> but <strong>{installed}</strong> is installed{/eq}{@eq key=type value="VULNERABLE"}Package has a known vulnerability: {id}: {description}{/eq}</li>91 {/issues}92 </ul>93 </li>94{/issues}95{?dependencies}96 <li><span title="Other packages that are required by this package.">Dependencies:</span>97 <ul>98 {#dependencies}99 <li>{?installed}<a href="#{key}">{key}</a>{:else}{key}{/installed}{?spec} ({spec}){/spec}</li>100 {/dependencies}101 </ul>102 </li>103{/dependencies}104{?dependents}105 <li><span title="Other packages that depend on this package.">Dependents:</span>106 <ul>107 {#dependents}108 <li><a href="#{key}">{key}</a></li>109 {/dependents}110 </ul>111 </li>112{/dependents}113</ul>114''', # noqa115 }116def create(environment, options):117 rpt = HtmlReport().create(environment, options)...
bgp_route_aggregation.py
Source:bgp_route_aggregation.py
...36 if summary_only is not None:37 self.summary_only = summary_only38 self.prefix = prefix39 @property40 def summary_only(self):41 """Gets the summary_only of this BgpRouteAggregation. # noqa: E50142 Flag to send only summarized route # noqa: E50143 :return: The summary_only of this BgpRouteAggregation. # noqa: E50144 :rtype: bool45 """46 return self._summary_only47 @summary_only.setter48 def summary_only(self, summary_only):49 """Sets the summary_only of this BgpRouteAggregation.50 Flag to send only summarized route # noqa: E50151 :param summary_only: The summary_only of this BgpRouteAggregation. # noqa: E50152 :type: bool53 """54 self._summary_only = summary_only55 @property56 def prefix(self):57 """Gets the prefix of this BgpRouteAggregation. # noqa: E50158 cidr of the aggregate address # noqa: E50159 :return: The prefix of this BgpRouteAggregation. # noqa: E50160 :rtype: str61 """62 return self._prefix...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!