def setUpClass(cls): cls.setWithShifts(True) param = Parameters() param.num_processors = Constants.DEFAULT_PROCESSORS shift_duration = [5, 5, 2, 2] shift_type = [ Constants.ENTREGA, Constants.ENTREGA, Constants.RECOGIDA, Constants.DUAL ] shift_factor = 3600 # hours param.setParameters(shift_duration, shift_type, shift_factor) cls.coreObj = Core(param) cls.coreObj.output_file = open('./TEST_System.txt', "w+") cls.coreObj.parameters.output_file = Constants.OUTPUT_PATH + "TEST_System" cls.coreObj.run() cls.coreObj.output_file.close() with open(Constants.OUTPUT_PATH + 'TEST_System.csv', "r") as read: header = read.readline().split(',') header = [tmp.split('\n')[0] for tmp in header] for i in range(len(header)): cls.cols[header[i]] = i line = read.readline() # [current_time, event_name, event_scheduled, event_time, idle_proc, service_proc, num_idle_proc, buff_len, queue_len, entities_system, shift] # Current_Time,Event_Name,Event_Scheduled,Event-Time,Idle_Processors,Service_Processors,Number_Idle_Processors,Buffer_Length,Queue_Length,Entities_System,Shift while line: row = TestSystemWithShifts.process_line(line) cls.static_big_matrix.append(row) line = read.readline()
def test_updateState_Not_First_Shift(self): param = Parameters() param.num_processors = 2 self.coreObj = Core(param) for mock_processor in self.coreObj.processors: mock_processor.isIdle = MagicMock(return_value=False) mock_event = Event() mock_event.executeEvent = MagicMock() mock_event.eventTime = Constants.SIMULATION_INITIAL_TIME + 1 * 3600 + 1 self.coreObj.updateState(mock_event) mock_event = Event() mock_event.executeEvent = MagicMock() mock_event.eventTime = Constants.SIMULATION_INITIAL_TIME + 5 * 3600 + 1 self.coreObj.updateState(mock_event) self.assertEqual( self.coreObj.currentTime, Constants.SIMULATION_INITIAL_TIME + 5 * 3600 + 1, "The current time should be updated to SIMULATION_INITIAL_TIME + 5*3600 + 1" ) self.assertEqual( self.coreObj.serviceProcessors, (5 * 3600 + 1) * 2, "The service processors time should be (5*3600 + 1) * 2 (2 service processors)" ) self.assertEqual(self.coreObj.idleProcessors, 0, "The idle time should be 0")
def sourceIncrement(self, operationType): param = Parameters() if param.WITH_SHIFTS: if operationType == Constants.ENTREGA: return ceil(random.exponential(1 / self.LAMBDA_Entrega)) elif operationType == Constants.RECOGIDA: return ceil(random.exponential(1 / self.LAMBDA_Recogida)) else: # DUAL return ceil(random.exponential(1 / self.LAMBDA_Dual)) else: return ceil(random.exponential(1 / self.LAMBDA))
def initialization(self): random.seed(0) # se hace getNumTrucks para las tres self.numTrucksEntrega = self.getNumTrucks(Constants.ENTREGA) self.numTrucksRecogida = self.getNumTrucks(Constants.RECOGIDA) self.numTrucksDual = self.getNumTrucks(Constants.DUAL) self.numTrucks = self.getNumTrucks(None) p = Parameters() self.LAMBDA_Entrega = p.getTotalTime( Constants.ENTREGA) / self.numTrucksEntrega self.LAMBDA_Recogida = p.getTotalTime( Constants.RECOGIDA) / self.numTrucksRecogida self.LAMBDA_Dual = p.getTotalTime(Constants.DUAL) / self.numTrucksDual self.LAMBDA = p.getTotalTime(None) / self.numTrucks
def test_run(self): param = Parameters() param.num_processors = 2 self.coreObj = Core(param) self.coreObj.output_file = open('./TEST.txt', "w+") self.coreObj.parameters.output_file = "TEST" self.coreObj.run() self.coreObj.output_file.close() self.assertEquals( self.coreObj.eventsList.qsize(), 0, "The length should be 0 because the simulation ended") obj = self.coreObj.eventsList self.assertIsNotNone("The object is not none", obj) with open('./TEST.stats.csv', "r") as read: self.assertNotEquals(len(read.read()), 0, "The file should not be empty")
def processorIncrement(self, shift): param = Parameters() if param.WITH_SHIFTS: if shift == Constants.ENTREGA: return ceil( random.uniform(Constants.MINIMUM_TIME_ENTREGA, Constants.MAXIMUM_TIME_ENTREGA)) elif shift == Constants.RECOGIDA: return ceil( random.uniform(Constants.MINIMUM_TIME_RECOGIDA, Constants.MAXIMUM_TIME_RECOGIDA)) else: # DUAL return ceil( random.uniform(Constants.MINIMUM_TIME_DUAL, Constants.MAXIMUM_TIME_DUAL)) else: return ceil( random.uniform(Constants.MINIMUM_TIME, Constants.MAXIMUM_TIME))
def __init__(self, parameters=None): if parameters is None: self.parameters = Parameters() else: self.parameters = parameters num_sources = Constants.DEFAULT_SOURCES num_processors = self.parameters.num_processors # Attributes initialization self.processors = [] self.sources = [] self.eventsList = PriorityQueue(0) # maxsize = 0 (infinite) self.previousTime = Constants.SIMULATION_INITIAL_TIME self.currentTime = Constants.SIMULATION_INITIAL_TIME self.idleProcessors = 0 self.serviceProcessors = 0 self.entitiesSystem = 0 self.service_per_shift = [] self.service_per_total = [] self.shift_durations = self.parameters.getParameters()[1] self.shift_next_time = self.shift_durations[0] self.shift_next_index = 1 # Instance creation self.queue = Queue(Constants.SLOTS_BUFFER) self.parking = Queue(Constants.SLOTS_QUEUE) self.random = Random() for _ in range(0, num_processors): self.processors.append(Processor(self)) for _ in range(0, num_sources): self.sources.append(Source(self)) # Dependency injection for source in self.sources: source.addOutput(self.queue) # source -> queue self.queue.addOutput(self.parking) # queue -> parking self.parking.addInput(self.queue) # parking <- queue for processor in self.processors: self.parking.addOutput(processor) # parking -> processor processor.addInput(self.parking) # processor <- parking self.output_file = None self.numberOfIdleProcessors = num_processors
def test_updateState_With_2Idle_Processors(self): param = Parameters() param.num_processors = 2 self.coreObj = Core(param) for mock_processor in self.coreObj.processors: mock_processor.isIdle = MagicMock(return_value=True) mock_event = Event() mock_event.executeEvent = MagicMock() mock_event.eventTime = Constants.SIMULATION_INITIAL_TIME + 123 self.coreObj.updateState(mock_event) self.assertEqual( self.coreObj.currentTime, Constants.SIMULATION_INITIAL_TIME + 123, "The current time should be updated to SIMULATION_INITIAL_TIME + 123" ) self.assertEqual( self.coreObj.idleProcessors, 123 * 2, "The idle time should be 123 * 2 (2 idle processors)") self.assertEqual(self.coreObj.serviceProcessors, 0, "The service processors time should be 0")
def getNumTrucks(self, operationType): param = Parameters() if param.WITH_SHIFTS: if operationType == Constants.ENTREGA: return ceil( random.triangular(Constants.MINIMUM_TRUCKS_ENTREGA, Constants.MEDIAN_TRUCKS_ENTREGA, Constants.MAXIMUM_TRUCKS_ENTREGA)) elif operationType == Constants.RECOGIDA: return ceil( random.triangular(Constants.MINIMUM_TRUCKS_RECOGIDA, Constants.MEDIAN_TRUCKS_RECOGIDA, Constants.MAXIMUM_TRUCKS_RECOGIDA)) else: # DUAL return ceil( random.triangular(Constants.MINIMUM_TRUCKS_DUAL, Constants.MEDIAN_TRUCKS_DUAL, Constants.MAXIMUM_TRUCKS_DUAL)) else: return ceil( random.triangular(Constants.MINIMUM_TRUCKS, Constants.MEDIAN_TRUCKS, Constants.MAXIMUM_TRUCKS))
def setUp(self): self.parametersObj = Parameters() self.parametersObj.WITH_SHIFTS = True rand = Random() rand.initialization()
def many_simulations(t: int): """Run many simulations for different values of densities and display the results Args: t (int): Number of density1 and density2 to test """ densities1 = np.linspace(0.0, 0.6, t) densities2 = np.linspace(0.0, 0.4, t) # Run simulations results = [ [ one_simulation( Parameters( density1=densities1[i1], density2=densities2[i2], nbInitialFires=3, wind=Wind.West, firebreak=False, resistanceTree1=1, resistanceTree2=1.3, transmissibilityFire3=0.3, transmissibilityFire4=0.5, ) ) for i1 in tqdm(range(len(densities1))) ] for i2 in tqdm(range(len(densities2))) ] # Display results print(results) plt.figure(1) for i in range(t): plt.plot( densities1, results[i], label=f"density2 = {densities2[i]}", ) plt.title(f"Final density of trees for different initial values of densities") plt.xlabel("density1") plt.ylabel("final density of all trees") plt.legend() plt.figure(2) difference = [ [ densities1[i1] + densities2[i2] - resultats[i1][i2] for i1 in range(len(densities1)) ] for i2 in range(len(densities2)) ] for i in range(t): plt.plot( densities1, difference[i], label=f"density2 = {densities2[i]}", ) plt.title(f"Difference of density between initial and final values of densities") plt.xlabel("density1") plt.ylabel("loss of density") plt.legend() plt.show()
from src.Scene import Scene from src.Wind import Wind CELL_SIZE = 10 SCREEN_SIZE = (600, 600) # (900,900) (1280,1280) GRID_DIM = tuple(map(lambda x: int(x / CELL_SIZE), SCREEN_SIZE)) REFRESH_TIME = 10000 COLORS = [(255, 255, 255), (26, 174, 70), (7, 70, 22), (194, 46, 28), (107, 30, 30)] parameters = Parameters( density1=0.6, # The sum of densities must be included between 0 and 1 density2=0.3, nbInitialFires=3, wind=Wind.West, # South, West, North, East firebreak=True, resistanceTree1=1, resistanceTree2=1.3, transmissibilityFire3=0.3, transmissibilityFire4=0.5, ) def one_simulation(parameters: Parameters): """Make one entire simulation for one configuration Args: parameters (Parameters): parameters for the simulation Returns: float: final density of all trees
minutes = int((time % 3600) / 60) hourstr = str(hour) minutesstr = str(minutes) if hour < 10: hourstr = '0' + hourstr if minutes < 10: minutesstr = '0' + minutesstr return hourstr + ':' + minutesstr # Main program # load traces df = pd.read_csv(Constants.OUTPUT_PATH + "/trace.csv") ds = pd.read_csv(Constants.OUTPUT_PATH + "/trace.stats.csv") parameters = Parameters() charts = Charts() if (len(df.index) == 0) or (len(ds.index) == 0): raise Exception("The trace file is empty") shifts = True event = df.iloc[0] if event['Shift'] == '-': shifts = False # timeline chart total_time_cargas = 0 total_time_descargas = 0 total_time_duo = 0
def setWithShifts(self, value): param = Parameters() param.WITH_SHIFTS = value self.randObj = Random() self.randObj.initialization()
def setUp(self): param = Parameters() param.WITH_SHIFTS = True self.randObj = Random() self.randObj.initialization() self.coreObj = Core()
def setWithShifts(cls, value): param = Parameters() param.WITH_SHIFTS = value cls.randObj = Random() cls.randObj.initialization()