def compare_handle(): src1 = f3entry.get("1.0", "end-1c") src2 = f3entry2.get("1.0", "end-1c") left_complex = fn.equation_finder(src1) right_complex = fn.equation_finder(src2) if left_complex[1] == '': left_complex[1] = "1" if right_complex[1] == '': right_complex[1] = '1' if left_complex[0] > right_complex[0]: messagebox.showinfo( "Well WEll WELL...", f"It seems 'Second' algorithm is better.\n {left_complex[0]} > {right_complex[0]}" ) elif left_complex[0] < right_complex[0]: messagebox.showinfo( "Well WEll WELL...", f"It seems 'First' algorithm is better.\n {left_complex[0]} < {right_complex[0]}" ) else: messagebox.showinfo( "Well WEll WELL...", f"It seems order of both algorithms are equal to {left_complex[0]}" ) root.destroy() time.sleep(0.5) fn.plot(left_complex[1], right_complex[1])
def doPath(path): #Checks if the folder is well formated, if not, it is formated well if path[len(path) - 1] != '/': path = path + '/' means = [] integrals = [] maximums = [] files = utils.getFiles(path) for f in files: if '.txt' in f: m = doExercice(path + f) integrals.append(m["integral"]) if m['integral'] < 0.: functions.plotMatrix(m, f) print f means.append(m["mean"]) maximums.append(m["max"]) #nextGraph() else: #TODO format .trc files print "The file " + path + f + " is not allowed in this version" mhist, ma, mi, bins = functions.histogram(means) covariance = functions.fitting(mhist, ma, mi, bins) inte = functions.getValidIntegrals(integrals, means, maximums, covariance) if len(inte) > 0: ihist, ma, mi, bins = functions.histogram(inte) functions.plot(ihist, ma, mi, bins)
def task_2_1_2(): print("\n\nStart task 2.1.2") train_dataset = dl.load_from_csv(train_files[0], 1) train_io_array = functions.create_io_arrays(train_dataset, True) weights = functions.find_ols(train_io_array[0], train_io_array[1]) test_dataset = dl.load_from_csv(test_files[0], 1) line = functions.create_linreg_line(test_dataset, weights) functions.plot(train_dataset, test_dataset, line) print("End task 2.1.2")
def run(n, group_path, plotFlag, saveFlag): # Loading setups configurations config = setup() #rm-list_resources() to find address for smu address_2612b = 26 address_2400 = 24 clear_all() #running tests (smua measures iv and smub measures r) [smu_2612b, smu_2400, rm] = gpib(address_2612b, address_2400) [readingsV_sipm, readingsI_sipm, readingsV_led, readingsI_led, readingsR] = SelfHeating(smu_2612b, smu_2400, config[0], config[1], config[2], config[3], config[4], config[5], config[6], config[7], config[8], config[9], config[10], config[11], config[12], config[13], config[14], config[15], config[16], config[17], config[18], config[19], config[20], config[21]) smu_2612b.write('reset()') smu_2612b.write('smua.nvbuffer1.clear()') smu_2612b.write('smub.nvbuffer1.clear()') smu_2400.write('*CLS') rm.close Number = [] led_power = [] for i in range(0, len(readingsR)): Number.append(i) led_power.append(readingsV_led[i] * readingsI_led[i]) if plotFlag == 1: graphR = plot(Number, readingsR, 'N', 'R', 1) graphIV = plot(readingsI_led, readingsI_sipm, 'Iled', 'Isipm', 2, log=True, errorbars_2612=True) graphIVLed = plot(readingsV_led, readingsI_led, 'Vled', 'I', 3) else: graphR = 'NULL' graphIV = 'NULL' if saveFlag == 1: save(readingsV_sipm, readingsI_sipm, readingsV_led, readingsI_led, readingsR, graphIV, graphR, n, group_path) return
def calc_handle(): user_input = f2entry.get("1.0", "end-1c") complexity = fn.equation_finder(user_input) messagebox.showinfo( "TADDDDDAAAAAAAAAAAAA", f"(BIG O notation): {complexity[0]}\n" f"click OK to sketch the graph") root.destroy() time.sleep(0.5) if complexity[1] == '': fn.plot(1) elif 1 < int(complexity[1]) < 10: fn.plot(complexity[1]) else: print("Not able to plot, power > 9")
def evaluate(path, scale, model): img = cv2.imread(path) lr = make_lr(img, factor) low = cv2.cvtColor(lr, cv2.COLOR_RGB2YCrCb) y, cr, cb = cv2.split(low) y = np.expand_dims(y, axis=0) y = np.expand_dims(y, axis=-1) pred = np.squeeze(model.predict(y)) pred = postprocess(pred).astype(np.uint8) pred = cv2.merge((pred, cr, cb)) pred = cv2.cvtColor(pred, cv2.COLOR_YCrCb2RGB) pred = postprocess(pred) result = psnr(img, pred) print('predicted psnr:', result) print('lr psnr:', psnr(lr, img)) plot(pred)
def find_min(old_features, function, life_time, feature_range, num_of_children, speed_parameter, sensivity, smart_mutation=False): new_features = copy.deepcopy(old_features) print(new_features) init_results = np.average(f.evaluate(old_features, function)) old_generation_results = init_results print(f.evaluate(old_features, function)) print('init results: ', init_results) History = [] find_max = False for year in range(life_time): # print(year) if smart_mutation == True: new_features, old_features = f.run_genetic_algorithm_with_smart_mutation( new_features, old_generation_results, function, feature_range, num_of_children, sensivity=sensivity, find_max=find_max) else: old_features = f.run_genetic_algorithm(old_features, function, feature_range, num_of_children, speed_parameter, year, sensivity=sensivity, find_max=find_max) old_generation_results = f.evaluate(old_features, function) result = np.average(old_generation_results) History.append(result) print('done!') print('final result', np.average(old_generation_results)) f.plot(History) return new_features
def find_max(features, function, life_time, feature_range, num_of_children, speed_parameter): init_results = np.average(f.evaluate(features, function)) print(f.evaluate(features, function)) print('init results: ', init_results) History = [] find_max = True for year in range(life_time): # print(year) features = f.run_genetic_algorithm(features, function, feature_range, num_of_children, speed_parameter, year, find_max) old_generation_results = f.evaluate(features, function) result = np.average(old_generation_results) History.append(result) print('done!') print('final result', np.average(old_generation_results)) f.plot(History)
def main(): # get arguments regularization, feature_type, path = functions.read_argv() epochs, mini_batch_size = 200, 10000 stop_criteria = 0.0005 # get data train_data = functions.read_gz_idx(path+'train-images-idx3-ubyte.gz') train_label = functions.read_gz_idx(path+'train-labels-idx1-ubyte.gz') test_data = functions.read_gz_idx(path+'t10k-images-idx3-ubyte.gz') test_label = functions.read_gz_idx(path+'t10k-labels-idx1-ubyte.gz') # data preprocessing train_data, train_label, test_data, test_label = data_preprocess(train_data, train_label, test_data, test_label, feature_type) # model initialization model = StochasticGradientDescent(len(train_data[0]), regularization, mini_batch_size) # initialize list for plotting accuracy_train = [] accuracy_test = [] # start training prev_loss = 0 # for stopping criteria epoch = epochs # for plotting for e in range(epochs): # shuffle training data if batch if mini_batch_size == len(train_data): train_data, train_label = functions.unison_shuffle(train_data, train_label) # model fitting loss = model.fit(train_data, train_label, 0) # test the accuracy acc_train = functions.accuracy(model.classify(train_data), train_label)/100 acc_test = functions.accuracy(model.classify(test_data), test_label)/100 # record for plotting accuracy_train.append(acc_train) accuracy_test.append(acc_test) # log print ("epoch {0:3d}:\t Train loss: {1:8.4f},\t Train acc: {2:8.4f}, \tTest acc: {3:8.4f}".format( e+1, loss, acc_train, acc_test)) # stopping criteria if np.absolute(prev_loss-loss)<stop_criteria: epoch = e+1 break prev_loss = loss print ('End of Train & Test') print ('Plotting ... ') # plot to graph if regularization: title = 'GD Regularize '+feature_type else: title = 'GD '+feature_type functions.plot(title, [e for e in range(1, epoch+1)], accuracy_train, accuracy_test) print ("End Of The Program")
def run(n, test, group_path, plotFlag, saveFlag): clear_all() # Loading setups configurations config = setup() #rm-list_resources() to find address for smu address_2612b = 26 #running tests (smua measures iv and smub measures r) [smu_2612b, rm] = gpib(address_2612b) [readingsV_sipm, readingsI_sipm] = IVComplete(smu_2612b, config) readingsV_sipm_neg, readingsV_sipm_pos, readingsI_sipm_neg, readingsI_sipm_pos = split( readingsV_sipm, readingsI_sipm) if plotFlag == 1: graphIV_neg = plot(readingsV_sipm_neg, readingsI_sipm_neg, 'Vsipm', 'Isipm', 1, log=False, errorbars_2612=True) graphIV_pos = plot(readingsV_sipm_pos, readingsI_sipm_pos, 'Vsipm', 'Isipm', 2, log=False, errorbars_2612=True) else: graphIV_neg = 'NULL' graphIV_pos = 'NULL' if saveFlag == 1: group_path_pos = group_path + " (rq)" group_path_neg = group_path + " (vbr)" save_iv(readingsV_sipm_neg, readingsI_sipm_neg, graphIV_neg, n, group_path_pos) save_iv(readingsV_sipm_pos, readingsI_sipm_pos, graphIV_pos, n, group_path_neg) time.sleep(0) readingsI_sipm_dark = DarkCurrent(smu_2612b, config) number = [] for g in range(len(readingsI_sipm_dark)): number.append(g) if plotFlag == 1: graphIV = plot(number, readingsI_sipm_dark, 'N', 'Isipm', 3, log=False, errorbars_2612=True) else: graphIV = 'NULL' if saveFlag == 1: group_path_dark = group_path + " (idark)" save_dark(readingsI_sipm_dark, graphIV, n, group_path_dark) [readingsI_sipm_led, readingsI_led, readingsV_led] = LEDTest(smu_2612b, config) if plotFlag == 1: graphIV_led = plot(readingsI_led, readingsI_sipm_led, 'Iled', 'Isipm', 4, log=True, errorbars_2612=True, xflag='I') else: graphIV_led = 'NULL' if saveFlag == 1: group_path_dark = group_path + " (LED)" save_led(readingsI_sipm_led, readingsI_led, readingsV_led, graphIV_led, n, group_path_dark) rm.close return
wkdys = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] weekdays = sleep[sleep['Weekday'].isin(wkdys)] weekdays.sort_index(inplace = True) #Mean relations of weekends avgweekends = (round(weekends['Hours of Sleep'].mean(), 2)) moodweekends = (round(weekends['Hours of Sleep'].mean(), 2)) #Mean relations of weekdays avgweekdays = (round(weekdays['Hours of Sleep'].mean(), 2)) moodweekdays = (round(weekdays['Hours of Sleep'].mean(), 2)) ############################### DATA ANALYSING COMPLETE ######################################################### print('Project CIRCAN') print('Analysis successful') if devsleep > (1.5) or avgsleep < (7.50): print('You do not have a consistent number of hours of sleep.') elif devsleep < (1.5) and avgsleep > (7.50): print('Congratulations! You have quite the healthy sleep routine!') x = float(input("For an overall sleep analysis of all days, press 1. For a customized analysis of a chosen interval, press 2. To exit, press 3. ")) if x == 1: plot() elif x == 2: custom() else: print('Thank you. Hope you have a great day!')
if __name__ == "__main__": from functions import make_circle # units are microns dx = 0.6 dy = 0.6 Lx_max = 1000 Ly_max = 1000 wavelength = .6 alpha = .1 beta = .1 z = 1000 plane_wave = create_plane_wave(dx, dy, Lx_max, Ly_max, alpha, beta, wavelength) mat2D, extent, F_mat2D, F_extent = make_circle( dx=dx, dy=dy, Lx_max=Lx_max, Ly_max=Ly_max, a=.005, # stretch in x b=.005, # stretch in y ) plot(plane_wave, extent) plot(mat2D, extent) output_field = scalar_prop(mat2D * plane_wave, dx, dy, z, wavelength) plot(output_field, extent)
def run(n, mode, group_path, plotFlag, saveFlag, wait_time): # Loading setups configurations config = setup() #rm-list_resources() to find address for smu address_2612b = 26 address_2400 = 24 clear_all() #running tests (smua measures iv and smub measures r) if mode == 'iv': [smu, rm] = gpib(address_2612b) [readingsV, readingsI, readingsR, readingsIR ] = ivr(smu, config[0], config[1], config[2], config[3], config[4], config[5], config[6], config[7], config[8], config[9], config[10], config[11], config[12], config[13], config[14], config[15], config[16], config[18], wait_time) smu.write('reset()') smu.write('smua.nvbuffer1.clear()') smu.write('smub.nvbuffer1.clear()') rm.close Number = [] for i in range(0, len(readingsR)): Number.append(i) if plotFlag == 1: graphR = plot(Number, readingsR, 'N', 'R', 1) graphIV = plot(readingsV, readingsI, 'V', 'I', 2) else: graphR = 'NULL' graphIV = 'NULL' if saveFlag == 1: save(readingsV, readingsI, readingsR, readingsIR, graphIV, graphR, n, group_path) return elif mode == 'led1': [smu_2612b, smu_2400, rm] = gpib2(address_2612b, address_2400) #polarization voltage for sipm on led1 test vPolarization_sipm = 30 [readingsI_sipm, readingsV_led, readingsI_led, readingsR, readingsIR ] = led1(smu_2612b, smu_2400, config[0], config[1], config[2], config[3], config[4], config[5], config[6], config[7], config[8], config[9], config[13], config[14], config[15], config[19], vPolarization_sipm, wait_time) smu_2612b.write('reset()') smu_2612b.write('smua.nvbuffer1.clear()') smu_2612b.write('smub.nvbuffer1.clear()') smu_2400.write('*CLS') rm.close Number = [] for i in range(0, len(readingsR)): Number.append(i) if plotFlag == 1: graphR = plot(Number, readingsR, 'N', 'R', 1) graphIV = plot(readingsI_led, readingsI_sipm, 'Iled', 'Isipm', 2) else: graphR = 'NULL' graphIV = 'NULL' if saveFlag == 1: save_led(readingsI_sipm, readingsV_led, readingsI_led, readingsR, readingsIR, graphIV, graphR, n, group_path) return elif mode == 'led2': [smu_2612b, smu_2400, rm] = gpib2(address_2612b, address_2400) #polarization current for led on led2 test iPolarization_led = 100 * P('m') vPolarization_sipm = 30 [readingsI_sipm, readingsV_led, readingsR, readingsIR ] = led2(smu_2612b, smu_2400, config[0], config[1], config[2], config[3], config[4], config[5], config[6], config[7], config[8], config[9], config[17], config[20], vPolarization_sipm, iPolarization_led, wait_time) smu_2612b.write('reset()') smu_2612b.write('smua.nvbuffer1.clear()') smu_2612b.write('smub.nvbuffer1.clear()') smu_2400.write('*CLS') rm.close Time = [] for i in range(0, len(readingsR)): Time.append(i * wait_time) if plotFlag == 1: graphR = plot(Time, readingsR, 't', 'R', 1) graphI = plot(Time, readingsI_sipm, 't', 'Isipm', 2) else: graphR = 'NULL' graphI = 'NULL' if saveFlag == 1: save_led(Time, readingsI_sipm, readingsV_led, readingsR, readingsIR, graphI, graphR, n, group_path) return
# filename1 = 'obama.jpg' # filename2 = 'ted_cruz.jpg' filename2 = 'donald_trump.jpg' # filename2 = 'hillary_clinton.jpg' # filename2 = 'obama.jpg' # importar as imagens print("Coletando as Imagens") img1 = # src img2 = # dst img1Warped = print("Coletando os pontos faciais correspondentes") points1 = points2 = func.plot("Step1-FaceAlignment.jpg") print("Criando os vetores das funções convexas") hull1 = [] hull2 = [] print("Intersecção dos conjuntos das funções convexas, terminadas pelas distâncias euclidianas") hullIndex = for i in range(0, len(hullIndex)): hull1.append() hull2.append() print("Triangularização de Delaunay aplicada pelos prontos faciais") sizeImg2 = rect = (0, 0, sizeImg2[1], sizeImg2[0])
# first lens output_field = F(dots) extent2 = np.array(F_extent) * wavelength * focal_length dx2 = extent2[1] * 2 / output_field.shape[0] dy2 = extent2[3] * 2 / output_field.shape[1] # circular aperture in Fourier plane multiplies the field aperture, extent, F_mat2D, F_extent = make_circle( dx=dx2, dy=dy2, Lx_max=extent2[1], Ly_max=extent2[3], a=.005, # stretch in x b=.005, # stretch in y ) plot(aperture, extent) output_field = output_field * aperture # second lens output_field = F(output_field) extent2 = np.array(F_extent) * wavelength * focal_length plot(output_field, extent2) #### # Imaging system without aberrations, circular OTF with radius defined by # numerical aperture (NA), magnification M #### # units are microns wavelength = .6
elif command[0]=='absd': #baseline i=0 elif command[0]=='clear': #reset all i=0 elif command[0]=='plot': try: todo=command[1] except: print "Specify plot: spectrum or fid" # try: if 'spectrum' in command[1]: functions.plot(nmrdict['spectrum'],command) elif 'fid' in command[1]: functions.plot(nmrdict['fid'],command) # except Exception as inst: # print type(inst) elif command[0]=='print': print nmrdict.keys() elif command[0]=='ft': # fourier transform i=0 elif command[0]=='help': #help functions.help() elif command[0]=='b2a':
Lx_max = Lx_max, Ly_max = Ly_max) # Create the transmission function of a lens lens_phase = -np.pi/(wavelength*focal_length)*(xm**2+ym**2) lens_transmission = np.exp(1j*lens_phase) # Equation 6-10 # Simulate a plane wave passing through a lens and propagating the focal length output_field = scalar_prop(lens_transmission,dx,dy, focal_length, # z wavelength) plt.imshow(lens_phase) plot(lens_transmission, extent) plot(output_field, extent) # Simulate an input field at the front focal plane propagating to the lens, # passing the lens, and propagating the focal length propagating with scalar transform input_field, extent, F_mat2D, F_extent = make_circle(dx = dx, dy = dy, Lx_max = Lx_max, Ly_max = Ly_max, a = .05, # stretch in x b=.05, # stretch in y ) output_field = scalar_prop(input_field,dx,dy,
def main(): env_setup() HEPD, MEPD = data(orbit_no, True, True) plot(HEPD, MEPD, 'south', 'spacepy', 'plot_combined', 'pdf')
dx = 0.01 dy = 0.01 Lx_max = 1 Ly_max = 1 x, y, xm, ym, extent, F_extent = make_meshgrid(dx=dx, dy=dy, Lx_max=Lx_max, Ly_max=Ly_max) dots = np.zeros_like(xm) dots[len(x) // 3, len(y) // 3] = 1 dots[len(x) * 2 // 3, len(y) * 2 // 3] = 1 plot(dots, extent) # shape_0, extent, F_circle, F_extent = make_circle(dx = dx, # dy = dy, # Lx_max = Lx_max, # Ly_max = Ly_max, # a = 10, # stretch in x # b=10, # stretch in y # ) shape_0, extent, F_circle, F_extent = make_2D( dx=dx, dy=dy, Lx_max=Lx_max, Ly_max=Ly_max, a=10,
def update(self, hs, v0, theta, time_range, w=None, rad_range=None, CNT_MAX=10000, save=False, arrow=True): """Simulate this model. Args: hs (list): Fan's cordinate. v0 (float): Fan's initial velocity. theta (float): Fan's elevation angle. time_range (float): Simulation time. w (float, optional): Fan's ngular velocity. Defaults to None. rad_range (list, optional): Fan's angle range. Defaults to None. CNT_MAX (int, optional): Iteration value. Defaults to 10000. save (bool, optional): Whether you save every plot. Defaults to False. arrow (bool, optional): Plot style. Arrow or particle. Defaults to True. """ lx, ly = self.lx, self.ly DELT, DELL = self.DELT, self.DELL passed_time, num = 0, 0 dirname = './imgs_ex/2d_{}_{}'.format(v0, theta) os.makedirs(dirname, exist_ok=True) theta = np.deg2rad(theta) # Particles Array ptclsx = np.random.rand(4000) * lx ptclsy = np.random.rand(4000) * ly particles = np.stack([ptclsx, ptclsy]).T while passed_time < time_range: self.ux, self.uy, theta, w = F2d.ff(self.ux, self.uy, self.DELT, hs, v0, theta, w, rad_range) # Canvus ax = self.fig.add_subplot( 111, xlim=(-0.1, self.lx * 1.1), ylim=(-0.1, self.ly * 1.1), aspect='equal', ) ax.set(xlabel='Room Length x/m', ylabel='Room Height y/m') ax.set_title('t = {:.2f} [s]'.format(num * DELT)) # Plot if arrow: divider = make_axes_locatable(ax) cax = divider.append_axes('right', '5%', pad='3%') im = F2d.plot(self.ux, self.uy, DELL, DELL, self.xx, self.yy, ax) self.fig.colorbar(im, cax=cax) else: im = F2d.pp(self.ux, self.uy, particles, DELT, DELL, DELL, ax) self.fig.savefig('{}/{:0=10}.png'.format(dirname, num)) if not save: self.imgs.append([im]) plt.cla() plt.clf() print('time : {:.2f}'.format(num * DELT)) # Advection ux_ast = F2d.adv_x(self.ux, self.uy, DELT, DELL, DELL) uy_ast = F2d.adv_y(self.ux, self.uy, DELT, DELL, DELL) # Viscosity ux_ast, uy_ast = F2d.vis(self.ux, self.uy, ux_ast, uy_ast, DELL, DELL, self.MU, self.RHO) # Solce Poisson Eq to Align ux&uy (div u = 0) self.p = F2d.poisson(ux_ast, uy_ast, DELT, DELL, DELL, self.p, self.EPS, CNT_MAX) # Fix each Velocity self.ux, self.uy = F2d.fix_u(ux_ast, uy_ast, self.p, DELT, DELL, DELL, self.RHO) passed_time = num * DELT num += 1 if not save: anim = anime.ArtistAnimation(self.fig, self.imgs, interval=DELT * 1000) anim.save('./animation_{}_{}.mp4'.format(v0, theta), writer='ffmpeg')
H[np.nonzero(np.sqrt(FX**2 + FY**2) > (1. / wavelength))] = 0 U1 = U0 * H u1 = Ft(U1) return (u1) if __name__ == "__main__": dfx = 0.0005 dfy = 0.0005 fx_max = 1 fy_max = 1 wavelength = 0.5 z = 0 F_annulus, F_extent = make_annulus(dfx=dfx, dfy=dfy, fx_max=fx_max, fy_max=fy_max, d_radius=dfx * 3) plot(F_annulus, F_extent) u1 = scalar_prop_freq(F_annulus, dfx, dfy, fx_max, fy_max, z, wavelength) plot(u1, F_extent, log=True) z = 500 u1 = scalar_prop_freq(F_annulus, dfx, dfy, fx_max, fy_max, z, wavelength) plot(u1, F_extent, log=True)
Ly_max = 100 # Increase to increase zero padding wavelength = .6 z = 200 aperture, extent, F_aperture, F_extent = make_circle( dx=dx, dy=dy, Lx_max=Lx_max, Ly_max=Ly_max, a=.05, # stretch in x b=.05, # stretch in y ) output_field = scalar_prop(aperture, dx, dy, z, wavelength) plot(aperture, extent, figsize_x=Lx_max / 10, figsize_y=Ly_max / 10) plot(F_aperture, F_extent, figsize_x=Lx_max / 10, figsize_y=Ly_max / 10) plot(output_field, extent, figsize_x=Lx_max / 10, figsize_y=Ly_max / 10) # Loop different sampling dx_vec = [0.1, 1.0] Lx_max = 100 # Increase to increase zero padding Ly_max = 100 # Increase to increase zero padding wavelength = .6 z = 200 plt.figure() for dx in dx_vec: x, y, xm, ym, extent, F_extent = make_meshgrid(dx=dx, dy=dx,
folder_name + "/corr_func M=" + str(M) + ", N=" + str(N) + ", T=" + str(T[i]), pair_corr_func[i]) # -------------------------- </storing the array with the pair correlation function> -------------------------- print("The pair correlation function have been calculated") print("The time spent on pair correlation function calculation: " + str( datetime.timedelta(seconds=end_corr_func_calc_time - start_corr_func_calc_time)) + " hh:mm:ss") print( "The date and the time when the pair correlation function was calculated: " + time.strftime("%D %H:%M:%S", time.localtime(end_corr_func_calc_time)) + " hh:mm:ss") print("The total calculation time: " + str( datetime.timedelta(seconds=end_play_out_time - start_play_out_time + end_corr_func_calc_time - start_corr_func_calc_time)) + " hh:mm:ss") print( "The ratio of the time of pair correlation function calculation to the time of playing states out: " + str((end_corr_func_calc_time - start_corr_func_calc_time) / (end_play_out_time - start_play_out_time))) print("Calculation at T = " + str(T[i] * T0) + " K was completed") # --------------------------- </pair correlation function calculation> --------------------------------------------- # --------------------------- <pair correlation function plotting> --------------------------------------------- for i in range(len(T)): plot( r, pair_corr_func[i], "g(r*), the pair correlation function of " + chosen_noble_gas.value.name_en + " at T = " + str(T[i] * T0) + " K", "r*", "g(r*)") # --------------------------- </pair correlation function plotting> --------------------------------------------
from propagators import create_plane_wave from functions import plot # units are microns dx = 0.3 dy = 0.3 Lx_max = 100 Ly_max = 100 wavelength = 0.6 extent = [-Lx_max, Lx_max - dx, -Ly_max, Ly_max - dy] alpha_max = wavelength / (2 * dx) beta_max = wavelength / (2 * dy) # No aliasing alpha = alpha_max * 1 beta = 0 plane_wave = create_plane_wave(dx, dy, Lx_max, Ly_max, alpha, beta, wavelength) # Aliasing example 1 plot(plane_wave, extent) alpha = alpha_max * 2 beta = 0 plane_wave = create_plane_wave(dx, dy, Lx_max, Ly_max, alpha, beta, wavelength) plot(plane_wave, extent) # Aliasing example 2 alpha = alpha_max * 7 beta = 0 plane_wave = create_plane_wave(dx, dy, Lx_max, Ly_max, alpha, beta, wavelength) plot(plane_wave, extent)
def main(nqubits, instance, T, dt, solver, plot, trotter, params, method, maxiter): """Adiabatic evoluition to find the solution of an exact cover instance. Args: nqubits (int): number of qubits for the file that contains the information of an Exact Cover instance. instance (int): intance used for the desired number of qubits. T (float): maximum schedule time. The larger T, better final results. dt (float): time interval for the evolution. solver (str): solver used for the adiabatic evolution. plot (bool): decides if plots of the energy and gap will be returned. trotter (bool): decides if a Trotter Hamiltonian will be used. params (list): list of polynomial coefficients for scheduling function. Default is linear scheduling. method (str): Method to use for scheduling optimization (optional). maxiter (bool): Maximum iterations for scheduling optimization (optional). Returns: Result of the most probable outcome after the adiabatic evolution. Plots of the ground and excited state energies and the underlying gap during the adiabatic evolution. The plots are created only if the ``--plot`` option is enabled. """ # Read 3SAT clauses from file control, solution, clauses = functions.read_file(nqubits, instance) nqubits = int(control[0]) # Define "easy" and "problem" Hamiltonians times = functions.times(nqubits, clauses) sh0, smap0 = functions.h_initial(nqubits, times) sh1, smap1 = functions.h_problem(nqubits, clauses) if trotter: print('Using Trotter decomposition for the Hamiltonian\n') gs = lambda: functions.ground_state(nqubits) H0 = hamiltonians.TrotterHamiltonian.from_symbolic(sh0, smap0, ground_state=gs) H1 = hamiltonians.TrotterHamiltonian.from_symbolic(sh1, smap1) else: print('Using the full Hamiltonian evolution\n') H0 = hamiltonians.Hamiltonian.from_symbolic(sh0, smap0) H1 = hamiltonians.Hamiltonian.from_symbolic(sh1, smap1) print('-' * 20 + '\n') if plot and nqubits >= 14: print('Currently not possible to calculate gap energy for {} qubits.' '\n Proceeding to adiabatic evolution without plotting data.\n' ''.format(nqubits)) plot = False if plot and method is not None: print('Not possible to calculate gap energy during optimization.') plot = False # Define scheduling according to given params if params is None: # default is linear scheduling s = lambda t: t else: if method is None: s = lambda t: functions.spolynomial(t, params) else: s = functions.spolynomial # Define evolution model and (optionally) callbacks if plot: ground = callbacks.Gap(0) excited = callbacks.Gap(1) gap = callbacks.Gap() evolve = models.AdiabaticEvolution(H0, H1, s, dt, solver=solver, callbacks=[gap, ground, excited]) else: evolve = models.AdiabaticEvolution(H0, H1, s, dt, solver=solver) if method is not None: print(f'Optimizing scheduling using {method}.\n') if params is None: params = [T] else: params.append(T) if method == "sgd": options = {"nepochs": maxiter} else: options = {"maxiter": maxiter, "disp": True} energy, params, _ = evolve.minimize(params, method=method, options=options) T = params[-1] # Perform evolution initial_state = np.ones(2**nqubits) / np.sqrt(2**nqubits) final_state = evolve(final_time=T, initial_state=initial_state) output_dec = (np.abs(final_state.numpy())**2).argmax() max_output = "{0:0{bits}b}".format(output_dec, bits=nqubits) max_prob = (np.abs(final_state.numpy())**2).max() print("Exact cover instance with {} qubits.\n".format(nqubits)) if solution: print('Known solution: {}\n'.format(''.join(solution))) print('-' * 20 + '\n') print(f'Adiabatic evolution with total time {T}, evolution step {dt} and ' f'solver {solver}.\n') print(f'Most common solution after adiabatic evolution: {max_output}.\n') print(f'Found with probability: {max_prob}.\n') if plot: print('-' * 20 + '\n') functions.plot(nqubits, ground[:], excited[:], gap[:], dt, T) print('Plots finished.\n')
def run(n, test, group_path, plotFlag, saveFlag): # Loading setups configurations config = setup() #rm-list_resources() to find address for smu address_2612b = 26 address_2400 = 24 clear_all() #running tests (smua measures iv and smub measures r) [smu_2612b, smu_2400, rm] = gpib(address_2612b, address_2400) if test == 'iv': [readingsV_sipm, readingsI_sipm, readingsR] = IVComplete(smu_2612b, smu_2400, config) smu_2612b.write('reset()') smu_2612b.write('smua.nvbuffer1.clear()') smu_2612b.write('smub.nvbuffer1.clear()') smu_2400.write('*CLS') readingsV_sipm_neg, readingsV_sipm_pos, readingsI_sipm_neg, readingsI_sipm_pos, readingsR_neg, readingsR_pos = split( readingsV_sipm, readingsI_sipm, readingsR) number_neg = [] number_pos = [] for g in range(len(readingsR_neg)): number_neg.append(g) for g in range(len(readingsR_pos)): number_pos.append(g) if plotFlag == 1: graphR_neg = plot(number_neg, readingsR_neg, 'N', 'R', 1, log=False, errorbars_2400=True) graphR_pos = plot(number_pos, readingsR_pos, 'N', 'R', 2, log=False, errorbars_2400=True) graphIV_neg = plot(readingsV_sipm_neg, readingsI_sipm_neg, 'Vsipm', 'Isipm', 3, log=False, errorbars_2612=True) graphIV_pos = plot(readingsV_sipm_pos, readingsI_sipm_pos, 'Vsipm', 'Isipm', 4, log=False, errorbars_2612=True) else: graphR_neg = 'NULL' graphR_pos = 'NULL' graphIV_neg = 'NULL' graphIV_pos = 'NULL' if saveFlag == 1: group_path_pos = group_path + " (rq)" group_path_neg = group_path + " (vbr)" save_iv(readingsV_sipm_neg, readingsI_sipm_neg, readingsR_neg, graphIV_neg, graphR_neg, n, group_path_pos) save_iv(readingsV_sipm_pos, readingsI_sipm_pos, readingsR_pos, graphIV_pos, graphR_pos, n, group_path_neg) time.sleep(45) [readingsI_sipm, readingsR] = DarkCurrent(smu_2612b, smu_2400, config) smu_2612b.write('reset()') smu_2612b.write('smua.nvbuffer1.clear()') smu_2612b.write('smub.nvbuffer1.clear()') smu_2400.write('*CLS') number = [] for g in range(len(readingsR)): number.append(g) if plotFlag == 1: graphR = plot(number, readingsI_sipm, 'N', 'Isipm', 5, log=False, errorbars_2612=True) else: graphR = 'NULL' if saveFlag == 1: group_path_dark = group_path + " (idark)" save_dark(readingsI_sipm, readingsR, graphR, n, group_path_dark) rm.close return elif test == 'self_heating': [ readingsV_sipm, readingsI_sipm, readingsV_led, readingsI_led, readingsR ] = SelfHeating(smu_2612b, smu_2400, config) smu_2612b.write('reset()') smu_2612b.write('smua.nvbuffer1.clear()') smu_2612b.write('smub.nvbuffer1.clear()') smu_2400.write('*CLS') rm.close Number = [] for i in range(0, len(readingsR)): Number.append(i) if plotFlag == 1: graphR = plot(Number, readingsR, 'N', 'R', 1) graphIV = plot(readingsI_led, readingsI_sipm, 'Iled', 'Isipm', 2, log=True, errorbars_2612=True) else: graphR = 'NULL' graphIV = 'NULL' if saveFlag == 1: save(readingsV_sipm, readingsI_sipm, readingsV_led, readingsI_led, readingsR, graphIV, graphR, n, group_path) return else: print(str(test) + " is not a valid mode") return
pair_corr_func_description) elif device_to_calculate_pair_correlation_function == CalculateOn.GPU: pair_corr_func[i] = calculate_pair_correlation_function_on_gpu(molecules_ensemble, r, delta_r, L, n, pair_corr_func_execution_progress, block_dim, pair_corr_func_description) end_corr_func_calc_time = time.time() # -------------------------- <сохраняем массив с корреляционной функцией> ------------------------------------- folder_name = "corr_func_arrays/M=" + str(M) + "/N=" + str(N) if not path.exists(folder_name): makedirs(folder_name) np.save(folder_name + "/corr_func M=" + str(M) + ", N=" + str(N) + ", T=" + str(T[i]), pair_corr_func[i]) # -------------------------- </сохраняем массив с корреляционной функцией> ------------------------------------ print("Парная корреляционная функция найдена") print("Время расчёта корреляционной функции: " + str(datetime.timedelta(seconds=end_corr_func_calc_time - start_corr_func_calc_time)) + " hh:mm:ss") print("Дата и время конца расчёта корреляционной функции: " + time.strftime("%D %H:%M:%S", time.localtime(end_corr_func_calc_time)) + " hh:mm:ss") print("Общее время расчёта: " + str(datetime.timedelta(seconds= end_play_out_time - start_play_out_time + end_corr_func_calc_time - start_corr_func_calc_time)) + " hh:mm:ss") print("Отношение времени расчёта парной корреляционной функции ко времени разыгрывания состояний: " + str((end_corr_func_calc_time - start_corr_func_calc_time) / (end_play_out_time - start_play_out_time))) print("Расчёт при T = " + str(T[i] * T0) + " K завершён") # --------------------------- </вычисляем корреляционнную функцию> ------------------------------------------------- # --------------------------- <строим корреляционнную функцию> ----------------------------------------------------- for i in range(len(T)): plot(r, pair_corr_func[i], "g(r*), парная корреляционная функция " + chosen_noble_gas.value.name_ru + "а при T = " + str(T[i] * T0) + " K", "r*", "g(r*)") # --------------------------- </строим корреляционнную функцию> ----------------------------------------------------
'coordinaten'] = "51.4251,6.1561" df_locations.loc[df_locations.coordinaten == "51.7851.5.3641", 'coordinaten'] = "51.7851,5.3641" df_locations.loc[df_locations.coordinaten == "51.7143.4,783131", 'coordinaten'] = "51.7143,4.783131" df_locations.loc[:, "geometry"] = df_locations.coordinaten.apply( lambda x: parse_point(x)) df_locations = gpd.GeoDataFrame(df_locations) df_locations.crs = {'init': 'epsg:4326'} df_locations = df_locations.loc[~df_locations.geometry.isna(), :] df_locations.loc[:, 'river'] = df_locations['Nieuwe code'].apply(lambda x: x[0]) df_locations = df_locations.iloc[:, [1, 4, 5]] df_locations.columns = ['Gebiedscode', 'geometry', 'river'] ax = plot() df_locations.plot(ax=ax, transform=ccrs.PlateCarree()) plt.title("Locations of river OSPAR observations") plt.show() # SECTION 3 # QUALITY CONTROL dubious_codes = [] # Sample IDs that seem to be duplicates for i in df.Gebiedscode.unique(): if i == 0 or i == '0': continue x = df.loc[df.Gebiedscode == i, 'meting'] if df[df.duplicated(keep=False)].shape[0] > 0: dubious_codes.append(i)