def analyze(): sims1 = [] labels1 = [] for run_number, exponent in enumerate(exponents1): runname = 'rsigma_{}'.format(exponent) sims1.append(simulation.Simulation('data/{}_output'.format(runname))) labels1.append(r'$r_{\sigma} = 10^{' + str(exponent) + '}$') simulation.Simulation.plotScatteringTest(sims1, labels1, filename='results/rsigmalog.png') sims2 = [] labels2 = [] for run_number, exponent in enumerate(exponents2): runname = 'steps_{}'.format(exponent) sims2.append(simulation.Simulation('data/{}_output'.format(runname))) labels2.append('$10^{' + str(exponent) + '}$ steps') simulation.Simulation.plotScatteringTest(sims2, labels2, filename='results/stepslog.png')
def test_short_sighted(): gen = 10 arrival_gen = algorithms.FileArrivals(6, 'arrival_files/arrivals_3.csv') move_gen = algorithms.ShortSighted() config = { 'num_rounds': 15, 'num_floors': 6, 'num_elevators': 2, 'elevator_capacity': 3, 'num_people_per_round': gen, 'arrival_generator': arrival_gen, # File arrival generator with 6 max floors and arrivals dictated by file # 'arrival_generator': arrival_gen, 'moving_algorithm': move_gen, 'visualize': False } sim = simulation.Simulation(config) stats = sim.run(15) people = 0 for elevator in sim.elevators: people += len(elevator.passengers) for key in sim.waiting: people += len(sim.waiting[key]) assert stats['num_iterations'] == 15 assert stats['total_people'] == 9 assert stats['people_completed'] == 7 assert stats['max_time'] == 8 assert stats['min_time'] == 1 assert stats['avg_time'] == 4 assert stats['total_people'] - stats['people_completed'] == people
def run_simulations(parameter): """ Runs the 2D Many-Rigid-Disc Collision Simulation. Parameters: parameter (list of [N_ball, random_speed_range, r_container, speed]): N_ball (int): Number of balls in the system. r_container (float): Radius of the container. random_speed_range (float): The speed range where the component velocity of the balls is generated from a uniform distribution of [-random_speed_range, random_speed_range]. speed (list of numpy.ndarray of float): List of ball velocities. Returns: (dict of float): Dictionary containing the average temperature and pressure of the system. """ N_ball = parameter[0] random_speed_range = parameter[1] r_container = parameter[2] speed = parameter[3] sim_IGL = sim.Simulation( N_ball=N_ball, r_container=r_container, r_ball=r_ball, m_ball=m_ball, random_speed_range=random_speed_range, ) sim_IGL.set_vel_ball(speed) result = sim_IGL.run(collisions=collisions, pressure=True, temperature=True, progress=False) return result
def run(run_name='default', parameters={}, hoffman2=False, compute_processes=1): parameter_defaults = parameterDefaults(run_name) assert all(key in parameter_defaults for key in parameters) with open('data/{}_input'.format(run_name), 'w') as f: for key in parameter_defaults.keys(): if key in parameters: value = parameters[key] else: value = parameter_defaults[key] f.write('{} = {}\n'.format(key, value)) if hoffman2: subprocess.run([ 'qsub', '-pe', 'dc_*', str(compute_processes + 1), 'run_epamss.sh', 'data/{}_input'.format(run_name) ], check=True) else: subprocess.run([ 'mpirun', '-np', str(compute_processes + 1), 'epamss', 'data/{}_input'.format(run_name) ], check=True) if os.path.isfile('data/{}_output'.format(run_name)): return simulation.Simulation( parameters['output_filename'] if 'output_filename' in parameters else parameter_defaults['output_filename'])
def __init__(self): phys_args = dict() phys_args['gravity'] = 9.81 phys_args['l1'] = 0.3 phys_args['l1c'] = 0.2071 phys_args['l2'] = 0.542 phys_args['l2c'] = 0.2717 phys_args['m1'] = 2.934 phys_args['m2'] = 1.1022 phys_args['mb'] = 0.064 phys_args['I1'] = 0.2067 phys_args['I2'] = 0.1362 phys_args['k2'] = 14.1543 phys_args['tau_max'] = 180.0 phys_args['q1d_max'] = 3.787 phys_args['power_max'] = 270.0 phys_args['enforce_constraints'] = True self.pitch_bot = robot.PitchingBot(**phys_args) self.flying_ball = robot.FlyingBall(**phys_args) sim_args = {} #sim_args['integrator'] = 'vode' sim_args['speed_factor'] = 1.0 sim_args['step_size'] = 0.01 sim_args['print_info'] = False sim_args['live_plot'] = False sim_args['constraint_warnings'] = True self.sim = simulation.Simulation(**sim_args)
def parseAndRun(self, values): args = Namespace(rocket='model.ork', outfile='./out.csv', rodAngle=45, rodAngleSigma=5, rodDirection=0, rodDirectionSigma=5, windSpeed=15, windSpeedSigma=5, startLat=0, startLong=0, simCount=25, windDirection=0, motorPerformance=0.1, parachute=0, pValue=0.007, iValue=0.2, finName="CONTROL") for k in args.__dict__: if values.__dict__[k] != '': if k == 'rocket' or k == 'outfile' or k == 'finName': self.args.__dict__[k] = values.__dict__[k] elif k == 'simCount': self.args.__dict__[k] = int(values.__dict__[k]) else: self.args.__dict__[k] = float(values.__dict__[k]) self.sim = simulation.Simulation() self.sim.set_args(self.args)
def makeSimulation(): sim = si.Simulation() sim.setNumPhases(10) sim.setTimestepsPerPhase(1) sim.setTimestep(1) sim.setIntegrator(si.Integrator.QuadraticExact) return sim
def run_simulations(parameter): """ Runs the 2D Many-Rigid-Disc Collision Simulation. Parameters: parameter (list of [r_ball, random_speed_range]): r_ball (float): Ball radius. random_speed_range (float): The speed range where the component velocity of the balls is generated from a uniform distribution of [-random_speed_range, random_speed_range]. Returns: (dict of float): Dictionary containing the average temperature and pressure of the system. """ r_ball = parameter[0] random_speed_range = parameter[1] sim_VDW = sim.Simulation( N_ball=N_ball, r_container=r_container, r_ball=r_ball, m_ball=m_ball, random_speed_range=random_speed_range, ) result = sim_VDW.run(collisions=collisions, pressure=True, temperature=True, progress=False) return result
def init(_args, _root): global args args = _args global db db = Database(clean=args.clean) global postCache postCache = Cache() global commentCache commentCache = Cache() global messageCache messageCache = Cache() global userNotifCache userNotifCache = Cache() global root root = _root global sim sim = simulation.Simulation(clean=args.clean) global conf conf = {"startingPoints": 0}
def main(): # define the variables L, F, q, x, y, w and k # L: length of one side of the square area # F: number of cultural features # q: number of possible traits for each feature # x: horizontal position of obstacle, # y: vertical position of the beginning of the window on the obstacle # w: size of the window L = [8] F = [5] Q = [10, 15] x = [int(l / 2) for l in L] num_of_realization = 10 step_number = [100000 * l * l for l in L] Y = [0,1,2,3] W = [1,3,5,7] # in case of multiple values, run the simulations for each value of each variable for f in F: for q in Q: for i in range(len(L)): for y in Y: for w in W: if y <= int(math.ceil((L[i] - w )/ 2)): #print(L[i]," ", f," ", q," ", x[i]," ", y," ", w) acm_simulator = simulation.Simulation(L[i], f, q, visualize_grid=False) acm_simulator.run([x[i], y, w], step_number[i], num_of_realization)
def test_no_params(): try: from unittest.mock import patch except ImportError: from mock import patch testargs = ["prog"] with patch.object(sys, 'argv', testargs): sim = simulation.Simulation() args = 0 sim.set_args(args) sim.parse_args() assert sim.args.outfile == "./out.csv" assert sim.args.rocket == sim.resource_path("model.ork") assert sim.args.simCount == 20 assert sim.args.rodAngle == 45 assert sim.args.rodAngleSigma == 5 assert sim.args.rodDirection == 0 assert sim.args.rodDirectionSigma == 5 assert sim.args.windSpeed == 15 assert sim.args.windSpeedSigma == 5 assert sim.args.startLat == 0 assert sim.args.startLong == 0 assert sim.args.pValue == 0.007 assert sim.args.iValue == 0.2 assert sim.args.finName == "CONTROL"
def runSimulation(self): """ runs the simulator on this project and returns the created Simulation object """ simulationResult = None if (self.id != None): headers = { 'APIKey': self.APIKey, 'content-type': 'application/x-www-form-urlencoded' } payload = urllib.urlencode({'id': self.id}) r = requests.post(config.URL + "simulations/create", data=payload, headers=headers) if (r.status_code == requests.codes.ok): data = r.text if (data != config.INVALID_API_KEY): simulationResult = simulation.Simulation(int(data), self) else: raise ValueError("'" + self.APIKey + "'" + " is not a valid API key.") else: print "Error in the server." else: print "This project has not yet been stored." return simulationResult
def getSimulations(self): """ returns previous simulation headers in the form of Simulation objects """ simulationResults = [] outputString = "" if (self.id != None): headers = {'APIKey': self.APIKey} payload = {'id': self.id} r = requests.get(config.URL + "multiplesimulations.json", params=payload, headers=headers) if (r.status_code == requests.codes.ok): data = r.text if (data != config.INVALID_API_KEY): simulationJSONList = json.loads(data) count = 0 for x in simulationJSONList: simulationResults.append( simulation.Simulation(int(x['id']), self)) outputString += "(" + repr( count) + ") " + "Simulation " + x['id'] + " " count = count + 1 else: raise ValueError("'" + self.APIKey + "'" + " is not a valid API key.") else: print "Error in the server." print outputString return simulationResults
def initialize_sim(num_genes, num_nodes): """Initialize the simulation.""" sim = simulation.Simulation(genes = num_genes) sim.initialize_nodestate(num_nodes = num_nodes) sim.initialize_randomrelations() sim.calculate_statics() return sim
def start_simulation(self): self.get_dates_infos() self.get_output_name() self.error_catch() #Simulation informations/statistics : self.infos_frame_creation() #self.termf_display() #save form self.save_form() try: self.curr_simulation = sim.Simulation(self.startDate, self.endDate, self.timestep, self.mesh, self.outputName, self.latitude, self.readData, self.dataPath) self.betaLoadingLabel['text'] = "Beta coefficient : " + self.done except IOError: self.popupmsg("An error occured ! Please verify simulation parameters...") if(self.colorInput.get() != ''): print("Color simulation possible") self.make_color_simulation() try: self.curr_simulation.make_simulation() except IOError: self.popupmsg("An error occured ! Please verify simulation parameters...") self.simLoadingLabel['text'] = "Simulation : " + self.done self.simInfosFrame.update()
def test_create_pop(): pop_size = 1000 vacc_percentage = .25 virus_name = "Ebola" mortality_rate = 0.5 basic_repro_num = 1 initial_infected = 1 sim = simulation.Simulation(pop_size, vacc_percentage, virus_name, mortality_rate, basic_repro_num, initial_infected) population = sim._create_population(initial_infected) person = Person(10, True, None) assert person._id == 10 assert person.is_vaccinated == True assert person.infected == None assert len(population) == pop_size vaccinated_people = 0 for person in population: if person.is_vaccinated: vaccinated_people += 1 assert vaccinated_people / len(population) == vacc_percentage
def create_collision_wall(integrator, f=20, L=1): """Creates a simulation of a collision with a wall.""" a = atoms.Neon([0, 0, 0], [1, 0, 0]) atom_list = [a] s = atoms.System(atom_list) fWall = forcefields.Wall(f, L, 0) return simulation.Simulation(s, [fWall], integrator)
def test_time_step(self): s = simulation.Simulation(time_step_nbr=1000, boundary_types="periodic", cells=80, domain_size=10, final_time=10) self.assertEqual(0.01, s.time_step)
def handleSearch(): """ Gere la recherche de la vitesse initiale necessaire pour aller a une hauteur X (beta) args / returns : graphs de la simulation et resultats """ minimum = 30 maximum = 100 steps = 5 trouve = 0 last = 0 m = 0.032 + askCharge() regress = [] print("Creation de la regression a basse precision pour cette masse") s = simulation.Simulation(bladeGeom, I, 0.1) cherche = 100 fastRange = range(minimum, maximum, steps) for i in fastRange: w = i * 2 * np.pi ymax = s.simulate(w, m, True) print(ymax) regress.append(ymax) fastResearch = np.polyfit(regress, list(fastRange), 11) eqRecherche = np.poly1d(fastResearch) print("RĂ©gression termine, quelle hauteur chercher vous (m) ?") while cherche > 0: cherche = float(input(">>")) sample = eqRecherche(cherche) print("Nous vous proposons une vitesse de ", sample, "tour / seconde") print("Qui vous donnerait") s = simulation.Simulation(bladeGeom, I, 0.01) s.simulate(sample * 2 * np.pi, m) ymax, tmax = s.analyseSimulation(True) s.simulationGraph() s.energies(True) erreur = abs(ymax - cherche) / cherche * 100 print( "\n le resultat a un taux d erreur de ", erreur, "%\nnous nous excusons pour le resultat imprecis, une nouvelle version du programme fera des recherches plus precises" ) plt.show()
def Init(): try: thread1 = simulation.Simulation(self) thread1.start() except: self.setInstruction( "Veuillez selectionner un scenario dans la liste") self.setInstruction("Ou cocher la case \"Tout tester\"")
def test_boundary_conditions(self): j = simulation.Simulation(time_step_nbr=1000, boundary_types="periodic", cells=80, domain_size=10, final_time=1.) for d in np.arange(j.dims): self.assertEqual("periodic", j.boundary_types[d])
def evaluate_(item): average = 0 num_samples = 1 # XXX for i in range(num_samples): s = simulation.Simulation(item) s.run() average += s.get_results() average /= num_samples return 1 / ((average**3) + .00001)
def reference_frame(self): self.get_dates_infos() self.get_output_name() self.error_catch() try : simulation = sim.Simulation(self.startDate,self.endDate,self.timestep,self.mesh,self.outputName,self.latitude,self.readData,self.dataPath) simulation.export_reference_frame() except (IOError, ValueError) as e: self.popupmsg("An error occured ! Please verify simulation parameters...")
def setUp(self): if C_IMP: self.sim = CINS() else: self.sim = PyINS() self.sim.prepare() import simulation self.model = simulation.Simulation()
def period_at(B, c): s = simulation.Simulation() s.B = B s.c = c s.Om = 0.17 s.T = 2**12 s.solve() s.find_period() return (s.check_periodicity(), s.Tp)
def test_setup(): sim = simulation.Simulation(population_size=1000, vaccination_rate=0.5, virus_name="Eeksies", mortality_rate=0.5, infection_rate=3/4) assert sim.population_size == 1000 assert sim.vaccination_rate == 0.5 assert sim.virus_name == "Eeksies" assert sim.mortality_rate == 0.5 assert sim.infected_rate == 0.75 assert sim.initial_infected == 1 assert sim.num_interactions == 100 assert sim.newly_infected == []
def SetupSim(self): brakeAzmuth = math.atan2( self.ballList[1].Loc.y - self.ballList[0].Loc.y, self.ballList[1].Loc.x - self.ballList[0].Loc.x) shot = tableballdefs.Shot(self.ballList[0], 2, brakeAzmuth, 0, self.ballList[0].radius / 2) sim = simulation.Simulation(self.numballs, self.ballList, shot, self.table) sim.run()
def main(): """ Entry point function :return: """ simulator = simulation.Simulation() try: simulator.start() except KeyboardInterrupt: simulator.stop()
def simulation(self, realtime=False, trace=True, gui=True, initial_time=0, environment_process=None, **kwargs): """ Prepare simulation of the model This will actually not run the simulation it will only return the simulation object. The object can then be run using run(max_time) command. realtime - should the simualtion be run in real time or not? trace - should the trace of the simulation be printed? gui - should the environment appear on a separate screen? (This requires tkinter) initial_time - what is the starting time point of the simulation? environment_process - what environment process should the simulation use? The last argument should be supplied with the method environment_process of the environemnt used in the model. kwargs are arguments that environment_process will be supplied with. """ if len(self.decmems) == 1: for key in self.__buffers: self.__buffers[ key].dm = self.decmem #if only one dm, let all buffers use it elif len([x for x in self.decmems.values() if x]) == 1: for key in self.__buffers: if not self.__buffers[key].dm: self.__buffers[ key].dm = self.decmem #if only one non-trivial dm, let buffers use it that do not have a dm specified decmem = {name: self.__buffers[name].dm for name in self.__buffers\ if self.__buffers[name].dm != None} #dict of declarative memories used; more than 1 decmem might appear here # self.__buffers["manual"] = motor.Motor() #adding motor buffer if self.__env: self.__env.initial_time = initial_time #set the initial time of the environment to be the same as simulation # if self.visbuffers: # self.__buffers.update(self.visbuffers) # else: # dm = list(decmem.values())[0] # self.__buffers["visual"] = vision.Visual(self.__env, dm) #adding vision buffers # self.__buffers["visual_location"] = vision.VisualLocation(self.__env, dm) #adding vision buffers self.used_productions = productions.ProductionRules( self.__productions, self.__buffers, decmem, self.model_parameters ) #only temporarily changed, should be used_productions chunks.Chunk._similarities = self.__similarities return simulation.Simulation(self.__env, realtime, trace, gui, self.__buffers, self.used_productions, initial_time, environment_process, **kwargs)
def main(): input_speed = np.array([30]) """ Note: it no longer matters how many elements the input_speed array has, the simulation automatically reshapes the array depending on the simulation_length. Examples: If you want a constant speed for the entire simulation, insert a single element into the input_speed array. >>> input_speed = np.array([30]) <-- constant speed of 30km/h If you want 50km/h in the first half of the simulation and 60km/h in the second half, do the following: >>> input_speed = np.array([50, 60]) This logic will apply for all subsequent array lengths (3, 4, 5, etc.) Keep in mind, however, that the condition len(input_speed) <= simulation_length must be true """ simulation_model = simulation.Simulation(race_type="ASC") distance_travelled = simulation_model.run_model(speed=input_speed, plot_results=True, verbose=False) bounds = InputBounds() bounds.add_bounds(8, 20, 60) optimization = BayesianOptimization(bounds, simulation_model.run_model) random_optimization = RandomOptimization(bounds, simulation_model.run_model) results = optimization.maximize(init_points=3, n_iter=1, kappa=10) optimized = simulation_model.run_model(speed=np.fromiter(results, dtype=float), plot_results=True, verbose=False, route_visualization=False) results_random = random_optimization.maximize(iterations=15) optimized_random = simulation_model.run_model(speed=np.fromiter( results_random, dtype=float), plot_results=True, verbose=False, route_visualization=False) print(f'Distance travelled: {distance_travelled}') print(f'Optimized results. Max traversable distance: {optimized}') print(f'Random results. Max traversable distance: {optimized_random}') print(f'Optimized Speeds array: {results}') print(f'Random Speeds array: {results_random}') return distance_travelled