def grovers_algorithm(folder): """ Function to implement Grover's Algorithm. param: folder - string name of folder where plot must be saved """ # Creating quantum circuit qubits = qk.QuantumRegister(3) quantum_circuit = qk.QuantumCircuit(qubits) # Applying Hadamard gates quantum_circuit.h(qubits) quantum_circuit.barrier() # Marking the states for searching quantum_circuit = phase_quantum_oracle(quantum_circuit, qubits) quantum_circuit.barrier() # Inverting circuit quantum_circuit = inversion_about_average(quantum_circuit, qubits, 3) quantum_circuit.barrier() # Measuring output quantum_circuit.measure_all() # Simulating quantum circuit simulation.simulation(quantum_circuit, folder) return
def quantum_fourier_transform_algorithm(qubits_number, folder): """ Function to implement Quantum Fourier Transform. param: 1. qubits_number - int number of qubits 2. folder - string name of folder where plot must be saved """ # Creating quantum circuit qubits = qk.QuantumRegister(qubits_number) quantum_circuit = qk.QuantumCircuit(qubits) # Defining qubits input state quantum_circuit = input_state(quantum_circuit, qubits_number) quantum_circuit.barrier() # Transforming the qubits quantum_circuit = quantum_fourier_transform(quantum_circuit, qubits_number) # Measuring output quantum_circuit.measure_all() # Simulating quantum circuit simulation.simulation(quantum_circuit, folder) return
def quantum_phase_estimation_algorithm(folder): """ Function to implement Quantum Phase Estimation. param: folder - string name of folder where plot must be saved """ # Creating quantum circuit qubits = qk.QuantumRegister(4) classical_bits = qk.ClassicalRegister(3) quantum_circuit = qk.QuantumCircuit(qubits, classical_bits) # Applying X and Hadamard gates quantum_circuit.x(qubits[3]) quantum_circuit.h(qubits[:3]) # Performing controlled unitary operations iterations = 4 for qubit in range(3): for i in range(iterations): quantum_circuit.cu1(np.pi / 4, qubit, 3) iterations //= 2 # Applying inverse QFT quantum_circuit = quantum_fourier_transform_estimation(quantum_circuit, 3) # Measuring output quantum_circuit.measure(0, 2) quantum_circuit.measure(1, 1) quantum_circuit.measure(2, 0) # Simulating quantum circuit simulation.simulation(quantum_circuit, folder) return
def __init__(self, temp): # disease detect s_Disease = "plant_images\\disease_img.jpg" s_Image = "plant_images\\source_img.jpg" print("__init__") print(temp) # programLogic.diseaseDitect(s_Image, s_Disease) os.system("CLS") print("############## Please fill below details ##############") temprature = float(input("ENV TEMPRATURE : ")) wind_speed = float(input("WIND SPEED : ")) wind_nature = str(input("WIND NATURE : ")) co2_level = float(input("CO2 LEVEL : ")) hclo3_level = float(input("HCLO3 LEVEL : ")) base_level = float(input("BASE LEVEL : ")) co_level = float(input("CO LEVEL : ")) AH_level = float(input("ABSOLUTE HUMIDITY : ")) RH_level = float(input("RELETIVE HUMIDITY : ")) soil_moisture = float(input("SOIL MOISTURE : ")) PH_level = float(input("PH LEVEL : ")) light_intensity = float(input("LIGHT INTENSITY : ")) UV_condition = float(input("UV CONDITION : ")) IR_condition = float(input("IR CONDITION : ")) print("#######################################################") programLogic.pestDitect() programLogic.flowerDitect() w = whetherAnalysis.whetherAnalysis # w.__init__(25, 127,"stormy",100,2,5,20, 10,50, 100, 5.6, 30, 4, 6) w.__init__(temprature, wind_speed, wind_nature, co2_level, hclo3_level, base_level, co_level, AH_level, RH_level, soil_moisture, PH_level, light_intensity, UV_condition, IR_condition) simulation.simulation(s_Image, s_Disease, temprature, wind_speed, wind_nature, co2_level, hclo3_level, base_level, co_level, AH_level, RH_level, soil_moisture, PH_level, light_intensity, UV_condition, IR_condition)
def superdense_coding_protocol(folder): """ Function to implement Superdense Coding Protocol. param: folder - string name of folder where plot must be saved """ # Creating quantum circuit qubits = qk.QuantumRegister(2) quantum_circuit = qk.QuantumCircuit(qubits) # Generating the entangled pair quantum_circuit.h(qubits[0]) quantum_circuit.cx(qubits[0], qubits[1]) quantum_circuit.barrier() # Encoding message quantum_circuit.z(qubits[0]) quantum_circuit.x(qubits[0]) quantum_circuit.barrier() # Sending messsage quantum_circuit.cx(qubits[0], qubits[1]) quantum_circuit.h(qubits[0]) quantum_circuit.barrier() # Measuring output quantum_circuit.measure_all() # Simulating quantum circuit simulation.simulation(quantum_circuit, folder) return
def test_daily_ret(self): testSimu1 = simulation(100, 1000) #test the position value self.assertEqual(testSimu1.position_value, 10) #test the single return and total return daily_ret = testSimu1.cumu_return() self.assertTrue(daily_ret[1].mean() <= 1 and daily_ret[1] >= -1) self.assertTrue(np.mean(daily_ret) <= 1 and np.mean(daily_ret) >= -1) #test the length of the list self.assertEqual(len(daily_ret), 1000) testSimu1 = simulation(50, 2000) #test the position value self.assertEqual(testSimu1.position_value, 20) #test the single return and total return daily_ret = testSimu1.cumu_return() self.assertTrue(daily_ret[1].mean() <= 1 and daily_ret[1] >= -1) self.assertTrue(np.mean(daily_ret) <= 1 and np.mean(daily_ret) >= -1) #test the length of the list self.assertEqual(len(daily_ret), 2000)
def main(n=1000, isSim=True): ''' ''' demandData = load_DemandData() locations = load_WarehouseLocations() #distances = load_WarehouseRoutes(True) durations = load_WarehouseRoutes(False) nodes = initialise_nodes(demandData, locations) north_routes, north_obj = find_routes(nodes, durations, n, False) south_routes, south_obj = find_routes(nodes, durations, n, True) if isSim: north_weekday = simulation(north_routes, isWeekday=True, n=1000) south_weekday = simulation(south_routes, isWeekday=True, n=1000) north_weekend = simulation(north_routes, isWeekday=False, n=1000) south_weekend = simulation(south_routes, isWeekday=False, n=1000) sim_plot(north_weekday, south_weekday, north_weekend, south_weekend) print(percent_return(north_routes)) print("North:", north_obj, "South:", south_obj, sep='\t') print('Percentage of routes not returning to original warehouse: ', percent_return(north_routes))
def run(config_file): # Load configuration. config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_file) p = neat.Checkpointer.restore_checkpoint('checkpoint') genomes = list(p.population.values()) genomes = [genome for genome in genomes if genome.fitness is not None] genomes.sort(key=operator.attrgetter('fitness')) best = genomes[:2] simulation(best[0], best[1], config, True)
def eval_genomes(genomes, config): for _, genome in genomes: genome.fitness = 0 for _ in range(ROUNDS): for pair in pairs(sample(genomes, len(genomes))): if len(pair) == 2: [(_, genome1), (_, genome2)] = pair simulation(genome1, genome2, config) else: [(_, genome)] = pair simulation(genome, genome, config) genome.fitness = genome.fitness / 2
def deutsch_josza_algorithm(string_length, folder, quantum_oracle='b'): """ Function to implement Superdense Coding Protocol. param: 1. string_length - int length ob bit-string 2. folder - string name of folder where plot must be saved 3. quantum_oracle - char value of function type ('b' as default) """ # Creating quantum circuit qubits = qk.QuantumRegister(string_length + 1) classical_bits = qk.ClassicalRegister(string_length) quantum_circuit = qk.QuantumCircuit(qubits, classical_bits) # Flipping the last qubit quantum_circuit.x(qubits[string_length]) quantum_circuit.barrier() # Applying Hadamard gates to all qubits quantum_circuit.h(qubits) quantum_circuit.barrier() # Setting gates depending of function type if quantum_oracle == 'b': a = np.random.randint(1, 2**string_length) for i in range(string_length): if a & (1 << i): quantum_circuit.cx(qubits[i], qubits[string_length]) else: a = np.random.randint(2) if a == 1: quantum_circuit.x(qubits[string_length]) else: quantum_circuit.iden(qubits[string_length]) quantum_circuit.barrier() # Applying Hadamard gates quantum_circuit.h(qubits[:string_length]) # Measuring output quantum_circuit.measure(qubits[:string_length], classical_bits[:string_length]) # Simulating quantum circuit simulation.simulation(quantum_circuit, folder) return
def boids(): """ Returns an animation of a flock of `boids' (https://dl.acm.org/citation.cfm?doid37401.37406) with interaction parameters starting positions specified by the config.yml file """ # Load config dictionary and instantiate the swarm config=yaml.load(open( os.path.join(os.path.dirname(__file__), "config.yml"))) swarm=simulation(config) # Animate! figure=plt.figure() axes=plt.axes(xlim=(-500,1500), ylim=(-500,1500)) scatter=axes.scatter(swarm.flock_coords[0],swarm.flock_coords[1]) def animate(frame): swarm.update() scatter.set_offsets(zip(swarm.flock_coords[0],swarm.flock_coords[1])) anim = animation.FuncAnimation(figure, animate, frames=50, interval=50) plt.show()
def randomSimulation(self): dialog = QtGui.QInputDialog() value, ok = dialog.getInt(self, "Random simulation", "How many followers?", DEFAULT_RANDOM_AMOUNT, 0) if ok: self.simulation = simulation(self.current_window_width, self.current_window_height, value, True) self.fps_slider.setValue(60) self.resetButtons()
def evaluate(self, optimum=None): # Evaluate the individual if random.random() > 0.99: show = True else: show = False sim = simulation(show=show) # Create the simulation delta = 0.02 # Create the robot pos_x = 500 pos_y = 350 w = 15 wlk = walker(sim.space, \ (pos_x, pos_y), \ self.get_gene('ul'), \ self.get_gene('ll'), \ w, \ self.get_gene('lua'), \ self.get_gene('lla'), \ self.get_gene('rua'), \ self.get_gene('rla')) # Test the robot in the simulation running = True while running: sim.step(delta) ke = sim.get_ke() if ke < 4000.0 or ke > 1000000000.0: running = False # The score minimizes x self.score = wlk.lul.body.position[0] + \ wlk.rul.body.position[0] print 'score: ', self.score
def parse_config(self, conf_files): #---------------------------------------- # read and parse config file # of simulations and components #---------------------------------------- for conf_file in conf_files: try: config = ConfigObj(conf_file, file_error=True, interpolation='template') except IOError as xxx_todo_changeme: (ex) = xxx_todo_changeme print('Error opening/finding config file %s' % conf_file) print('ConfigObj error message: ', ex) raise except SyntaxError as xxx_todo_changeme1: (ex) = xxx_todo_changeme1 print('Syntax problem in config file %s' % conf_file) print('ConfigObj error message: ', ex) raise try: sims = config['simulation'] if not isinstance(sims, list): sims = [sims] for s in sims: self.simulations.append( simulation(config[s], self, len(self.simulations))) self.description = config['description'] except: print('problem parsing simulations') raise
def main(): """ simulate a multi-dimensional hawkes point process, the parameters are hard encoded """ # parse argument parser = argparse.ArgumentParser( "Multi-dimensional hawkes point process simulator") parser.add_argument('params', type=str, nargs='?', default='parameters.json', help="the filepath of json parameter file") args = parser.parse_args() # load parameters parameters = json.load(open(args.params, "rt")) # simulate U, A, w, T = parameters['U'], parameters['A'], parameters['w'], parameters[ 'T'] seqs = simulation(U, A, w, T) # save result dirname = "result" os.makedirs(dirname, exist_ok=True) json.dump(parameters, open(os.path.join(dirname, "parameters.json"), "wt"), indent=2) json.dump(seqs, open(os.path.join(dirname, "sequences.json"), "wt"), indent=2) # draw figures draw_line(seqs, os.path.join(dirname, "line.svg")) draw_qq_plot(parameters, seqs, os.path.join(dirname, "qq_plot.svg"))
def __init__(self, scale, device): self.device = device self.scale = scale self.simulation = simulation() self.upsample = upsample() self.upsample.to(self.device)
def parse_config(self, conf_files): """ for each configuration file in conf_files, the simulation definition sections are detected, and simulation objects created. Further parsing happens in the simulation object, and its sub-objects. """ for conf_file in conf_files: try: config = ConfigObj(conf_file, file_error=True, interpolation='template') except IOError as xxx_todo_changeme: (ex) = xxx_todo_changeme print('Error opening/finding config file %s' % conf_file) print('ConfigObj error message: ', ex) raise except SyntaxError as xxx_todo_changeme1: (ex) = xxx_todo_changeme1 print('Syntax problem in config file %s' % conf_file) print('ConfigObj error message: ', ex) raise try: sims = config['simulation'] if not isinstance(sims, list): sims = [sims] for s in sims: self.simulations.append( simulation(config[s], self, len(self.simulations))) self.description = config['description'] except: print('problem parsing simulations') raise
def test_createUser(self): np.random.seed(seednum) # create an instance of the class simulation simulation_obj = simulation(num_of_users, num_of_timeframes) np.random.seed(seednum) u = simulation_obj.createUser() self.assertEquals("(0.22199317108973948, 0.8707323061773764)", str(u))
def test_culc_TF_potential_risk(self): np.random.seed(seednum) # create an instance of the class simulation simulation_obj = simulation(3, 3, smoothing_factor=0.1, change_prob=0) users_risk_list = [(0, 0.9), (1, 0.8), (3, 0.6), (4, 0.5), (2, 0), (5, 0)] capacity = 4 users_risk_list2 = [(0, 0.9), (1, 0.8), (4, 0), (2, 0), (3, 0), (5, 0.99)] capacity2 = 3 users_risk_list3 = [(0, 0.9), (1, 0.8), (4, 0.3), (2, 0.22), (3, 0.44), (5, 0.99)] capacity3 = 6 capacity4 = 5 self.assertEquals( "2.8", str( simulation_obj.calc_TF_potential_risk(users_risk_list, capacity))) self.assertEquals( "2.69", str( simulation_obj.calc_TF_potential_risk(users_risk_list2, capacity2))) self.assertEquals( "3.65", str( simulation_obj.calc_TF_potential_risk(users_risk_list3, capacity3))) self.assertEquals( "3.43", str( simulation_obj.calc_TF_potential_risk(users_risk_list3, capacity4)))
def setUp(self): n =100 self.xmax = 100 self.xmin = 10 self.ymax = 200 self.ymin = 5 particles = Particles('nazwa', n) self.simulation = simulation(particles) self.simulation.set_boundaries(self.xmax, self.xmin, self.ymax, self.ymin)
def exercise_8f_offet(timestep): """search phase offset """ phase_range=np.linspace(0, np.pi, 10) parameter_set = [ SimulationParameters( duration=10, # Simulation duration in [s] timestep=timestep, # Simulation timestep in [s] spawn_position=[0, 0, 0.1], # Robot position in [m] spawn_orientation=[0, 0, 0], # Orientation in Euler angles [rad] drive=2., # An example of parameter part of the grid search amplitudes=[0.3, 0.3], turn=0, pattern='walk', phase_lag=0.2*np.pi, absolute_amplitude=False, phase_body_limb=temp_phase , ) for temp_phase in phase_range ] filename = './logs_8f/phase{}.{}' for i in range(len(phase_range)): temp_phase=phase_range[i] temp_param=parameter_set[i] sim, data = simulation ( sim_parameters=temp_param, arena='ground', fast=True ) data.to_file(filename.format(temp_phase,'h5')) velocities=[] for i in range(len(phase_range)): temp_phase=phase_range[i] data=AnimatData.from_file(filename.format(temp_phase, 'h5')) links_positions = data.sensors.gps.urdf_positions() head_positions = links_positions[:, 0, :] final_head_dist=np.linalg.norm(head_positions[-1]) times = data.times total_time = times[-1] - times[0] temp_velocity = final_head_dist/total_time velocities.append(temp_velocity) fig = plt.figure() plt.plot(phase_range, velocities) plt.legend() plt.xlabel("phase") plt.ylabel("velocity") plt.title("Relationship of Phase Offset and Walking Speed") plt.grid(True)
def exercise_example(timestep): """Exercise example""" # Parameters parameter_set = [ SimulationParameters( duration=10, # Simulation duration in [s] timestep=timestep, # Simulation timestep in [s] spawn_position=[0, 0, 0.1], # Robot position in [m] spawn_orientation=[0, 0, 0], # Orientation in Euler angles [rad] drive=3, # An example of parameter part of the grid search amplitude_gradient=None, #amplitudes=[1, 2, 3], # Just an example phase_lag=2 * np.pi / 10, # or np.zeros(n_joints) for example # Another example frequency=1, # ... ) for drive in np.linspace(1, 2, 2) # for amplitudes in ... # for ... ] # Grid search for simulation_i, sim_parameters in enumerate(parameter_set): filename = './logs/example/simulation_{}.{}' sim, data = simulation( sim_parameters=sim_parameters, # Simulation parameters, see above arena='water', # Can also be 'ground' or 'amphibious' # fast=True, # For fast mode (not real-time) # headless=True, # For headless mode (No GUI, could be faster) # record=True, # Record video, see below for saving # video_distance=1.5, # Set distance of camera to robot # video_yaw=0, # Set camera yaw for recording # video_pitch=-45, # Set camera pitch for recording ) # Log robot data data.to_file(filename.format(simulation_i, 'h5'), sim.iteration) # Log simulation parameters with open(filename.format(simulation_i, 'pickle'), 'wb') as param_file: pickle.dump(sim_parameters, param_file) # Save video if sim.options.record: if 'ffmpeg' in manimation.writers.avail: sim.interface.video.save( filename='salamandra_robotica_simulation.mp4', iteration=sim.iteration, writer='ffmpeg', ) elif 'html' in manimation.writers.avail: # FFmpeg might not be installed, use html instead sim.interface.video.save( filename='salamandra_robotica_simulation.html', iteration=sim.iteration, writer='html', ) else: pylog.error('No known writers, maybe you can use: {}'.format( manimation.writers.avail))
def test_sort_users_by_risk(self): np.random.seed(seednum) # create an instance of the class simulation simulation_obj = simulation(3, 3, smoothing_factor=0.1, change_prob=0) risks = simulation_obj.current_timeframe_risks(1) sorted_by_risks = simulation_obj.sort_users_by_risk(risks) #compare the risks from time frame index = 1 to the expected risks: self.assertEquals([[2, 0.09637744711724958], [0, 0.004097132462795419], [1, 0.0012278863428629003]], sorted_by_risks)
def test_choose_top_users(self): np.random.seed(seednum) # create an instance of the class simulation simulation_obj = simulation(3, 3, smoothing_factor=0.1, change_prob=0) users_risk_list = [(0, 0.9), (1, 0.8), (2, 0.7), (3, 0.6), (4, 0.5), (5, 0.4)] capacity = 2 users = simulation_obj.choose_top_users(users_risk_list, capacity) self.assertEquals("[(0, 0.9), (1, 0.8)]", str(users))
def quantum_counting(folder): """ Function to implement Quantum Counting. param: folder - string name of folder where plot must be saved """ # Determining the number of qubits for counting and searching qubits_number_counting = 4 qubits_number_searching = 4 # Creating quantum circuit qubits = \ qk.QuantumRegister(qubits_number_counting + qubits_number_searching) classical_bits = qk.ClassicalRegister(qubits_number_searching) quantum_circuit = qk.QuantumCircuit(qubits, classical_bits) # Applying Hadamard gates quantum_circuit.h(qubits) quantum_circuit.barrier() # Applying controled Grover's iterations iterations = 1 for qubit in reversed(qubits[:4]): for i in range(iterations): quantum_circuit.append(grovers_iterations().to_gate().control(), qargs=[qubit] + qubits[qubits_number_counting:]) iterations *= 2 quantum_circuit.barrier() # Applying inverse QFT quantum_circuit.append(quantum_fourier_transform_grovers( qubits_number_counting).to_gate().inverse(), qargs=qubits[:qubits_number_counting]) quantum_circuit.barrier() # Measuring output quantum_circuit.measure(qubits[:qubits_number_counting], classical_bits) # Simulating quantum circuit simulation.simulation(quantum_circuit, folder) return
def exercise_8f(timestep, phase_lag_vector, experience): """Exercise 8f""" # Parameters parameter_set = [ SimulationParameters( duration=10, # Simulation duration in [s] timestep=timestep, # Simulation timestep in [s] spawn_position=[0, 0, 0.1], # Robot position in [m] spawn_orientation=[0, 0, 0], # Orientation in Euler angles [rad] drive_mlr=2, # drive so the robot can walk amplitude_limb=0.5, phase_lag=phase_lag, phase_limb_body=np.pi / 2, exercise_8f=True # ... ) for phase_lag in phase_lag_vector ] # Grid search for simulation_i, sim_parameters in enumerate(parameter_set): filename = './logs/{}/simulation_{}.{}' sim, data = simulation( sim_parameters=sim_parameters, # Simulation parameters, see above arena='ground', # Can also be 'ground' or 'amphibious' #fast=True, # For fast mode (not real-time) #headless=True, # For headless mode (No GUI, could be faster) # record=True, # Record video, see below for saving # video_distance=1.5, # Set distance of camera to robot # video_yaw=0, # Set camera yaw for recording # video_pitch=-45, # Set camera pitch for recording ) # Log robot data data.to_file(filename.format(experience, simulation_i, 'h5'), sim.iteration) # Log simulation parameters with open(filename.format(experience, simulation_i, 'pickle'), 'wb') as param_file: pickle.dump(sim_parameters, param_file) # Save video if sim.options.record: if 'ffmpeg' in manimation.writers.avail: sim.interface.video.save( filename='salamandra_robotica_simulation.mp4', iteration=sim.iteration, writer='ffmpeg', ) elif 'html' in manimation.writers.avail: # FFmpeg might not be installed, use html instead sim.interface.video.save( filename='salamandra_robotica_simulation.html', iteration=sim.iteration, writer='html', ) else: pylog.error('No known writers, maybe you can use: {}'.format( manimation.writers.avail))
def exercise_8d2(timestep): """Exercise 8d2""" parameter_set = SimulationParameters( duration=10, # Simulation duration in [s] timestep=timestep, # Simulation timestep in [s] spawn_position=[0, 0, 0.1], # Robot position in [m] spawn_orientation=[0, 0, 0], # Orientation in Euler angles [rad] drive=3., # An example of parameter part of the grid search amplitudes=[0.3, 0.3], turn=0, pattern='swim', phase_lag=-0.2 * np.pi, #amplitude=1., # ... ) filename = './logs_8d/simulation_back.{}' sim, data = simulation( sim_parameters=parameter_set, # Simulation parameters, see above arena='water', # Can also be 'ground' or 'amphibious' fast=True, # For fast mode (not real-time) #record=True, ) data.to_file(filename.format('h5')) ''' sim.interface.video.save( filename='8d_backward.mp4', iteration=sim.iteration, writer='ffmpeg', ) ''' data = AnimatData.from_file(filename.format('h5')) links_positions = data.sensors.gps.urdf_positions() head_positions = links_positions[:, 0, :] osc_phases = data.state.phases_all() osc_amplitudes = data.state.amplitudes_all() times = data.times plt.figure() plot_results.plot_trajectory( head_positions, title='Head Trajectory of Salmandar Swimming Backward') plt.figure() labels = ['Spine Joint ' + str(i + 1) for i in range(10)] links_positions = data.sensors.gps.urdf_positions() plot_results.plot_spine_angles( osc_phases, osc_amplitudes, times, labels=labels, title='Spine Angles of Salmandar Swimming Backward')
def __init__(self): device = torch.device("cuda:2" if torch.cuda.is_available() else "cpu") # training on GPU or CPU self.prediction = Prediction('scale_64',device) self.simulation = simulation() self.true_permeability = np.loadtxt(os.getcwd()+f'/Gaussian/test_data/true_permeability_0.05.dat').reshape(64,64) self.obs = np.loadtxt(os.getcwd()+f'/Gaussian/test_data/obs_0.05.dat') self.sigma = np.loadtxt(os.getcwd()+f'/Gaussian/test_data/sigma_0.05.dat') self.ref_fx,_,_,_,_,_ = self.simulation.demo64(self.true_permeability) self.ref_sswr = np.sum(np.power((self.obs-self.ref_fx)/self.sigma,2.0) ) self.ref_rss = np.sum(np.power((self.obs-self.ref_fx),2.0) )
def __button_calculate(self): # Perform simulation sim = simulation(self.n_simulations.get(), self.attacker, self.defender) self.avg_rounds.set(sim['rounds_avg']) self.att_fraction.set(sim['attacker_win_fraction'] * 100) self.def_fraction.set(sim['defender_win_fraction'] * 100) # Redraw the result inner frame self.inner_frame.destroy() self.inner_frame = self.__frame_results_filled()
def setUp(self): n = 100 self.xmax = 10 self.xmin = 0 self.ymax = 20 self.ymin = 0 particles = Particles('nazwa', n) self.simulation = simulation(particles) self.simulation.set_coordinations(n, self.xmax, self.xmin, self.ymax, self.ymin)
def run(config_file): config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_file) local_dir = os.path.dirname(__file__) checkpoint_path = os.path.join(local_dir, 'checkpoint') if os.path.isfile(checkpoint_path): p = neat.Checkpointer.restore_checkpoint(checkpoint_path) else: p = neat.Population(config) p.add_reporter(neat.StdOutReporter(True)) stats = neat.StatisticsReporter() p.add_reporter(stats) p.add_reporter(neat.Checkpointer(50)) winner = p.run(eval_genomes, 5000) simulation(winner, winner, config, True)
def exercise_8d1(timestep): """Exercise 8d1""" # Use exercise_example.py for reference parameter_set = [ SimulationParameters( duration=10, timestep=timestep, spawn_position=[0, 0, 0.1], # Robot position in [m] spawn_orientation=[0, 0, 0], # Orientation in Euler angles [rad] amplitude_gradient=True, drive=4, amplitudes=[0.2, 1], phase_lag=2 * np.pi / 10, frequency=1, turn=[0.5, 'Right'], ) ] # Grid search for simulation_i, sim_parameters in enumerate(parameter_set): filename = './logs/exercise_8d1/simulation_{}.{}' sim, data = simulation( sim_parameters=sim_parameters, # Simulation parameters, see above arena='water', # Can also be 'ground' or 'amphibious' # fast=True, # For fast mode (not real-time) # headless=True, # For headless mode (No GUI, could be faster) # record=True, # Record video, see below for saving # video_distance=1.5, # Set distance of camera to robot # video_yaw=0, # Set camera yaw for recording # video_pitch=-45, # Set camera pitch for recording ) # Log robot data data.to_file(filename.format(simulation_i, 'h5'), sim.iteration) # Log simulation parameters with open(filename.format(simulation_i, 'pickle'), 'wb') as param_file: pickle.dump(sim_parameters, param_file) # Save video if sim.options.record: if 'ffmpeg' in manimation.writers.avail: sim.interface.video.save( filename='salamandra_robotica_simulation.mp4', iteration=sim.iteration, writer='ffmpeg', ) elif 'html' in manimation.writers.avail: # FFmpeg might not be installed, use html instead sim.interface.video.save( filename='salamandra_robotica_simulation.html', iteration=sim.iteration, writer='html', ) else: pylog.error('No known writers, maybe you can use: {}'.format( manimation.writers.avail))
def quantum_teleportation_algorithm(secret_unitary, folder): """ Function to implement Quantum Teleportation Algorithm. param: 1. secret_unitary - string of gates names 2. folder - string name of folder where plot must be saved """ # Creating quantum circuit qubits = qk.QuantumRegister(3) classical_bits = qk.ClassicalRegister(3) quantum_circuit = qk.QuantumCircuit(qubits, classical_bits) # Applying the secret unitary secret_unitary_applying(secret_unitary, qubits[0], quantum_circuit) quantum_circuit.barrier() # Applying the teleportation protocol itself quantum_circuit.h(qubits[1]) quantum_circuit.cx(qubits[1], qubits[2]) quantum_circuit.barrier() quantum_circuit.cx(qubits[0], qubits[1]) quantum_circuit.h(qubits[0]) quantum_circuit.measure(qubits[:2], classical_bits[:2]) quantum_circuit.cx(qubits[1], qubits[2]) quantum_circuit.cz(qubits[0], qubits[2]) quantum_circuit.barrier() # Applying the secret unitary for output secret_unitary_applying(secret_unitary, qubits[2], quantum_circuit, dagger=True) # Measuring the output quantum_circuit.measure(qubits[2], classical_bits[2]) # Simulating quantum circuit simulation.simulation(quantum_circuit, folder) return
def __init__(self, add = None, tower=0): global SIM, file1 self.THREAD_LOCK = Lock() if file1 == None: self.ROBOT_DATA_FILE = patrol_config.LOG_PATH + datetime.datetime.now().isoformat('_') self.open_file() if SIM == None: SIM = simulation.simulation() self.STATUS = "Idle" self.LOCATION = -1 self.LAPS = 0 self.TOWER = tower threading.Thread.__init__(self)
def store_mean_std(positions,num_trials): ''' receive a list of positions and a number of trials, stimulate each position, store the mean and standard deviation of daily return in a file called results.txt. ''' try: results = open('results.txt','w') #open a file to store mean and standard deviation except: print " Errors! Cannot open the file!" for position in positions: daily_ret = simulation(position, num_trials) mean = np.mean(daily_ret) std = np.std(daily_ret) results.write('Position: ' + str(position) + '\n') results.write('Mean: ' + str(mean) + '\n') results.write('Standard Deviation: ' + str(std) + '\n') results.close()
def __init__(self,H=None,T=None,numFreq=10001): self.sim = simulation.simulation() self.waves = wave.wave(H,T,numFreq) self.desiredRespAmp = 0.0 # [-] Desired response amplitude. M_d in documentation. self.waveHeightDesired = None # [m] Height of wave desired if renormalizing amplitudes # calculated variables self._RAO = None # [-] Complex RAO array N x 6 self._RAOdataReadIn = np.zeros(6,dtype=bool) # [-] What RAO dimensions did we read in? self._RAOdataFileName = ['','','','','',''] # [-] Name of the data file read in for RAO self._CoeffA_Rn = None # [ ] MLER coefficients A_{R,n} self._S = None # [m^2-s] Conditioned wave spectrum vector self._A = None # [m^2-s] 2*(conditioned wave spectrum vector) self._phase = 0.0 # [rad] Wave phase self._Spect = None # [-] Spectral info self._rescaleFact = None # [-] Rescaling factor for renormalizing the amplitude self._animation = None # Object storing animation information self._respExtremes = None # [m] Array containing min/max of the simulated response
def solveEquation(self): #constants d = 1.29 # kg/m^3 c = 1000 # kJ/kg*K k = 0.5 # W/m*degrees Celsius R = 0.96 # W/m*degrees Celsius i = 2 # number of walls inside room in 1 direction; 2*i is total number of walls TG = 80 #constant connected to room equipment for an ordinary house mk = self.airConditionerFlowRate.value() / 60 Tk = self.airConditionerTemp.value() Tin = self.temp_room.value() Tadj = self.temp_adjacent.value() Tout = self.temp_out.value() V = self.roomHeight.value() * self.roomWidth.value() * self.roomDepth.value() Qg = self.radiatorEfficiency.value() Np = self.peopleNumber.value() hi = self.externalWallThickness.value() hl = self.internalWallThickness.value() Ai = self.exteriorWallsNumberDepth.value() * self.roomDepth.value() * self.roomHeight.value() + self.exteriorWallsNumber.value() * self.roomWidth.value() * self.roomHeight.value() Al = (2 - self.exteriorWallsNumberDepth.value()) * self.roomDepth.value() * self.roomHeight.value() + (2 - self.exteriorWallsNumber.value()) * self.roomWidth.value() * self.roomHeight.value() windows = self.windowsList airCon=self.airConditioner.isChecked() radiator=self.radiator.isChecked() self.solver = solver(mk, Tk, Tin, V, d, c, Qg, Np, k, hi, hl, Tadj, Ai, Al, Tout, R, airCon,radiator,i,windows,TG) self.simulation = simulation(self.solver, self) if (self.temperatureControl.isChecked()): self.simulation.setDesiredTemperature(self.dailyTemperature.value()) self.simulation.setupUi() self.simulation.show() self.simulation.exec_()
def main(): while True: try: print('type "quit" to quit the program') shares = raw_input("a list of the number of shares to buy in parallel:e.g.[1, 10, 100, 1000]: ") if shares == 'quit': sys.exit(0) positions = positions_to_list(shares) break except EOFError: sys.exit(0) except KeyboardInterrupt: sys.exit(0) while True: try: trial = raw_input('number of trials? ') if trial == 'quit': sys.exit(0) num_trial = inputTrial_to_validTrial(trial) break except EOFError: sys.exit(0) except KeyboardInterrupt: sys.exit(0) f = open('results.txt', 'w') for i in positions: result = simulation(i, num_trial) result.present_result() f.write('position: ' + str(i) + ', mean = ' + str(result.get_mean()) + ', std = ' + str(result.get_std()) + "\r\n") f.close()
def main(): ''' Main function of the simulation. The positions is [1, 10, 100, 1000] and the number of trials is 10000 ''' try: positionInput = raw_input("Please input the positions set in such a format: '[1, 10, 100, 1000]' or there will be an exception: ") except: raise InvalidInput('There is something wrong with your input!') try: num_trials = input("Please input the number of trials(please just input number):") except: raise InvalidInput("There is something wrong with your input!") positions = parseInputPositions(positionInput) # simulate the different investment. investResult = simulation(positions, num_trials) # plot histogram for different position for position in positions: plt.figure() plt.hist(investResult[position], 100, range=[-1.0, 1.0], color='red') plt.xlabel('Daily Ret') plt.ylabel('Numbers') plt.title("Histogram of position-{}'s daily ret".format(position)) plt.savefig('histogram_{}_pos.pdf'.format(str(position).zfill(4))) # set up a file called 'result.txt' and save the mean and std of different position try: f = open('result.txt', 'w') f.write('position' + '\t' + 'mean' + '\t' + 'std' + '\n') for position in positions: f.write(str(position) + '\t' + str(np.array(investResult[position]).mean()) + '\t' + str(np.array(investResult[position]).std()) + '\n') f.close() except: print "There is something wrong with opening the file and writing into the file." print 'Assignment Done!'
def __init__(self): try: super(mainWindow, self).__init__() #init stuff self.current_window_width = DEFAULT_WIDTH self.current_window_height = DEFAULT_HEIGHT self.simulation = simulation(self.current_window_width, self.current_window_height, DEFAULT_RANDOM_AMOUNT) self.frame_times = [] for i in range(21): self.frame_times.append(time.clock()) #This is for the fps counter self.target_fps = DEFAULT_FPS self.old_mouse_pos = vector(0, 0) self.creating_leader = False self.creating_follower = False #init UI self.initUI() #start threads self.runThread = runProgram(self) self.runThread.start() self.paintThread = runPaint(self) self.paintThread.start() except: print "An error occurred in program initialization!" raise
def main(): '''This program stimulates each position, plot the results, store the means and standard deviations in a text file.''' position = [1, 10, 100, 1000] num_trials = 10000 results = open('results.txt','w') #open a file to store mean and standard deviation for position in position: daily_ret = simulation(position, num_trials) plt.figure() plt.hist(daily_ret, 100, range=[-1, 1]) plt.xlim(-1,1) plt.xlabel('Daily Return') plt.ylabel('Frequency in Number') plt.title('Daily Return of Position{}'.format(position)) plt.savefig('histogram_{}_pos.pdf'.format(str(position).zfill(4))) mean = np.mean(daily_ret) std = np.std(daily_ret) results.write('Position: ' + str(position) + '\n') results.write('Mean: ' + str(mean) + '\n') results.write('Standard Deviation: ' + str(std) + '\n') results.close()
import scipy.sparse as sparse import numpy as np import argparse as argparse from potential import potential from initialPsi import initialPsi parser = argparse.ArgumentParser(prog="python main.py", description = "main.py handles everything. Use python main.py -h to see your options."); parser.add_argument('-p', '--potential', help='Choose the form of the potential. 1: parabolic, 2: infinite wall, 3: finite walls, 4: ramp, 5: moving semi-circle, 6: constant.', default = 3, action='store', type = int); parser.add_argument('-w', '--waveFunc', help='Choose the form of psi. 1: gaussian, 2: parabola, 3: triangle, 4: sines/cosines.', default = 4, action='store', type = int); parser.add_argument('-tm', '--timemultiply', help='Speed up the animation with $value$. This multiplies the tau by $value$.', default = 1.0, action='store', type = float); parser.add_argument('-dm', '--dimensionmultiply', help='Multiply the number of dimensions by value.', default = 1, action='store', type = int); args = parser.parse_args(); sim = simulation() sim.hbar = scc.hbar sim.mass = scc.m_e sim.argsPotential = args.potential sim.dimensions = 1000 * args.dimensionmultiply sim.chi = 1e-9/sim.dimensions #just dx #1e-18 accounts for mass and the nm, while the sim.dimensions**-2 accounts for the parameters of the simulation. #The last number, 0.1 at the time of writing, is the timestep in the simulation in a way that makes sense. sim.tau = 1e-18 * (sim.dimensions)**(-2.0) * 4.0 * sim.mass / sim.hbar * 1.0e2 * args.timemultiply sim.init()
import sys import random import matplotlib.pyplot as plt import numpy as np import user_input as ui import simulation as si import draw_plot as dp if __name__ == "__main__": positions = ui.take_positions() num_trials = ui.take_num_trials() task = si.simulation(positions, num_trials) # creates a class of simulation result_file = open('results.txt', 'w') # create an empty txt file to write for position in positions: position_value = task.total_investment/position daily_ret = task.simulate_daily_return(position_value, num_trials) # saves the simulations of daily return in a list mean = np.mean(daily_ret) std = np.std(daily_ret) result_file.write('For position %d, mean is %f, standard deviation is %f.\n' %(position, mean, std)) # writes the numerical result into the txt file print '\nFor position %d, mean is %f, standard deviation is %f. \nResult is saved to results.txt' %(position, mean, std) # plot the simulation and save the plot.
first = 1 if first == 1:#Decision Rule Approch + Gene Rounding decisionSolver = decisionRule.decisionRule() #decisionSolver.echoInput() #decisionSolver.echoVal() decisionSolver.inputDemand(demander) decisionSolver.addVar() decisionSolver.addOpt() decisionSolver.addConstr() decisionSolver.solve() #decisionSolver.echoOpt() simulator = simulation.simulation(decisionSolver,demander) ''' realDemand = {} for i in range(0,3): realDemand[i] = demander.sim() opt = gene.gene(decisionSolver,simulator) opt.initX() opt.setSTD(realDemand) opt.evolve() ''' simulator.initX() print simulator.run(1000) #print simulator.bookLimRun(100,opt.X) elif first == 0:#reduction of Approximate Linear Programming
parametry = [5, 10, 3, 0.02] force_field2 = force_field.split("+") force = [] line = None for f in force_field2: f = f.split(",") f = [x.strip() for x in f] force.append(f[0]) for i in f[1:]: # print(i[1]) if i[0] == "L": l = float(i.split("=")[-1]) elif i[0] == "f": f = float(i.split("=")[-1]) elif i[0] == "e" and i[0] != "L": epsi = float(i.split("=")[-1]) elif i[0] == "R": r = float(i.split("=")[-1]) elif i[0] == "p": parametry = [] line = i.split("=") for l in line[-1].split(";"): parametry.append(float(l)) symulacja = simulation(potencjal=force, algorytm_calkujacy=algorytm, ilosc_atomow=atoms, output="wynik.pdb", ilosc_krokow=steps, dlugosc_kroku_czasowego=krok_czasowy, l=l, f=f, epsi=epsi, r=r, parametry=parametry, wymiar=wymiar) symulacja.run() rysuj()
import matplotlib.pylab as mtl import numpy as np import simulation as s1 import simulation2 as s2 import simulation3 as s3 l1 = [] l2 = [] l3 = [] for i in range(10**4): l1.append(s1.simulation()) l2.append(s2.simulation()) l3.append(s3.simulation()) #mtl.axis([0,10,0,0.6]) mtl.title('Comparacion entre los tres sistemas') mtl.xlabel('Tiempo en meses') mtl.ylabel('Frecuencia observada') #mtl.grid(True) mu1, sigma1 = 1.751, 1.604 mu2, sigma2 = 2.582, 2.459 mu3, sigma3 = 3.597, 3.326 #mtl.text(7, .4, '$\mu=1.751$', size = 25) #mtl.text(7, .34, '$\sigma=1.604$', size=25) mtl.hist(l1,100,normed=1 ,facecolor='blue',alpha=0.4, ) mtl.hist(l2,100,normed=1,facecolor='orange',alpha=0.4, ) mtl.hist(l3,100,normed=1,facecolor='green',alpha=0.4)
def clearSimulation(self): self.simulation = simulation(self.current_window_width, self.current_window_height, 0) self.fps_slider.setValue(0) self.resetButtons()