def cleaning_movies(): '''Function 1 to clean data ''' data = pd.read_csv('../input/movies/movies.csv') data = data.drop(columns=['Cast', 'Wiki Page'], axis=1) data = data.rename( columns={ 'Release Year': 'year', 'Title': 'title_movie', 'Origin/Ethnicity': 'origin', 'Director': 'director', 'Genre': 'genres', 'Plot': 'plot' }) data['genres'] = data['genres'].replace('unknown', np.nan) data = data.dropna(axis=0, subset=['genres']) pdf.creaPDF(data) return data
def process_PDF(): cookie = bottle.request.get_cookie("session") username = sessions.get_username(cookie) if not username: username = '******' filename = c.pdf_file_name + '_' + username + '_' + str(time.time()) id_to_export = bottle.request.forms.getall("id") list_of_publication = [publication.get_publication_id(id) for id in id_to_export] PDF.generatePDF(list_of_publication, filename, DOC_ROOT, TMP_DIR) return bottle.redirect("/pdf/%s.pdf" % filename)
def imprimirFactura(self,widget): model,iter= self.idTreeFactura.get_selection().get_selected() nFactura=model.get_value(iter,0) nCliente=model.get_value(iter,2) print(nCliente) pdf = PDF.PDF() if(nCliente!=""): pdf.getFactura(nFactura,nCliente) else: self.idinformativo.set_text("Selecciona una factura")
def split(args): canvas_conf = loadConfig(args.canvas_config) c = Canvas(canvas_conf["token"], canvas_conf["course_id"], canvas_conf["URL"]) students = c.getStudents() student_username_set = [student['login_id'] for student in students] string_matcher = StringMatcher(student_username_set) with open(args.names) as f: usernames = [] lines = [line.strip() for line in f.readlines()] for line in lines: line = line.split(" ") student = string_matcher.match_str(line[0]) usernames.append(student) pdf.split(args.fname, usernames, args.folder, int(args.pages))
def GenrateReport(self): title='Link Scanner -- Finding Broken links and Patterns' PDFInput = [] PDFInput = self.__l.putResult() self.Report = PDF() self.Report.setdata(PDFInput,self.ExeTime,self.Processortime,title,'komal') #self.Report.set_title(title) #self.Report.set_author('Jules Verne') self.Report.print_chapter() self.Report.output('Report.pdf','F') self.Report.displaydata()
def single_location_comparison(model_filepath, lat, lon): """ Plots model outputs for given coordinates over time """ era5_ds = dd.collect_ERA5() cmip_ds = dd.collect_CMIP5() cordex_ds = dd.collect_CORDEX() cru_ds = dd.collect_CRU() #aphro_ds = dd.collect_APHRO() era5_ts = select_coords(era5_ds, lat, lon) cmip_ts = select_coords(cmip_ds, lat, lon) cordex_ts = select_coords(cordex_ds, lat, lon) cru_ts = select_coords(cru_ds, lat, lon) #aphro_ts = select_coords(aphro_ds, lat, lon) timeseries = [era5_ts, cmip_ts, cordex_ts, cru_ts] #, aphro_ts] xtr, y_gpr_t, y_std_t = model_prep([lat, lon], model_filepath) tims.benchmarking_plot(timeseries, xtr, y_gpr_t, y_std_t) dataset_stats(timeseries, xtr, y_gpr_t, y_std_t) corr.dataset_correlation(timeseries, y_gpr_t) pdf.benchmarking_plot(timeseries, y_gpr_t)
def basin_comparison(model_filepath, location): """ Plots model outputs for given coordinates over time """ era5_ds = dd.collect_ERA5() cmip_ds = dd.collect_CMIP5() cordex_ds = dd.collect_CORDEX() cru_ds = dd.collect_CRU() #aphro_ds = dd.collect_APHRO() era5_bs = select_basin(era5_ds, location) cmip_bs = select_basin(cmip_ds, location) cordex_bs = select_basin(cordex_ds, location) cru_bs = select_basin(cru_ds, location) #aphro_bs = select_basin(aphro_ds, location) basins = [era5_bs, cmip_bs, cordex_bs, cru_bs] #, aphro_ts] xtr, y_gpr_t, y_std_t = model_prep(location, model_filepath) tims.benchmarking_plot(basins, xtr, y_gpr_t, y_std_t) dataset_stats(basins, xtr, y_gpr_t, y_std_t) corr.dataset_correlation(basins, y_gpr_t) pdf.benchmarking_plot(basins, y_gpr_t)
def boxPDF(box, NBIN=20): """get simple PDF of box as (xmin,xmax,pdf) hack here to ensure all data included in straightforward way bad since slightly distorts uniform distribution""" xmin = box.box_data.min() * 0.99999 xmax = box.box_data.max() * 1.00001 delta = (xmax - xmin) / (NBIN) pdf = np.zeros(NBIN) xbin = np.zeros(NBIN) data = box.box_data pdfsum = 0 #number of elements which fall in to bin #trying to do this without a loop over the data elements for i in range(NBIN): binlow = i * delta + xmin binhigh = binlow + delta binmid = (binlow + binhigh) / 2 xbin[i] = binmid #next line a little convoluted and must be better way of #combining the two criterea into one evaluation over box nval = ((data >= binlow) * (data < binhigh)).nonzero()[0].size pdfsum += nval pdf[i] = float(nval) / float(data.size) / delta if not pdfsum == data.size: print 'Warning: pdf calculation has double counted elements' print 'counted=', pdfsum print 'expected=', data.size pdfV = PDF() pdfV.set(xmin, xmax, delta, xbin, pdf) #return (xmin,xmax,delta,xbin,pdf,pdfV) return pdfV
def boxPDF(box,NBIN=20): """get simple PDF of box as (xmin,xmax,pdf) hack here to ensure all data included in straightforward way bad since slightly distorts uniform distribution""" xmin=box.box_data.min()*0.99999 xmax=box.box_data.max()*1.00001 delta=(xmax-xmin)/(NBIN) pdf=np.zeros(NBIN) xbin=np.zeros(NBIN) data=box.box_data pdfsum=0 #number of elements which fall in to bin #trying to do this without a loop over the data elements for i in range(NBIN): binlow=i*delta+xmin binhigh=binlow+delta binmid=(binlow+binhigh)/2 xbin[i]=binmid #next line a little convoluted and must be better way of #combining the two criterea into one evaluation over box nval=((data>=binlow)*(data<binhigh)).nonzero()[0].size pdfsum+=nval pdf[i]=float(nval)/float(data.size)/delta if not pdfsum==data.size: print 'Warning: pdf calculation has double counted elements' print 'counted=',pdfsum print 'expected=',data.size pdfV=PDF() pdfV.set(xmin,xmax,delta,xbin,pdf) #return (xmin,xmax,delta,xbin,pdf,pdfV) return pdfV
class keepSmile: def __init__(self,url): self.url = url def func_a(self): time.sleep(1) # simulate some work def func_b(self): time.sleep(0.3) def func_c(self): time.sleep(0.9) def func_d(self): i=0 time.sleep(0.6) while i < 1000: i=i+1 print i def GenrateReport(self): title='Link Scanner -- Finding Broken links and Patterns' PDFInput = [] PDFInput = self.__l.putResult() self.Report = PDF() self.Report.setdata(PDFInput,self.ExeTime,self.Processortime,title,'komal') #self.Report.set_title(title) #self.Report.set_author('Jules Verne') self.Report.print_chapter() self.Report.output('Report.pdf','F') self.Report.displaydata() def arbitrary(self): start_time = time.time() start_clock=time.clock() self.__l=linkScan(self.url,4) self.__l.crawl() que.put(1) self.__l.scan() que.put(2) self.__l.pattern_search() que.put(3) self.ExeTime= time.time() - start_time,"seconds" self.Processortime=time.clock()-start_clock,"seconds" self.GenrateReport() que.put(4) self.func_d() que.put(5) print self.__l.putResult()
# -*- coding: utf-8 -*- """ Created on Wed Feb 19 15:19:16 2020 @author: TR """ from PDF import * import matplotlib.pyplot as plt iFreq = scio.loadmat('matlabdata_iFreq_FOR RDF.mat')['iFreq'] Mask = scio.loadmat('matlabdata_Mask_FOR RDF.mat')['Mask'] matrix_size = scio.loadmat('matlabdata_matrix_size_FOR RDF.mat')['matrix_size'] voxel_size = scio.loadmat('matlabdata_voxel_size_FOR RDF.mat')['voxel_size'] B0_dir = scio.loadmat('matlabdata_ B0_dir_FOR RDF.mat')['B0_dir'] N_std = scio.loadmat('matlabdata_N_std_FOR RDF.mat')['N_std'] RDF = PDF(iFreq, N_std, Mask, matrix_size, voxel_size, B0_dir) print('RDF.shape=', RDF.shape) print('RDF=', RDF[126:129, 126:129, 29]) fig = plt.figure() fig1 = fig.add_subplot(111) fig1.imshow(np.real(RDF[:, :, 29]), 'gray') plt.show() print('pass')
def calculateMetric(metric_name, param_vals): if metric_name == 'count': if len(param_vals)!= 1: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be count(data)' raise Exception() return red.count(*param_vals) elif metric_name == 'pdf': if len(param_vals)!= 3: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be pdf(data, bin_values, continuous_bins)' raise Exception() return PDF.single(*param_vals) elif metric_name == 'deft': if len(param_vals) < 2 or len(param_vals) > 3: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be deft(data, g, alpha)' raise Exception() return deft.deft(*param_vals) elif metric_name == 'pdf_joint': if len(param_vals)!= 6: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be pdf_joint(dataA, bin_valuesA, continuous_binsA, dataB, bin_valuesB, continuous_binsB)' raise Exception() return PDF.joint(*param_vals) elif metric_name == 'mutual_information': if len(param_vals) < 3 or len(param_vals) > 4: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be mutual_information(pdfA, pdfB, joint_pdf, logbase="log2")' raise Exception() return MI.calculate(*param_vals) elif metric_name == 'shannon': if len(param_vals) < 1 or len(param_vals) > 2: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be shannon(pdf, logbase="log2")' raise Exception() return shannon.calculate(*param_vals) elif metric_name == 'kullback-leibler': if len(param_vals) < 2 or len(param_vals) > 3: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be kullback-leibler(pdf_p, pdf_q, logbase="log2")' raise Exception() return kullback.calculate(*param_vals) elif metric_name == 'fisher': if len(param_vals) < 2 or len(param_vals) > 3: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be fisher(pdf, eps, logbase="log2")' raise Exception() return fis.calculate(*param_vals) elif metric_name == 'hellinger-distance': if len(param_vals) != 2: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be hellinger-distance(pdf_p, pdf_q)' raise Exception() return hellinger.calculate(*param_vals) elif metric_name == 'surprise': if len(param_vals)!= 1: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be surprise(prob)' raise Exception() return surprise.calculate(*param_vals) elif metric_name == 'idt': if len(param_vals) < 6 or len(param_vals) > 7: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be idt(initial, time_series, epsilon, dt, bin_values, continuous_bins, logbase="log2")' raise Exception() return IDT.system(*param_vals) elif metric_name == 'idt_individual': if len(param_vals) < 8 or len(param_vals) > 9: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be idt_individual(initial, time_series, dt, bin_values, continuous_bins, sample_state_0, sample_state_t, sample_time, logbase="log2")' raise Exception() return IDT.individual(*param_vals) elif metric_name == 'information_integration': if len(param_vals) < 9 or len(param_vals) > 10: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be information_integration(initial, group, dt, bin_values, continuous_bins, sample_N1, sample_N2, sample_G, sample_t, logbase="log2")' raise Exception() return II.calculate(*param_vals) elif metric_name == 'multi_information': if len(param_vals) < 6 or len(param_vals) > 7: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be multi_information(data, bin_values, continuous_bins, sample_var, sample_elems, sample_pop, logbase="log2")' raise Exception() return multi.calculate(*param_vals) elif metric_name == 'swap_axes': if len(param_vals)!= 3: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be swap_axes(data, axis0, axis1)' raise Exception() return np.swapaxes(*param_vals) elif metric_name == 'add_dimension': if len(param_vals)!= 2: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be add_dimension(data, dimNumber)' raise Exception() return np.expand_dims(*param_vals) elif metric_name == 'join_dimensions': if len(param_vals)!= 3: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be join_dimensions(data, dimNumberA, dimNumberB)' raise Exception() return red.join(*param_vals) else : # Try to get a numpy function try : func = getattr(np, metric_name) return func(*param_vals) except: print 'ERROR:Metric ', metric_name, ' does not exist' raise Exception()
def PDF_generator(sstalib, gate, sample_dist): return PDF(sample_dist=sample_dist, mu=sstalib[gate]['mu'], sigma=sstalib[gate]['sigma'])
def imprimir(self, control): obj = PDF.PDF() obj.pdf()
def calculateMetric(metric_name, param_vals): ''' Calculates a metric. Input: metric_name metric name param_vals metric parameters Returns: result of the metric ''' if metric_name == 'count': if len(param_vals)!= 1: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be count(data)' raise Exception() return red.count(*param_vals) elif metric_name == 'pdf': if len(param_vals)!= 3: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be pdf(data, bin_values, continuous_bins)' raise Exception() return PDF.single(*param_vals) elif metric_name == 'deft': if len(param_vals) < 4 or len(param_vals) > 5: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be deft(data, g, minLimit, maxLimit, alpha=2)' raise Exception() return deft.deft(*param_vals) elif metric_name == 'deft_joint': if len(param_vals) < 7 or len(param_vals) > 8: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be deft_joint(dataA, dataB, g, minLimitA, maxLimitA, minLimitB, maxLimitB, alpha=2)' raise Exception() return deft.deft(*param_vals) elif metric_name == 'pdf_joint': if len(param_vals)!= 6: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be pdf_joint(dataA, bin_valuesA, continuous_binsA, dataB, bin_valuesB, continuous_binsB)' raise Exception() return PDF.joint(*param_vals) elif metric_name == 'mutual_information': if len(param_vals) < 3 or len(param_vals) > 4: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be mutual_information(pdfA, pdfB, joint_pdf, logbase="log2")' raise Exception() return MI.calculate(*param_vals) elif metric_name == 'shannon': if len(param_vals) < 1 or len(param_vals) > 2: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be shannon(pdf, logbase="log2")' raise Exception() return shannon.calculate(*param_vals) elif metric_name == 'kullback-leibler': if len(param_vals) < 2 or len(param_vals) > 3: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be kullback-leibler(pdf_p, pdf_q, logbase="log2")' raise Exception() return kullback.calculate(*param_vals) elif metric_name == 'fisher': if len(param_vals) < 2 or len(param_vals) > 3: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be fisher(pdf, eps, logbase="log2")' raise Exception() return fis.calculate(*param_vals) elif metric_name == 'hellinger-distance': if len(param_vals) != 2: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be hellinger-distance(pdf_p, pdf_q)' raise Exception() return hellinger.calculate(*param_vals) elif metric_name == 'surprise': if len(param_vals)!= 1: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be surprise(prob)' raise Exception() return surprise.calculate(*param_vals) elif metric_name == 'idt': if len(param_vals) < 6 or len(param_vals) > 7: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be idt(initial, time_series, epsilon, dt, bin_values, continuous_bins, logbase="log2")' raise Exception() return IDT.system(*param_vals) elif metric_name == 'idt_individual': if len(param_vals) < 8 or len(param_vals) > 9: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be idt_individual(initial, time_series, dt, bin_values, continuous_bins, sample_state_0, sample_state_t, sample_time, logbase="log2")' raise Exception() return IDT.individual(*param_vals) elif metric_name == 'information_integration': if len(param_vals) < 9 or len(param_vals) > 10: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be information_integration(initial, group, dt, bin_values, continuous_bins, sample_N1, sample_N2, sample_G, sample_t, logbase="log2")' raise Exception() return II.calculate(*param_vals) elif metric_name == 'multi_information': if len(param_vals) < 6 or len(param_vals) > 7: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be multi_information(data, bin_values, continuous_bins, sample_var, sample_elems, sample_pop, logbase="log2")' raise Exception() return multi.calculate(*param_vals) elif metric_name == 'early_warning_difference': if len(param_vals) < 4 or len(param_vals) > 5: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be early_warning_difference(time_series_ref, time_series_comp, change_values, warning_values, histogram_limit=50)' raise Exception() return ew.early_warning_difference(*param_vals) elif metric_name == 'early_warning_flips': if len(param_vals) != 2: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be early_warning_flips(time_series, change_values)' raise Exception() return ew.early_warning_flips(*param_vals) elif metric_name == 'add_dimension': if len(param_vals)!= 2: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be add_dimension(data, dimNumber)' raise Exception() return np.expand_dims(*param_vals) elif metric_name == 'join_dimensions': if len(param_vals)!= 3: print 'ERROR:Error in ', metric_name, ', number of parameters incorrect. It must be join_dimensions(data, dimNumberA, dimNumberB)' raise Exception() return red.join(*param_vals) else : # Try to get a numpy function try : func = getattr(np, metric_name) return func(*param_vals) except: print 'ERROR:Metric ', metric_name, ' does not exist' raise Exception()
def individual(initial, times, dt, bin_values, continuous_bins, sample_N1, sample_N2, sample_t, logbase="log2"): """ IDT individual metric Input: initial Initial data NxP N = elements P = population times Time state data TxNxP T = time series N = elements P = population dt Number of timesteps between time series bin_values values of the bins continuous_bins true if the values of the bins are continuous sample_N1 percentage of elements to choose as a sample for state 0 sample_N2 percentage of elements to choose as a sample for state t sample_time percentage of elements to choose as a sample for time series logbase Base for the logarithm ("log2", "log", "log10") Returns: IDT N N = elements """ assert logbase in ["log2", "log", "log10"], 'Logbase parameter must be one of ("log2", "log", "log10")' assert 0 < sample_N1 <= 1, "Sample for N1 must be within (0, 1]" assert 0 < sample_N2 <= 1, "Sample for N2 must be within (0, 1]" assert 0 < sample_time <= 1, "Sample for time must be within (0, 1]" number_of_bins = len(bin_values) if continuous_bins: number_of_bins = number_of_bins - 1 # Sampling input data sample_elements_1 = np.arange(len(initial)) sample_elements_2 = np.arange(len(initial)) sample_time = np.arange(len(times)) np.random.shuffle(sample_elements_1) np.random.shuffle(sample_elements_2) np.random.shuffle(sample_time) sample_elements_1 = sample_elements_1[: len(initial) * sample_N1] sample_elements_2 = sample_elements_2[: len(initial) * sample_N2] sample_time = sample_time[: len(times) * sample_t] sample_time = np.sort(sample_time) times_sampled = times[sample_time] initial_sampled = initial[sample_elements_1] initial_sampled_2 = initial[sample_elements_2] initial_sampled_len = len(initial_sampled) initial_sampled_len_2 = len(initial_sampled_2) times_sampled_len = len(times_sampled) # Maximum value for IDT when there is no enough decay IDT_max = len(times) * dt # Initial marginals pdf pdf_initial = PDF.single(initial_sampled, bin_values, continuous_bins) pdf_initial_2 = PDF.single(initial_sampled_2, bin_values, continuous_bins) # Initial entropy h_initial = shannon.calculate(pdf_initial, logbase) # Temporal marginals pdf pdf_t = np.ndarray((len(sample_time), len(sample_elements_2), number_of_bins), dtype="float") for t in xrange(len(sample_time)): pdf_t[t] = PDF.single(times_sampled[t][sample_elements_2, ...], bin_values, continuous_bins) # Calculate IDT for each element (sample) IDT_var = np.ndarray(initial_sampled_len, dtype="float") init = time.clock() for i in xrange(initial_sampled_len): # Target decay limit h_target = h_initial[i] / 2 # Maximum mutual information max_I = np.ndarray(times_sampled_len + 1, dtype="float") initial_sampled_i_len = len(initial_sampled[i]) found = False # Initial mutual information mi_init = np.ndarray((len(times_sampled[t][sample_elements_2])), dtype="float") for j in xrange(len(times_sampled[t][sample_elements_2])): initial_sampled_i_len_2 = len(initial_sampled_2[j]) # Calculate joint pdf from initial state pdf_joint = PDF.joint( initial_sampled[i].reshape(1, initial_sampled_i_len), bin_values, continuous_bins, initial_sampled_2[j].reshape(1, initial_sampled_i_len_2), bin_values, continuous_bins, ) # Mutual information mi_init[j] = MI.calculate( pdf_initial[i].reshape(1, number_of_bins), pdf_initial_2[j].reshape(1, number_of_bins), pdf_joint, logbase, ) max_I[0] = np.amax(mi_init) # Time series mutual information for t in xrange(times_sampled_len): mi = np.ndarray((len(times_sampled[t][sample_elements_2])), dtype="float") # Mutual information in time t for j in xrange(len(times_sampled[t][sample_elements_2])): # Calculate joint pdf from initial state and time t pdf_joint = PDF.joint( initial_sampled[i].reshape(1, initial_sampled_i_len), bin_values, continuous_bins, times_sampled[t][sample_elements_2][j].reshape(1, len(times_sampled[t][sample_elements_2][j])), bin_values, continuous_bins, ) # Mutual information mi[j] = MI.calculate( pdf_initial[i].reshape(1, number_of_bins), pdf_t[t, j, :].reshape(1, number_of_bins), pdf_joint, logbase, ) max_I[t + 1] = np.amax(mi) # Find t crossing target decay for t in xrange(times_sampled_len): # Interpolate when found if max_I[t + 1] - h_target < 0: t1 = t t2 = t + 1 found = True h1 = max_I[t1] h2 = max_I[t2] if h2 - h1 == 0: IDT_var[i] = 0 else: IDT_var[i] = (t1 + (t2 - t1) * (h_target - h1) / (h2 - h1)) * dt break # Setting maximum IDT value when not found if not found: IDT_var[i] = IDT_max return IDT_var
K1.append(k) V1.append(np.sum(V)) #print t #print '\r',v, #sys.stdout.flush() print 'time do loop fortran: ', time.time()-start tempo = np.array(tempo) plt.title("termoandersen") plt.plot(tempo,K1,'g-',ms=1,label="Kinetic energy fortran") plt.plot(tempo,V1,'r-',ms=1,label="Potential energy fortran") plt.show() #Pair distributions function c,hist = PDF.gr(X,Y,R2) hist1 = hist + 0.0 #mean on time for Pair distribution function for i in range(0,100): c,hist = PDF.gr(X,Y,R2) hist1 = hist1 + hist for j in range(0,100): fx,fy,V,R2 = forcas.lennardjones(size,p,X,Y,l2) x,y,vx,vy = dymol.integrate(x,y,vx,vy,fx,fy,dt) p = np.c_[x,y] HIST = hist1/100. plt.plot(c,HIST) plt.title("Pair distribution function density = 1.") plt.xlabel("dist")
def convert_to_pdf(html, **kwargs): print "rhinocloud.utils.pdf.convert_to_pdf() is deprecated! Please use rhinocloud.utils.PDF.render()" return PDF.render(html.encode("UTF-8"))
def merge(args): pdf.merge(args.pdfs, args.output)
class GUI2_BCT: def __init__(self, maestro): self.master = maestro #GPIO.setmode(GPIO.BOARD) self.banderaMD = False self.banderaMI = False '''self.control_pins = [3,5,7] for pin in self.control_pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, 0)''' #self.AccM = MotorPAP() #Esquema del marco #self.marco = Frame(maestro) self.marco1 = maestro self.marco1.grid() #self.marco1.resizable(True) style.use("ggplot") self.bandera = False # IMPORTACIÖN DE LAS CLASES self.fW = wFile() self.docPDF = PDF() self.num_prueb = 0 self.num_pruebaR = False self.xyValue = [] self.tempor = 0 #------------------------------CREAR GRAFICA--------------------------------- self.fig = Figure(figsize=(12.8, 4.8), dpi=100) self.a = self.fig.add_subplot(111) self.canvas = FigureCanvasTkAgg( self.fig, self.marco1) # CREAR AREA DE DIBUJO DE TKINTER. self.canvas.draw() self.canvas.get_tk_widget().grid(row=0, column=0, columnspan=5) #-------------------GUI (Botones, etiquetas y textbox)------------------------- self.pdfB = Button(self.marco1, text="Generar informe\nPDF", command=self.exportPDF) self.pdfB.grid(row=1, column=3) #Inicializar imagenes self.imgbtnAr = PhotoImage( file= '/home/pi/Desktop/InterfazG-BCT/resources/img/button/flechaArriba.png' ) self.imgbtnAb = PhotoImage( file= '/home/pi/Desktop/InterfazG-BCT/resources/img/button/flechaAbajo.png' ) self.imgbtnPa = PhotoImage( file= '/home/pi/Desktop/InterfazG-BCT/resources/img/button/botonR.png') self.imgbtnArr = PhotoImage( file= '/home/pi/Desktop/InterfazG-BCT/resources/img/button/botonV.png') self.imgbtnRe = PhotoImage( file= '/home/pi/Desktop/InterfazG-BCT/resources/img/button/reiniciar.png' ) # Botón cerrar self.button = Button(self.marco1, text="CERRAR", command=self.cerrar, fg="white", bg='red') self.button.grid(row=1, column=4) # Botón arriba self.arrB = Button(self.marco1, image=self.imgbtnAr) self.arrB['command'] = self.Arriba self.arrB.grid(row=1, column=0) # Botón abajo self.abaB = Button(self.marco1, image=self.imgbtnAb) self.abaB['command'] = self.Abajo self.abaB.grid(row=2, column=0) #etiquetas para instrucciones self.instruccion = Label(self.marco1, text='BCT') self.instruccion.grid(row=1, column=1, sticky="n") #Combobox para respuesta self.txtBCT = Text(self.marco1, width=20, height=2, wrap=WORD) self.txtBCT.grid(row=1, column=1, sticky="s") #etiquetas para instrucciones self.instruccionP = Label(self.marco1, text='Desplazamiento') self.instruccionP.grid(row=1, column=2, sticky="n") #Combobox para respuesta self.txtPos = Text(self.marco1, width=20, height=2, wrap=WORD) self.txtPos.grid(row=1, column=2, sticky="s") #Boton de inicio de prueba self.StartB = Button(self.marco1, image=self.imgbtnArr) self.StartB['command'] = self.StartG self.StartB.grid(row=2, column=1) #Boton de reset de prueba self.ResetB = Button(self.marco1, image=self.imgbtnRe) self.ResetB['command'] = self.resetFile self.ResetB.grid(row=2, column=2) #Boton de paro de prueba self.StopB = Button(self.marco1, image=self.imgbtnPa, text='Paro') self.StopB['command'] = self.StopG self.StopB.grid(row=2, column=3) #Boton para iniciar ventana donde se agregan datos de la caja self.ventanaIN = Button(self.marco1, text='Ingrese datos\n de la caja') self.ventanaIN['command'] = self.ventanaDATA self.ventanaIN.grid(row=2, column=4) #-----------------------AÑADIR BARRA DE HERRAMIENTAS-------------------------- self.toolbarFrame = Frame(self.marco1) self.toolbarFrame.grid(row=3, column=0, columnspan=5) self.toolbar = NavigationToolbar2Tk(self.canvas, self.toolbarFrame) self.toolbar.grid(row=4, column=0, columnspan=4) self.ani = animation.FuncAnimation(self.fig, self.animate, interval=500) self.gg = True #Bandera de actividad de la ventana de ingreso de datos self.banderaDATA = False #Bandera de ingreso de datos self.alturaC = 0 self.anchoC = 0 self.largoC = 0 self.Cliente = "" self.Producto = "" self.InfoCj = [] self.resetFile(False) def ventanaDATA(self): self.banderaDATA = True if self.gg == True: print 'Hola ventana' #self.marco1.iconify() self.marco2 = DATAin(self.master) #self.marco1.wait_window(self.marco2.top) self.gg = False #self.marco1.deiconify() elif (self.marco2.alturaDATA, self.marco2.anchoDATA, self.marco2.largoDATA) != 0: print 'Hola ya ingreso' tkMessageBox.showinfo( 'Atención', 'Ya ingreso los datos de la caja, si desea corregir los datos presione el botón de RESET' ) else: print 'Hola ventana abierta' tkMessageBox.showinfo( 'Atención', 'Ya se encuentra abierta la ventana, favor de verificar') def Arriba(self): if self.banderaMI == True: self.banderaMD = True self.banderaMI = False '''GPIO.output(5, 0) GPIO.output(3, 1)''' print "Boton arriba pulsado cuando abajo esta pulsado" elif self.banderaMD == False: self.banderaMD = True #GPIO.output(3, 1) print "Boton arriba pulsado" else: self.banderaMD = False #GPIO.output(3, 0) print "Boton arriba pulsado de nuevo" def Abajo(self): if self.banderaMD == True: self.banderaMI = True self.banderaMD = False '''GPIO.output(3, 0) GPIO.output(5, 1)''' print "Boton abajo pulsado cuando arriba esta pulsado" elif self.banderaMI == False: self.banderaMI = True #GPIO.output(5, 1) print "Boton abajo pulsado" else: self.banderaMI = False #GPIO.output(5, 0) print "Boton abajo pulsado de nuevo" def exportPDF(self): if self.bandera == True: self.StopG() tkMessageBox.showerror("Atención", "Se detuvo la prueba por seguridad") # elif self.bandera == False: # print "Inserte datos" if self.num_prueb == 0: tkMessageBox.showinfo( 'Atención', 'Debe realizar la prueba antes de exportar los datos') elif self.num_prueb != 0 and self.num_pruebaR: #and path.exists('/home/pi/Desktop/ProgGUI/GUI/resources/graf/GraficoBCT_{}.png'.format(self.num_pruebaR)): # if self.num_prueb == 1: # self.docPDF.load_data(largo = self.largoC, ancho = self.anchoC, alto = self.alturaC, prod = self.Producto, clie = self.Cliente, datos = self.InfoCj) desp = float(self.xyValue[0]) * 0.005 self.xyValue[0] = 0 self.docPDF.add_PDF(self.segundos, self.xyValue[2], desp) self.num_pruebaR = False answ = tkMessageBox.askyesno( "Atención", "Datos recopilados en PDF, ¿Desea realizar otra pueba?") if answ == False: self.docPDF.load_data(largo=self.largoC, ancho=self.anchoC, alto=self.alturaC, prod=self.Producto, clie=self.Cliente, datos=self.InfoCj) self.docPDF.build_PDF() tkMessageBox.showinfo( 'Atención', "Reporte creado con éxito, Se abrirá una ventana donde podrá realizar diferentes acciones con el reporte" ) self.final = VentanaFinal(self.master, self.now, self.docPDF.direc) #self.marco1.wait_window(self.final.marco3) #if respuesta==True: # commands.getoutput('qpdfview BCT_reporte.pdf') self.final.SaveObj(self.resetFile) #self.resetFile(False) else: self.resetFile(False, False) else: tkMessageBox.showinfo( 'Atención', 'Debe realizar la prueba antes de exportar los datos') def cerrar(self): if self.bandera == True: self.StopG() tkMessageBox.showerror("Atención", "Se detuvo la prueba por seguridad") respuesta = tkMessageBox.askyesno("Cuidado", "¿Quiere salir del programa?") if respuesta == True: #sys.exit() self.resetFile(False) #GPIO.cleanup() self.marco1.quit() def animate(self, i): if self.bandera == True: # PRIMERO OBTENEMOS EL VALOR self.xyValue = self.fW.EscribeArch(False) pullData = open( "/home/pi/Desktop/InterfazG-BCT/resources/sampleText.txt", "r").read() dataList = pullData.split('\n') self.xList = [] self.yList = [] for eachLine in dataList: if len(eachLine) > 1: x, y = eachLine.split(',') self.xList.append(float(x)) self.yList.append(float(y)) self.a.clear() print(str(self.xyValue) + " Animate") self.a.plot(self.xList, self.yList) self.a.set_ylabel("BCT (kg)") self.a.set_xlabel('Desplazamiento (mm)') self.tempor += 1 self.esctxtCB() else: self.a.clear() self.a.set_ylabel("BCT (kg)") self.a.set_xlabel('Desplazamiento (mm)') def resetFile(self, edo=True, borra=True): if edo == True: if self.num_prueb == 0 and self.gg == True: tkMessageBox.showinfo( 'Atención', 'El dispositivo se encuentra en su estado inicial') else: respuesta = tkMessageBox.askyesno( "Cuidado", "¿Desea reiniciar la prueba actual?, se eliminarán los datos obtenidos" ) if respuesta == True: self.ani.event_source.start() self.xyValue = self.fW.EscribeArch(True) print(str(self.xyValue) + " resetFile1") self.esctxtCB() self.bandera = False self.StopG() self.num_prueb = 0 self.gg = True self.docPDF.reset_num(self.now) # self.ventanaDATA() else: self.ani.event_source.start() self.xyValue = self.fW.EscribeArch(True) #print(str(self.xyValue) + " resetFile0") self.esctxtCB() self.bandera = False if borra == (not False): self.num_prueb = 0 self.gg = True self.now = datetime.now() self.docPDF.reset_num(self.now) self.banderaDATA = False try: comando = 'mv /home/pi/Desktop/InterfazG-BCT/resources/graf/*.png /home/pi/Desktop/InterfazG-BCT/resources/graf/old' commands.getoutput(comando) except: print 'Imagenes ya eliminadas' self.ventanaDATA() print(str(self.xyValue) + " resetFile0 ") + str(borra) def StartG(self): if self.banderaDATA == True: self.alturaC = self.marco2.alturaDATA self.anchoC = self.marco2.anchoDATA self.largoC = self.marco2.largoDATA self.Cliente = self.marco2.cliente self.Producto = self.marco2.Producto try: self.InfoCj = self.marco2.Datos except: print 'No coloco datos extras' self.num_prueb += 1 print self.alturaC, self.anchoC, self.largoC respuesta = tkMessageBox.askyesno( "Cuidado", "¿Está seguro de iniciar la prueba, con los siguientes datos?: \n {}cm de alto, {}cm de ancho, {}cm de largo" .format(self.alturaC, self.anchoC, self.largoC)) if respuesta == True: self.num_pruebaR = True print "Second number state " + str(self.num_pruebaR) #GPIO.output(7, 1) self.instanteInicial = datetime.now() if self.bandera == False: self.ani.event_source.start() #INICIA/REANUDA ANIMACIÓN self.bandera = True else: self.num_prueb -= 1 else: tkMessageBox.showerror('Atención', 'Debe ingresar los datos de la caja') print 'Numero de pruebas en ventana main ' + str(self.num_prueb) def StopG(self): if self.bandera == True: self.ani.event_source.stop() #DETIENE ANIMACIÓN self.instanteFinal = datetime.now() tiempo = self.instanteFinal - self.instanteInicial self.segundos = tiempo.seconds self.bandera = False plt.ioff() #GPIO.output(7, 0) figs = plt.figure(figsize=(7, 3.9), dpi=100) pltAr = figs.add_subplot(111) try: pltAr.plot(self.xList, self.yList) except Exception: print 'error' plt.xlabel('Desplazamiento (mm)') plt.ylabel("BCT (kg)") plt.savefig( '/home/pi/Desktop/InterfazG-BCT/resources/graf/GraficoBCT_{}.png'. format(self.num_prueb), dpi=80, transparent=True) print("Grafico creado") plt.clf() def esctxtCB(self): self.txtBCT.delete(0.0, END) self.txtBCT.insert(0.0, self.xyValue[1]) self.txtPos.delete(0.0, END) self.txtPos.insert(0.0, self.xyValue[0])
def system(initial, times, epsilon, dt, bin_values, continuous_bins, logbase="log2"): """ IDT system metric Input: initial Initial data NxP N = elements P = population times Time state data TxNxP T = time series N = elements P = population epsilon epsilon parameter dt Number of timesteps between time series bin_values values of the bins continuous_bins true if the values of the bins are continuous logbase Base for the logarithm ("log2", "log", "log10") Returns: IDT N N = elements """ assert logbase in ["log2", "log", "log10"], 'Logbase parameter must be one of ("log2", "log", "log10")' numTime = len(times) numElems = len(times[0]) # Initial entropy h_initial = shannon.calculate(PDF.single(initial, bin_values, continuous_bins), logbase) # Temporal entropy h_t = np.ndarray((numTime, numElems), dtype="float") for t in xrange(numTime): h_t[t] = shannon.calculate(PDF.single(times[t], bin_values, continuous_bins), logbase) IDT_var = np.ndarray(numElems, dtype="float") for i in xrange(numElems): h_target = h_initial[i] if h_target - epsilon > 0: h_target = h_target - epsilon found = False for t in xrange(numTime): if h_target - h_t[t, i] < 0: t1 = t - 1 t2 = t found = True break if found: if t1 < 0: h1 = 0 else: h1 = h_t[t1, i] h2 = h_t[t2, i] x1 = t1 + 1 x2 = t2 + 1 if h2 - h1 == 0: IDT_var[i] = 0 else: IDT_var[i] = (x1 + (x2 - x1) * (h_target - h1) / (h2 - h1)) * dt else: IDT_var[i] = numTime * dt return IDT_var
# Start value for pygame user events. EVENT_TIMER = pygame.USEREVENT + 1 # Lock to prevent ELM327 communications occuring when an existing one still running. LockELM327 = _thread.allocate_lock() # List of visual class instances to be flashed. FlashVisuals = {} # /***************************************/ # /* Create application class instances. */ #/***************************************/ ThisELM327 = ELM327.ELM327() ThisDisplay = Display.Display() ThisPDF = PDF.PDF() #/******************************************************/ #/* Display visual instances in their current Z order. */ #/******************************************************/ def DebugDisplayZOrder(): Count = 0 for ThisVisual in Visual.VisualZOrder: Count += 1 print(str(Count) + " " + ThisVisual.GetName() + " " + str(ThisVisual)) #/************************************************/ #/* Apply the application configuration options. */ #/************************************************/
qx, qy = qx / np.sqrt(qx**2 + qy**2), qy / np.sqrt(qx**2 + qy**2) psi = g * np.sqrt(kb * T * mass * beta / dt) * np.random.normal( 0, 1, 1) #Ec.append(np.sum(mass*0.5*(vx*vx+vy*vy))) #Ep.append(np.sum(V)) #Er.append(np.sum(I*w*w*0.5)) #time.append(i*dt) #rscl = 1 #dscl = 1 #rbin = (np.max(x)-np.min(x))/rscl #dbin = (np.max(y)-np.min(y))/dscl c, hist = PDF.gr(X, Y, R2) plt.plot(c, hist, label="T=" + str(T)) plt.xlabel(r"distance between particles $\mu m$") plt.ylabel("Pair distribution function g(r)") plt.legend() plt.show() exit() f, ax = plt.subplots(2, sharex=True) plt.suptitle("Energy of the system") ax[0].plot(time, Ec, 'g.-', ms=1, label="Kinetic energy") ax[0].plot(time, Ep, 'm.-', ms=1, label="Potential energy") ax[0].legend(loc=2) ax[1].plot(time, Er, 'r.-', ms=1, label="Rotational energy") ax[0].set_xlabel(r"time passed ($seconds$)") ax[0].set_ylabel(r'energy ($ mg \mu m^2 /s^2 $) ')
def __init__(self, maestro): self.master = maestro #GPIO.setmode(GPIO.BOARD) self.banderaMD = False self.banderaMI = False '''self.control_pins = [3,5,7] for pin in self.control_pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, 0)''' #self.AccM = MotorPAP() #Esquema del marco #self.marco = Frame(maestro) self.marco1 = maestro self.marco1.grid() #self.marco1.resizable(True) style.use("ggplot") self.bandera = False # IMPORTACIÖN DE LAS CLASES self.fW = wFile() self.docPDF = PDF() self.num_prueb = 0 self.num_pruebaR = False self.xyValue = [] self.tempor = 0 #------------------------------CREAR GRAFICA--------------------------------- self.fig = Figure(figsize=(12.8, 4.8), dpi=100) self.a = self.fig.add_subplot(111) self.canvas = FigureCanvasTkAgg( self.fig, self.marco1) # CREAR AREA DE DIBUJO DE TKINTER. self.canvas.draw() self.canvas.get_tk_widget().grid(row=0, column=0, columnspan=5) #-------------------GUI (Botones, etiquetas y textbox)------------------------- self.pdfB = Button(self.marco1, text="Generar informe\nPDF", command=self.exportPDF) self.pdfB.grid(row=1, column=3) #Inicializar imagenes self.imgbtnAr = PhotoImage( file= '/home/pi/Desktop/InterfazG-BCT/resources/img/button/flechaArriba.png' ) self.imgbtnAb = PhotoImage( file= '/home/pi/Desktop/InterfazG-BCT/resources/img/button/flechaAbajo.png' ) self.imgbtnPa = PhotoImage( file= '/home/pi/Desktop/InterfazG-BCT/resources/img/button/botonR.png') self.imgbtnArr = PhotoImage( file= '/home/pi/Desktop/InterfazG-BCT/resources/img/button/botonV.png') self.imgbtnRe = PhotoImage( file= '/home/pi/Desktop/InterfazG-BCT/resources/img/button/reiniciar.png' ) # Botón cerrar self.button = Button(self.marco1, text="CERRAR", command=self.cerrar, fg="white", bg='red') self.button.grid(row=1, column=4) # Botón arriba self.arrB = Button(self.marco1, image=self.imgbtnAr) self.arrB['command'] = self.Arriba self.arrB.grid(row=1, column=0) # Botón abajo self.abaB = Button(self.marco1, image=self.imgbtnAb) self.abaB['command'] = self.Abajo self.abaB.grid(row=2, column=0) #etiquetas para instrucciones self.instruccion = Label(self.marco1, text='BCT') self.instruccion.grid(row=1, column=1, sticky="n") #Combobox para respuesta self.txtBCT = Text(self.marco1, width=20, height=2, wrap=WORD) self.txtBCT.grid(row=1, column=1, sticky="s") #etiquetas para instrucciones self.instruccionP = Label(self.marco1, text='Desplazamiento') self.instruccionP.grid(row=1, column=2, sticky="n") #Combobox para respuesta self.txtPos = Text(self.marco1, width=20, height=2, wrap=WORD) self.txtPos.grid(row=1, column=2, sticky="s") #Boton de inicio de prueba self.StartB = Button(self.marco1, image=self.imgbtnArr) self.StartB['command'] = self.StartG self.StartB.grid(row=2, column=1) #Boton de reset de prueba self.ResetB = Button(self.marco1, image=self.imgbtnRe) self.ResetB['command'] = self.resetFile self.ResetB.grid(row=2, column=2) #Boton de paro de prueba self.StopB = Button(self.marco1, image=self.imgbtnPa, text='Paro') self.StopB['command'] = self.StopG self.StopB.grid(row=2, column=3) #Boton para iniciar ventana donde se agregan datos de la caja self.ventanaIN = Button(self.marco1, text='Ingrese datos\n de la caja') self.ventanaIN['command'] = self.ventanaDATA self.ventanaIN.grid(row=2, column=4) #-----------------------AÑADIR BARRA DE HERRAMIENTAS-------------------------- self.toolbarFrame = Frame(self.marco1) self.toolbarFrame.grid(row=3, column=0, columnspan=5) self.toolbar = NavigationToolbar2Tk(self.canvas, self.toolbarFrame) self.toolbar.grid(row=4, column=0, columnspan=4) self.ani = animation.FuncAnimation(self.fig, self.animate, interval=500) self.gg = True #Bandera de actividad de la ventana de ingreso de datos self.banderaDATA = False #Bandera de ingreso de datos self.alturaC = 0 self.anchoC = 0 self.largoC = 0 self.Cliente = "" self.Producto = "" self.InfoCj = [] self.resetFile(False)
def exportbutton_clicked(): PDF(db, shoppingbag, filedialog.askdirectory(), vorname, nachname, email, telefon, strasse, plz, ort, list_products, shoppingbag_instance)