def letsGetThisPartyStarted(params=None): if params==None: #print("No parameters passed when party getting started. Using defaults.") s = simulation([]) else: #print("Parameters passed in to get a party started! Indeed, params = " + str(params)) s = simulation(params) s.runSim()
def main(): ''' Generating input and plotting the graphs for the given positions list, as well as writing statistics to the document---'result.txt'. ''' #Take inputs from the users, but the graphs are generated with given position list while True: try: position = raw_input("Please type a list of positions you'd like to invest") position = position.strip('[()]').split(',') positions = [] #Raise exception if invalid input appears for position in position: positions.append(int(position)) break except: raise invalidInputException while True: try: num_trial = int(raw_input('Please enter the number of trials')) break except: raise invalidInputException return_list = simulation(positions, num_trial) #If there's an error with output file outputF = open('result1.txt', 'w') for i in range(len(return_list)): mean = np.mean(return_list[i]) std = np.std(return_list[i]) outputF.write("Position is " + str(positions[i]) + '\n') outputF.write("The mean of the return is " + str(mean)+ ', ' + "and the standard deviation is " + str(std)+"\n") outputF.flush() outputF.close() #Generating graphs for the given positions target = [1,10,100,1000] sample = simulation(target,10000) for i in range(len(sample)): plt.hist(sample[i], 100, range=[-1,1]) plt.savefig("histogram_" + str(target[i])+ "_pos.pdf") plt.close('all')
def test_get_simulation_ret(self): test_iii = simulation([1, 10],1000) test_iii.get_simulation() self.assertTrue(all(x <=1 for x in test_iii.diff_posit_ret[1])) self.assertTrue(all(x >= -1 for x in test_iii.diff_posit_ret[1])) self.assertTrue(all(x <=1 for x in test_iii.diff_posit_ret[10])) self.assertTrue(all(x >= -1 for x in test_iii.diff_posit_ret[10]))
def test_get_simulation_ret(self): test_iii = simulation([1, 10], 1000) test_iii.get_simulation() self.assertTrue(all(x <= 1 for x in test_iii.diff_posit_ret[1])) self.assertTrue(all(x >= -1 for x in test_iii.diff_posit_ret[1])) self.assertTrue(all(x <= 1 for x in test_iii.diff_posit_ret[10])) self.assertTrue(all(x >= -1 for x in test_iii.diff_posit_ret[10]))
def main(): pygame.init() pygame.mixer.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Animat-Based Modelling') clock = pygame.time.Clock() predator_learn = True prey_learn = True myfont = pygame.font.SysFont("monospace", 16) simulation(predator_learn, prey_learn) running = True while running: clock.tick(FPS) #process event for event in pygame.event.get(): if event.type == pygame.QUIT: running = False #update all_sprites.update() #draw screen.fill(Black) all_sprites.draw(screen) preytext = myfont.render( "Number of Pac-Man Dead: {0}".format(Prey.death), 1, (255, 255, 255)) screen.blit(preytext, (5, 10)) predatortext = myfont.render( "Number of Monster Dead: {0}".format(Predator.death), 1, (255, 255, 255)) screen.blit(predatortext, (5, 30)) posionfoodtext = myfont.render( "Number of Poisonous Food Eaten: {0}".format(Food.poison_eaten), 1, (255, 255, 255)) screen.blit(posionfoodtext, (5, 50)) normalfoodtext = myfont.render( "Number of Normal Food Eaten: {0}".format(Food.normal_eaten), 1, (255, 255, 255)) screen.blit(normalfoodtext, (5, 70)) pygame.display.flip() pygame.quit()
def report(self): print "=" * 70 print "generation: ", self.generation print "best: ", self.best s = simulation(show=True) s.individual_sim((self.best.chromosome[0], self.best.chromosome[1]), self.best.chromosome[2], self.best.chromosome[3], self.best.chromosome[4], self.best.chromosome[5], self.best.chromosome[6], self.best.chromosome[7], self.best.chromosome[8], self.generation, 0)
def plotting(file_name): x, results, analysis_type = simulation(file_name) v_node = [] if type(results[0]) == float: pass else: ind = len(results[0]) - 1 AMP = [] PHASE = [] #plot different curves based on analysis type if analysis_type[0] == 'op': pass elif analysis_type[0] == 'dc': if type(results[0]) == float: plt.title('dc sweep') plt.plot(x, results) plt.show() else: while ind != -1: for r in results: v_node.append(r[ind]) plt.title('dc sweep') plt.plot(x, v_node) plt.show() v_node = [] ind = ind - 1 elif analysis_type[0] == 'ac': while ind != -1: for r in results: v = r[ind] amplitude = math.sqrt((np.real(v))**2 + (np.imag(v))**2) AMP.append(amplitude) phase = np.angle(v) PHASE.append(phase) plt.figure(ind) plt.subplot(121) plt.title('Amplitude') plt.plot(x, AMP) plt.subplot(122) plt.title('Phase') plt.plot(x, PHASE) plt.show() ind = ind - 1 AMP = [] PHASE = [] elif analysis_type[0] == 'tran': while ind != -1: for r in results: v_node.append(r[ind][0]) plt.plot(x, v_node) plt.show() v_node = [] ind = ind - 1
def test_maximum_eigenvalue_is_1(self): bins = np.random.randint(0, 100) this = simulation() this.unbound = flat(bins) this.bound = flat(bins) this.catalytic_rate = 0 this.simulate() maximum_eigenvalue = this.eigenvalues[this.eigenvalues.argmax()] self.assertAlmostEqual(maximum_eigenvalue, 1, places=7, msg='Maximum eigenvalue is not 1.')
def test_flux_is_zero_with_no_potential(self): bins = np.random.randint(0, 100) this = simulation() this.unbound = flat(bins) this.bound = flat(bins) this.catalytic_rate = 0 this.simulate() flux = np.mean(this.flux_u + this.flux_b) self.assertAlmostEqual( flux, 0, places=2, msg='Flux is nonzero for zero potential surface.')
def newrandomworld(numderps,mapsize,startsize): # (self,foodlevel,xco,yco,newspeed,species_id,childSize,healthySize,worldsize) creatures = [] for i in range (numderps): x = random.randint(0,mapsize-1); y = random.randint(0,mapsize-1); creatures.append(herbivore(10,x,y,1,0,10,20,mapsize)) simworld = randomworld(mapsize) simworld.addamountfood(int(startsize/100),startsize) a = simulation(simworld,creatures) a.maxfood = startsize return a
def main(): while True: try: shares_input_str = '' trials_input_str = '' while not valid_share_str(shares_input_str): shares_input_str = input( "Please enter a list of 4 integers separated by commas as number of shares to buy in parallel\n" ) shares_input_str = rm_ws(shares_input_str) while not valid_trial_str(trials_input_str): trials_input_str = input( "Please enter the number of simulation trials\n") trials_input_str = rm_ws(trials_input_str) positions = [int(string) for string in shares_input_str.split(",")] num_trials = int(trials_input_str) this_simu = simulation(positions, num_trials) this_simu.simulate() # Run the simulation cumu_ret = this_simu.simulate_results # Collect the simulated results daily_ret = (cumu_ret / 1000) - 1 result_file = open('results.txt', 'w') for ii in np.arange(len(positions)): this_plot_data = daily_ret[:, ii] this_position_int = positions[ii] plot_simulation(this_plot_data, this_position_int) this_mean = np.mean(this_plot_data) this_std = np.std(this_plot_data) write_simulation(result_file, this_position_int, this_mean, this_std) result_file.close() print('results.txt saved.') break except KeyboardInterrupt: exit('Program terminated') except: pass exit('Program finished.')
def main(): while True: try: shares_input_str = '' trials_input_str = '' while not valid_share_str(shares_input_str): shares_input_str = input("Please enter a list of 4 integers separated by commas as number of shares to buy in parallel\n") shares_input_str = rm_ws(shares_input_str) while not valid_trial_str(trials_input_str): trials_input_str = input("Please enter the number of simulation trials\n") trials_input_str = rm_ws(trials_input_str) positions = [int(string) for string in shares_input_str.split(",")] num_trials = int(trials_input_str) this_simu = simulation(positions,num_trials) this_simu.simulate() # Run the simulation cumu_ret = this_simu.simulate_results # Collect the simulated results daily_ret = (cumu_ret/1000) - 1 result_file = open('results.txt', 'w') for ii in np.arange(len(positions)): this_plot_data = daily_ret[:,ii] this_position_int = positions[ii] plot_simulation(this_plot_data, this_position_int) this_mean = np.mean(this_plot_data) this_std = np.std(this_plot_data) write_simulation(result_file, this_position_int, this_mean, this_std) result_file.close() print('results.txt saved.') break except KeyboardInterrupt: exit('Program terminated') except: pass exit('Program finished.')
def main(): """This program simulates each position, plots histogram of daily return and creates a file containing mean and standard variance """ position = [1, 10, 100, 1000] num_trials = 10000 result = simulation(position, num_trials) f = open('results.txt', 'w') # open a file to write for x in position: mean = np.mean(result[str(x)]) std = np.std(result[str(x)]) f.write('Position is: '+str(x)+'\n') f.write('Mean: '+str(mean)+ ' Std: '+str(std)+'\n') f.flush() plt.figure() plt.hist(result[str(x)], 100, range = [-1, 1]) plt.savefig('histogram_'+str(x).zfill(4)+'_pos.pdf', format = 'pdf', dpi = 72) f.close()
def test_ss_is_boltzmann(self): bins = 4 this = simulation() this.unbound = np.random.rand(bins) this.bound = np.random.rand(bins) this.unbound /= np.sum(this.unbound) this.bound /= np.sum(this.bound) this.catalytic_rate = 0 this.offset_factor = 0 # Both surfaces should have equal probability this.cSubstrate = 1 this.ss[bins:] /= this.ss[bins:] this.simulate() unbound_difference = abs(this.ss[0:bins]) - abs(this.PDF_unbound) bound_difference = abs(this.ss[bins:]) - abs(this.PDF_bound) difference = np.sum(unbound_difference) + np.sum(bound_difference) self.assertAlmostEqual( difference, 0, places=3, msg='Steady state differs from Boltzmann in equilibrium.')
def simulate(file_name, text): x, results, analysis_type = simulation(file_name) if analysis_type[0] == 'op': print_op = open('op_points.txt', 'r') while True: line = print_op.readline() if len(line) == 0: break else: text.insert(END, line) print_op.close() elif analysis_type[0] == 'dc': print_dc = open('output_dc.txt', 'r') while True: line = print_dc.readline() if len(line) == 0: break else: text.insert(END, line) print_dc.close() elif analysis_type[0] == 'ac': print_ac = open('output_ac.txt', 'r') while True: line = print_ac.readline() if len(line) == 0: break else: text.insert(END, line) print_ac.close() elif analysis_type[0] == 'tran': print_tran = open('output_tran.txt', 'r') while True: line = print_tran.readline() if len(line) == 0: break else: text.insert(END, line) print_tran.close()
def main(): """ Main function that simulate through the position [1,10,100,100] and plot the histograms of daily return. The function will simulate 10000 trials for each position to get the results and then store it in a text file. """ file_txt = open('results.txt','w+') positions = [1,10,100,1000] num_trials = 10000 # Simulate the investment and plot histogram for different positions for position in positions: daily_ret = simulation(position, num_trials) plt.figure() plt.hist(daily_ret, 100, range=[-1,1]) plt.title('The histogram of daily return for position ={}'.format(position)) plt.xlabel('Daily return') plt.ylabel('The number of trials') plt.savefig('histogram_{}_pos.pdf'.format(str(position).zfill(4))) # Save the results of the simulation into a txt file file_txt.write('Position: {}\n'.format(position)) file_txt.write('Mean: {}; Std: {}\n'.format(np.mean(daily_ret),np.std(daily_ret))) file_txt.write('\n') file_txt.close()
def main(): """This program simulates each position, plots histogram of daily return and creates a file containing mean and standard variance """ position, num_trials = superinput() result = simulation(position, num_trials) try: f = open('results.txt', 'w') # open a file to write except: print "Fail to open a file called 'result.txt' for output" sys.exit() for x in position: mean = np.mean(result[str(x)]) std = np.std(result[str(x)]) f.write('Position is: ' + str(x) + '\n') f.write('Mean: ' + str(mean) + ' Std: ' + str(std) + '\n') f.flush() plt.figure() plt.hist(result[str(x)], 100, range=[-1, 1]) plt.savefig('histogram_' + str(x).zfill(4) + '_pos.pdf', format='pdf', dpi=72) f.close()
for L in [2]: for lambd in [0.01, 0.99]: dim_loc = 4 n_dis = 100 simdict = {'dim_loc': dim_loc, 'L': L, 'n_dis': n_dis} phi = np.pi / 3 eps = 0.1 time_set = np.power(2, np.arange(40)) idata={'JZZ': 1.0, 'hZ': 1.0, 'hX': 1.0, 'alphas': np.array([(1-lambd)*np.exp(1j*phi)/2, 1, (1-lambd)*np.exp(-1j*phi)/2]),\ 'betas': np.array([eps,lambd, eps]), 'lambdas': np.array([eps,1,eps]),\ 'phi': phi, 'lambd': lambd} filename = 'clock4/clock4_%d_%.2f.txt' % (L, lambd) clockH, clockK, clockZ = clock(dim_loc, L) Z_mean, Z_var, Y_mean, Y_var, spectral_data, spectral_data_var = simulation( dim_loc, L, n_dis, idata, clockH, clockK, clockZ, time_set) with open(filename, 'wb') as f: for key, value in simdict.items(): f.write(('\n# ' + key + ' ' + str(value)).encode('utf-8')) for key, value in idata.items(): f.write(('\n# ' + key + ' ' + str(value)).encode('utf-8')) for i in range(7): f.write(('\n# ' + spec_names[i] + ' ' + str(spectral_data[i]) + ' ' + str(spectral_data_var[i])).encode('utf-8')) f.write('\n# time\tRe(Z)\Im(Z)\tVar(Re(Z))\tVar(Im(Z))\n'.encode( 'utf-8')) np.savetxt(f, np.stack((time_set, np.real(Z_mean), np.imag(Z_mean),\ np.real(Z_var), np.imag(Z_var), np.real(Y_mean), np.imag(Y_mean),\ np.real(Y_var), np.imag(Y_var)), axis=-1))
'Valid numbers to input are 1,10,100 and 1000\n') positions = pos_num.split() for i, position in enumerate(positions): positions[i] = int(position) break except EOFError: sys.exit(1) except KeyboardInterrupt: sys.exit(2) while True: try: num_trials = int( raw_input('How many times to randomly repeat the test?\n')) break except ValueError: print('Invalid number!') except EOFError: sys.exit(3) except KeyboardInterrupt: sys.exit(4) f = open('results.txt', 'w') for i in positions: s = simulation(i, num_trials) f.write('Position: ' + str(i) + ', Mean: ' + str(s.mean) + ', Std: ' + str(s.std) + "\r\n") s.histogram('Histogram_' + str(i) + '_pos.pdf') f.close()
from simulation import * def ScalePlot(h): h.Scale(1./h.Integral()) #inputDir = "/home/mfiascar/Physics/Accelerator/Simulation/FCC/TOY_V1/HaloDist" inputDir = "/home/mfiascar/Physics/Accelerator/Simulation/HL-LHC/v1.0/HorizB1_onlyIR7_thicktothin_noLossMaps/" sim = simulation(inputDir) infile = TFile.Open(sim.Directory + "Coll_Scatter.root") t = infile.Get("ntuple") nmax = 1000000 #t.GetEntries() h_intType = TH1F("h_intType","h_intType",6,0.,6.) h_fi_intType_vs_dp = TH2F("h_firstImpact_intType_vs_dp","h_firstImpact_intType_vs_dp",6,0.,6.,100,0.,1.01) #relative dx (x=b) h_fi_intType_vs_dxp = TH2F("h_firstImpact_intType_vs_dxp","h_firstImpact_intType_vs_dxp",6,0.,6.,200,-2.e-5,2.e-5) #relative dxp (x=b) h_fi_intType_vs_dyp = TH2F("h_firstImpact_intType_vs_dyp","h_firstImpact_intType_vs_dyp",6,0.,6.,200,-2.e-5,2.e-5) #relative dxp (x=b) h_abs_icoll = TH1F("h_abs_icoll","h_abs_icoll",20,1,21) h_nTurn_absorption = TH1F("h_nTurn_fromFirstImpact_to_absorption","h_nTurn_fromFirstImpact_to_absorption",200,0,200) h_nTurn_absorption_icoll = TH2F("h_nTurn_fromFirstImpact_to_absorption_vs_icoll","h_nTurn_fromFirstImpact_to_absorption_vs_icoll",200,0,200,20,1,21) h_nPassagesTCP_absorbedTCP = TH1F("h_nPassagesTCP_absorbedTCP","h_nPassagesTCP_absorbedTCP",20,0,20) h_nPassagesTCP_absorbedOther = TH1F("h_nPassagesTCP_absorbedOther","h_nPassagesTCP_absorbedOther",20,0,20) turnOld = 0 firstImp = {} for i in range(nmax):
def test_get_simulation_len(self): test_ii = simulation([100, 10], 2000) test_ii.get_simulation() self.assertEqual(len(test_ii.diff_posit_ret[100]), 2000) self.assertEqual(len(test_ii.diff_posit_ret[10]), 2000)
def test_std(self): s3 = simulation(100, 10000) s4 = simulation(1000, 10000) self.assertTrue(abs(s3.std - 0.099479648391) < 0.01) self.assertTrue(abs(s4.std - 0.03175307467) < 0.01)
from simulation import * try: directory except NameError: directory = "/home/mfiascar/Physics/Accelerator/Simulation/HL-LHC/v1.0/HorizB1" #read input and make all root files with plots sim = simulation(directory) sim._print() sim._print_betafunctions() sim.nsigmaColl() sim._makeLayout_() sim.makeLossPlots() #sim.efficiency() sim.dispersion() #inputDir = directory + "/plots" #execfile("scripts/makePlot.py")
try: pos_num = raw_input('A list of number of shares to buy in parallel? ' 'Valid numbers to input are 1,10,100 and 1000\n') positions = pos_num.split() for i, position in enumerate(positions): positions[i] = int(position) break except EOFError: sys.exit(1) except KeyboardInterrupt: sys.exit(2) while True: try: num_trials = int(raw_input('How many times to randomly repeat the test?\n')) break except ValueError: print('Invalid number!') except EOFError: sys.exit(3) except KeyboardInterrupt: sys.exit(4) f = open ('results.txt','w') for i in positions: s = simulation(i, num_trials) f.write('Position: ' + str(i) + ', Mean: ' + str(s.mean)+ ', Std: ' + str(s.std) + "\r\n") s.histogram('Histogram_' + str(i) + '_pos.pdf') f.close()
from simulation import * # import warnings # warnings.filterwarnings("ignore") simulation(100, 10)
# Copyright (c) 2016 Jacob Marks ([email protected]) # # This file is part of QTop. # # QTop is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. from common import * from surface_codes import * from color_codes import * from error_models import * from decoders import mwpm from visualization import * from threshold import * from simulation import * ################## Surface Code Simulation ################## # model = CodeCapacity() model = Depolarizing() decoder = mwpm.MWPM_decoder() sim = simulation(2, 'Surface Code', [model, 'Depolarizing Channel'], [decoder, 'MWPM'], './') L_vals = [7,9] p_vals = np.linspace(.13,.18,10) num_trials = 3000 run(sim, L_vals, p_vals, num_trials)
# # Copyright (c) 2016 Jacob Marks ([email protected]) # # This file is part of QTop. # # QTop is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. from common import * from surface_codes import * from color_codes import * from error_models import * from decoders import mwpm from visualization import * from threshold import * from simulation import * ################## Surface Code Simulation ################## # model = CodeCapacity() model = Depolarizing() decoder = mwpm.MWPM_decoder() sim = simulation(2, 'Surface Code', [model, 'Depolarizing Channel'], [decoder, 'MWPM'], './') L_vals = [7, 9] p_vals = np.linspace(.13, .18, 10) num_trials = 3000 run(sim, L_vals, p_vals, num_trials)
def test_initial(self): test_i = simulation([1, 10], 1000) self.assertEqual(test_i.position, [1, 10]) self.assertEqual(test_i.numb, 1000)
def test_mean(self): s1 = simulation(10, 10000) s2 = simulation(100, 10000) self.assertTrue(abs(s1.mean - 0.01588) < 0.01) self.assertTrue(abs(s2.mean - 0.021166) < 0.01)
except EOFError: sys.exit() #handle exceptions for input of list of positions. while (True): try: numb_str = input( "Enter a valid number for simulation, and enter quit to exit: " ) #prompt users to enter a valid number for simulations if numb_str == 'quit': sys.exit() num_trials = correct_input_numb(numb_str) break except inputError: print( "Incorrect input! Please reenter a valid number for simulation!" ) except KeyboardInterrupt: sys.exit() except EOFError: sys.exit() #handle exceptions for invalid input of number of simulations print( 'reults.txt and histograms for different positions are being generated' ) stimulation_initial = simulation(positions, num_trials) #generate simulations stimulation_initial.get_simulation() #generate histograms and txt stimulation_initial.get_txt_hist()
def test_initial(self): test_i = simulation([1, 10],1000) self.assertEqual(test_i.position,[1, 10]) self.assertEqual(test_i.numb, 1000)
with open(filename, 'wb') as f: for key, value in simdict.items(): f.write(('\n# ' + key + ' ' + str(value)).encode('utf-8')) for key, value in idata.items(): f.write(('\n# ' + key + ' ' + str(value)).encode('utf-8')) # for i in range(7): # f.write(('\n# '+spec_names[i]+' '+str(spectral_data[i])+\ # ' '+str(spectral_data_var[i])).encode('utf-8')) #f.write('\n# time\tRe(Z)\Im(Z)\tVar(Re(Z))\tVar(Im(Z))\n'.encode('utf-8')) #f.write('\n# time\tRe(Z)\Im(Z)\tVar(Re(Z))\tVar(Im(Z))\n'.encode('utf-8')) f.write(('\n# eps\tgap\tshifted_gap\tshifted_gap_2\tlog10_gap\t'+\ 'log10_shifted_gap\tlog10_shifted_gap_2\tratio\n').encode('utf-8')) for eps in np.exp(np.linspace(-7, -0.5, 12)): idata['betas'] = np.array([eps, lambd, eps]) idata['lambdas'] = np.array([eps, 1, eps]) clockH, clockK, clockZ = clock(dim_loc, L) Z_mean, Z_var, Y_mean, Y_var, spectral_data, spectral_data_var =\ simulation(dim_loc, L, n_dis, idata, clockH, clockK, clockZ) with open(filename, 'ab') as f: np.savetxt( f, np.array([ np.concatenate( ([eps], spectral_data, spectral_data_var)) ])) #np.savetxt(f, np.stack((time_set, np.real(Z_mean),\ # np.imag(Z_mean), np.real(Z_var), np.imag(Z_var), \ # np.real(Y_mean), np.imag(Y_mean),\ # np.real(Y_var), np.imag(Y_var)), axis=-1))
def test_get_simulation_len(self): test_ii = simulation([100, 10],2000) test_ii.get_simulation() self.assertEqual(len(test_ii.diff_posit_ret[100]),2000) self.assertEqual(len(test_ii.diff_posit_ret[10]),2000)
positions=correct_input_position(input_str) break except inputError: print("Incorrect input! Please reenter a valid list of positions!") except KeyboardInterrupt: sys.exit() except EOFError: sys.exit() #handle exceptions for input of list of positions. while(True): try: numb_str=input("Enter a valid number for simulation, and enter quit to exit: ") #prompt users to enter a valid number for simulations if numb_str=='quit': sys.exit() num_trials=correct_input_numb(numb_str) break except inputError: print("Incorrect input! Please reenter a valid number for simulation!") except KeyboardInterrupt: sys.exit() except EOFError: sys.exit() #handle exceptions for invalid input of number of simulations print('reults.txt and histograms for different positions are being generated') stimulation_initial=simulation(positions,num_trials) #generate simulations stimulation_initial.get_simulation() #generate histograms and txt stimulation_initial.get_txt_hist()