def button_press(self, event): """ Handle button presses, detect if we are going to move any poles/zeros""" # find closest pole/zero if (event.xdata != None and event.ydata != None): new = event.xdata + 1.0j*event.ydata tzeros = list(abs(self.zeros-new)) tpoles = list(abs(self.poles-new)) if (size(tzeros) > 0): minz = min(tzeros) else: minz = float('inf') if (size(tpoles) > 0): minp = min(tpoles) else: minp = float('inf') if (minz < 2 or minp < 2): if (minz < minp): # Moving zero(s) self.index1 = tzeros.index(minz) self.index2 = list(self.zeros).index( conj(self.zeros[self.index1])) self.move_zero = True else: # Moving pole(s) self.index1 = tpoles.index(minp) self.index2 = list(self.poles).index( conj(self.poles[self.index1])) self.move_zero = False
def button_press(self, event): """ Handle button presses, detect if we are going to move any poles/zeros""" # find closest pole/zero if event.xdata != None and event.ydata != None: new = event.xdata + 1.0j*event.ydata tzeros = list(abs(self.zeros-new)) tpoles = list(abs(self.poles-new)) if (size(tzeros) > 0): minz = min(tzeros) else: minz = float('inf') if (size(tpoles) > 0): minp = min(tpoles) else: minp = float('inf') if (minz < 2 or minp < 2): if (minz < minp): # Moving zero(s) self.index1 = tzeros.index(minz) self.index2 = list(self.zeros).index( conj(self.zeros[self.index1])) self.move_zero = True else: # Moving pole(s) self.index1 = tpoles.index(minp) self.index2 = list(self.poles).index( conj(self.poles[self.index1])) self.move_zero = False
def solveCell(board, row, col): #print("Row: ", row, " Col: ", col) #if(checkCell(row, col)): return False band = checkBand(board, row) if(size(band) == 1): #print("Solved!", band[0],"at [",row,",",col,"]") #print("solved band") board[row][col] = band[0] return True stack = checkStack(board, col) if(size(stack) == 1): #print("Solved!", stack[0], "at [",row,",",col,"]") #print("solved stack") board[row][col] = stack[0] return True square = checkSquare(findSquare(board, row,col)) if(size(square) == 1): #print("Solved: ", square[0], "at [",row,",",col,"]") #print("solved square") board[row][col] = square[0] return True all_possible = [] all_possible = [x for x in band if x in band and x in stack and x in square] #print(all_possible) if(size(all_possible) == 1): #print("Solved using reduction", all_possible[0], "at [",row,",",col,"]") board[row][col] = all_possible[0] return True elif(size(all_possible) == 0): print("ERROR: NO POSSIBLE: ", all_possible, "at [",row,",",col,"]") print(board) else: return False
def LSTM_analyse(self, y_test, yhat, final_cols): correct_dir = [] for i in range(len(final_cols)): for j in range(len(final_cols[i][self.timestep - 1])): if y_test[i][j] < final_cols[i][self.timestep - 1][j]: if yhat[i][j] < final_cols[i][self.timestep - 1][j]: correct_dir.append(1) else: correct_dir.append(0) elif y_test[i][j] > final_cols[i][self.timestep - 1][j]: if yhat[i][j] > final_cols[i][self.timestep - 1][j]: correct_dir.append(1) else: correct_dir.append(0) correct = sum(correct_dir) total = correct / (size(correct_dir)) print("Number of total values", size(correct_dir)) print("All values correct: ", correct) print("Total percentage of correct:", total) correct_dir = [] for i in range(len(final_cols)): for j in range(len(final_cols[i][self.timestep - 1])): if y_test[i][0] < final_cols[i][self.timestep - 1][0]: if yhat[i][0] < final_cols[i][self.timestep - 1][0]: correct_dir.append(1) else: correct_dir.append(0) elif y_test[i][0] > final_cols[i][self.timestep - 1][0]: if yhat[i][0] > final_cols[i][self.timestep - 1][0]: correct_dir.append(1) else: correct_dir.append(0) elif y_test[i][3] < final_cols[i][self.timestep - 1][3]: if yhat[i][3] < final_cols[i][self.timestep - 1][3]: correct_dir.append(1) else: correct_dir.append(0) elif y_test[i][3] > final_cols[i][self.timestep - 1][3]: if yhat[i][3] > final_cols[i][self.timestep - 1][3]: correct_dir.append(1) else: correct_dir.append(0) correct = sum(correct_dir) total = correct / (size(correct_dir)) print("Number of total values", size(correct_dir)) print("All values correct: ", correct) print("Total percentage of correct:", total)
def princomp_B(A, numpc=0): """ Compute 1st Principal Component. Function modified from: http://glowingpython.blogspot.ch/2011/07/principal-component-analysis-with-numpy.html Parameters ---------- A : object of type MstConfiguration Contains the following attributes: subtract_column_mean_at_start (bool), debug (bool), use_gfp_peaks (bool), force_avgref (bool), set_gfp_all_1 (bool), use_smoothing (bool), gfp_type_smoothing (string), smoothing_window (int), use_fancy_peaks (bool), method_GFPpeak (string), original_nr_of_maps (int), seed_number (int), max_number_of_iterations (int), ERP (bool), correspondance_cutoff (double): numpc : int number of principal components Returns ------- coeff: array first principal component """ M = A.T a = np.dot( M, M.T ) #get covariance matrix by matrix multiplication of data with transposed data [latent, coeff] = eig(a) p = size(coeff, axis=1) idx = argsort(latent) # sorting the eigenvalues idx = idx[::-1] # in ascending order # sorting eigenvectors according to the sorted eigenvalues coeff = coeff[:, idx] #latent = latent[idx] # sorting eigenvalues if numpc < p or numpc >= 0: coeff = coeff[:, list(range(numpc))] # cutting some PCs #score = dot(coeff.T,M) # projection of the data in the new space return coeff
def princomp_B(A,numpc=0): """ Compute 1st Principal Component. Function modified from: http://glowingpython.blogspot.ch/2011/07/principal-component-analysis-with-numpy.html Parameters ---------- A : object of type MstConfiguration Contains the following attributes: subtract_column_mean_at_start (bool), debug (bool), use_gfp_peaks (bool), force_avgref (bool), set_gfp_all_1 (bool), use_smoothing (bool), gfp_type_smoothing (string), smoothing_window (int), use_fancy_peaks (bool), method_GFPpeak (string), original_nr_of_maps (int), seed_number (int), max_number_of_iterations (int), ERP (bool), correspondance_cutoff (double): numpc : int number of principal components Returns ------- coeff: array first principal component """ M=A.T a=numpy.dot(M,M.T) #get covariance matrix by matrix multiplication of data with transposed data [latent,coeff]=eig(a) p = size(coeff,axis=1) idx = argsort(latent) # sorting the eigenvalues idx = idx[::-1] # in ascending order # sorting eigenvectors according to the sorted eigenvalues coeff = coeff[:,idx] #latent = latent[idx] # sorting eigenvalues if numpc < p or numpc >= 0: coeff = coeff[:,range(numpc)] # cutting some PCs #score = dot(coeff.T,M) # projection of the data in the new space return coeff
def createRDecisionTrees(self, path): for filename in os.listdir(path): if filename=='train.csv': with open(os.path.join(path,filename)) as infile: f = csv.reader(infile) aux = f.next() # skip the header x = [] y = [] for line in f: if size(line) > 1: if self.option == 1: data = [converter(line[2]), converter(line[3]), converter(line[4]), converter(line[7]), converter(line[9])] y.append(converter(line[6])) x.append(data) elif self.option == 2: auxDeputy = fetchDeputyParty(line[2]) presence = fetchAssistance(line[7], line[2]) sessao = fetchSessionType(line[7], line[8]) data = [converter(line[2]), converter(line[3]), converter(line[4]), converter(line[7]), converter(line[9]), encodeParty(auxDeputy['party']), encodeState(auxDeputy['state']), converter(presence), converter(sessao)] y.append(converter(line[6])) x.append(data) clf = RandomForestClassifier(n_estimators=5) clf.fit(x, y) ##self.printTree(clf) self.testPrediction(clf, path, 'dtreeResult')
def run(): # Por definición, un escalar carece de dimensión, por lo que tanto len como shape me retornan un error escalar = 2 ic(escalar) vector = np.array([escalar, escalar + 1]) ic(vector) # Shape dice que vector tiene 3 escalares, sin filas ni columnas vector_s = vector.shape vector_l = len(vector) vector_z = size(vector) ic(vector_s) ic(vector_l) ic(vector_z) matriz = np.array([vector * 4, vector * 3, vector + 10, vector]) ic(matriz) # Shape dice que tiene 4 vectores, cada vector con 4 filas y 2 columnas matriz_s = matriz.shape matriz_l = len(matriz) matriz_z = size(matriz) ic(matriz_s) ic(matriz_l) ic(matriz_z) tensor = np.array([[matriz * 3], [matriz * 2]]) ic(tensor) tensor_s = tensor.shape tensor_l = len(tensor) tensor_z = size(tensor) ic(tensor_s) ic(tensor_l) ic(tensor_z) tensor_squeeze = tensor.squeeze() ic(tensor_squeeze) # -Shape dice que tiene 2 matrices, cada matriz de 4 filas y 2 columnas tensor_squeeze_s = tensor_squeeze.shape tensor_squeeze_l = len(tensor_squeeze) tensor_squeeze_z = size(tensor_squeeze) ic(tensor_squeeze_s) ic(tensor_squeeze_l) ic(tensor_squeeze_z)
def date_to_index(self, date): "Returns the index corresponding to one given date, as an integer." if self.isvalid(): index = date.value - self[0].value if index < 0 or index > self.size: raise IndexError, "Date out of bounds!" return index else: index_asarray = (self == date.value).nonzero() if fromnumeric.size(index_asarray) == 0: raise IndexError, "Date out of bounds!" return index_asarray[0][0]
def find_dates(self, *dates): "Returns the indices corresponding to given dates, as an array." ifreq = self.freq c = numpy.zeros(self.shape, bool_) for d in corelib.flatargs(*dates): if d.freq != ifreq: d = d.asfreq(ifreq) c += (self == d.value) c = c.nonzero() if fromnumeric.size(c) == 0: raise IndexError, "Date out of bounds!" return c
def initDecTrees(self, path): for filename in os.listdir(path): if filename=='train.csv': with open(os.path.join(path,filename)) as infile: f = csv.reader(infile) aux = f.next() # skip the header x = [] y = [] for line in f: if size(line) > 1: if self.option == 1: data = [converter(line[2]), converter(line[3]), converter(line[4]), converter(line[7]), converter(line[9])] y.append(converter(line[6])) x.append(data) elif self.option == 2: auxDeputy = fetchDeputyParty(line[2]) data = [converter(line[2]), converter(line[3]), converter(line[4]), converter(line[7]), converter(line[9]), encodeParty(auxDeputy['party']), encodeState(auxDeputy['state'])] y.append(converter(line[6])) x.append(data) clf = RandomForestClassifier(n_estimators=5) clf.fit(x, y) return clf
def createSVMachine(self, path): for filename in os.listdir(path): if filename=='train.csv': with open(os.path.join(path,filename)) as infile: f = csv.reader(infile) aux = f.next() # skip the header x = [] y = [] for line in f: if size(line) > 1: if self.option == 1: data = [converter(line[2]), converter(line[3]), converter(line[4]), converter(line[7]), converter(line[9])] y.append(converter(line[6])) x.append(data) elif self.option == 2: auxDeputy = fetchDeputyParty(line[2]) data = [converter(line[2]), converter(line[3]), converter(line[4]), converter(line[7]), converter(line[9]), encodeParty(auxDeputy['party']), encodeState(auxDeputy['state'])] y.append(converter(line[6])) x.append(data) clf = svm.SVC() clf.fit(x, y) ##self.printTree(clf) self.testPrediction(clf, path)
#!/usr/bin/python3 from hmmlearn.hmm import GaussianHMM from numpy.core.fromnumeric import size from venus.stock_base import StockEventBase from dev_global.env import GLOBAL_HEADER import numpy as np event = StockEventBase(GLOBAL_HEADER) df = event.mysql.select_values('SH600000', 'trade_date,close_price,amplitude,volume') df.columns = ['trade_date', 'close', 'amp', 'volume'] # print(df.head(5)) close = np.array(df['close']) diff = np.diff(df['close']) amp = np.array(df['amp']) vol = np.array(df['volume']) A = np.column_stack([close[:500], vol[:500], amp[:500]]) B = np.column_stack([close[-500:], vol[-500:], amp[-500:]]) print(size(A)) print(size(diff[:500])) model = GaussianHMM(n_components=2, covariance_type='full', n_iter=2000).fit([diff]) print(model.startprob_) # print(model.transmat_) # print(model.means_) # print(model.covars_)
print ids_of_first_quarter print ids_of_three_quarters count = 0 for centrality in first_quarter: print count, centrality count += 1 order = 1 same_same = 0 same_same_but_different = 0 for record in first_quarter: print record[0] for vertex in range(order, size(ids_of_first_quarter)): # print "Getting myopic search from ", record[0], " to ", ids_of_first_quarter[vertex] myopic_path = get_myopic_path(graf, g_layout, record[0], ids_of_first_quarter[vertex]) shortest_path = graf.get_shortest_paths(v=record[0], to=ids_of_first_quarter[vertex], weights="weight") # dijsktra_path = graf.shortest_paths_dijkstra(source=record[0], target=ids_of_first_quarter[vertex], # weights="weight") # print "Myopic shortest path is ", myopic_path, " and size is ", size(myopic_path) # print "IGraph shortest path is ", shortest_path, " and size is ", size(shortest_path) - 1 # print "Dijkst shortest path is ", dijsktra_path if size(myopic_path) == size(shortest_path) - 1: same_same += 1 else: same_same_but_different += 1 order += 1
def MLP_analyse(y_test, yhat, final_cols): # Loop checks each value and whether it moves in the correct direction # This loop looks at all columns correct_dir = [] for i in range(len(final_cols)): for j in range(len(final_cols[i])): if y_test[i][j] < final_cols[i][j]: if yhat[i][j] < final_cols[i][j]: correct_dir.append(1) else: correct_dir.append(0) elif y_test[i][j] > final_cols[i][j]: if yhat[i][j] > final_cols[i][j]: correct_dir.append(1) else: correct_dir.append(0) correct = sum(correct_dir) total = correct / (size(correct_dir)) print("Number of total values", size(correct_dir)) print("All values correct: ", correct) print("Total percentage of correct:", total) # This loops applies the same logic but applies to open and close column as they are the more important correct_dir = [] for i in range(len(final_cols)): if y_test[i][0] < final_cols[i][0]: if yhat[i][0] < final_cols[i][0]: correct_dir.append(1) # print("========") # print("Current: ",final_cols[i][0]) # print("Next: ",y_test[i][0]) # print("Predicted: ", round(yhat[i][0],5)) else: correct_dir.append(0) elif y_test[i][0] > final_cols[i][0]: if yhat[i][0] > final_cols[i][0]: correct_dir.append(1) # print("========") # print("Current: ",final_cols[i][0]) # print("Next: ",y_test[i][0]) # print("Predicted: ", round(yhat[i][0],5)) else: correct_dir.append(0) elif y_test[i][3] < final_cols[i][3]: if yhat[i][3] < final_cols[i][3]: correct_dir.append(1) # print("========") # print("Current: ",final_cols[i][3]) # print("Next: ",y_test[i][3]) # print("Predicted: ", round(yhat[i][3],5)) else: correct_dir.append(0) elif y_test[i][3] > final_cols[i][3]: if yhat[i][3] > final_cols[i][3]: correct_dir.append(1) # print("========") # print("Current: ",final_cols[i][3]) # print("Next: ",y_test[i][3]) # print("Predicted: ", round(yhat[i][3],5)) else: correct_dir.append(0) correct = sum(correct_dir) total = correct / (size(correct_dir)) print("Number of total values", size(correct_dir)) print("All values correct: ", correct) print("Total percentage of correct:", total)
def text_to_rcsv(text_file, edat_file, out_file, task): """ Converts text file produced by successful completion of E-Prime experiment to reduced csv. Considerably more complex than text_to_csv. Parameters ---------- text_file : str Raw E-Prime text file to convert. edat_file : str Raw E-Prime edat file paired with text_file. Only used for its file type, because sometimes files will differ between version of E-Prime (edat vs. edat2 suffix). out_file : str Name of output file (csv format) to generate. task : str Task name, used with dictionary from headers.pickle file to determine columns to keep. Examples ---------- >>> in_file = "subj0001_stop_signal_task-0.txt" >>> edat_file = "subj0001_stop_signal_task-0.edat2" >>> out_file = "subj0001_0.csv" >>> task = "TEST_STOPSIGNAL" >>> ce.text_to_rcsv(in_file, edat_file, out_file, task) Output file successfully created- subj0001_0.csv """ [_, edat_suffix] = os.path.splitext(edat_file) header_list = headers.get(task) replacements = replace_dict.get(task).get(edat_suffix) # Load the text file as a list. with open(text_file, "r") as fo: text_data = list(fo) # Remove unicode characters. filtered_data = [_strip(row) for row in text_data] # Determine where rows begin and end. start_index = [ i_row for i_row, row in enumerate(filtered_data) if row == "*** LogFrame Start ***" ] end_index = [ i_row for i_row, row in enumerate(filtered_data) if row == "*** LogFrame End ***" ] if (len(start_index) != len(end_index) or start_index[0] >= end_index[0]): print("Warning: LogFrame Starts and Ends do not match up.") n_rows = min(len(start_index), len(end_index)) # Find column headers and remove duplicates. all_headers = [] data_by_rows = [] for i_row in range(n_rows): one_row = filtered_data[start_index[i_row] + 1:end_index[i_row]] data_by_rows.append(one_row) for j_col in range(len(one_row)): split_header_idx = one_row[j_col].index(":") all_headers.append(one_row[j_col][:split_header_idx]) unique_headers = list(set(all_headers)) # Preallocate list of lists composed of NULLs. null_col = ["NULL"] * (n_rows + 1) data_matrix = [null_col[:] for i_col in range(len(unique_headers))] # Fill list of lists with relevant data from data_by_rows and # unique_headers. for i_col in range(len(unique_headers)): data_matrix[i_col][0] = unique_headers[i_col] for i_row in range(n_rows): for j_col in range(len(data_by_rows[i_row])): split_header_idx = data_by_rows[i_row][j_col].index(":") for k_header in range(len(unique_headers)): if (data_by_rows[i_row][j_col][:split_header_idx] == unique_headers[k_header]): data_matrix[k_header][ i_row + 1] = data_by_rows[i_row][j_col][split_header_idx + 1:].lstrip() # If a column is all NULLs except for the header and one value at the # bottom, fill the column up with that bottom value. # THIS SECTION NEEDS CLEANUP! for i_col, col in enumerate(data_matrix): rows_w_vals = [ j_cell for j_cell, cell in enumerate(col) if cell != "NULL" ] if len(rows_w_vals) == 2 and (rows_w_vals[1] == len(col) - 1 or rows_w_vals[1] == len(col) - 2 or rows_w_vals[1] == 1): data_matrix[i_col][1:len(col)] = ([col[rows_w_vals[1]]] * (len(col) - 1)) elif any([header in col[0] for header in fill_block]): for null_row in range(1, len(rows_w_vals)): first = rows_w_vals[null_row - 1] + 1 last = rows_w_vals[null_row] n_rows_to_fill = len( range(rows_w_vals[null_row - 1] + 1, rows_w_vals[null_row])) data_matrix[i_col][first:last] = (col[rows_w_vals[null_row]] * n_rows_to_fill) data_matrix[i_col] = col[:len(col) - 2] # Transpose data_matrix. t_data_matrix = _transpose(data_matrix) # Replace text headers with edat headers (replacement dict). Unnecessary if # your processing scripts are built around text files instead of edat # files. t_data_matrix[0] = [ replacements.get(item, item) for item in t_data_matrix[0] ] # Pare data_matrix down based on desired headers # Create list of columns with relevant headers. header_index = [t_data_matrix[0].index(header) for header in header_list] # Merge any columns that need to be merged. columns_to_merge = merge_cols.get(task) merge_col_names_list = merge_col_names.get(task) merged_data = [] for i_merge in range(len(merge_col_names_list)): merge_col_nums = [ t_data_matrix[0].index(hed) for hed in columns_to_merge[i_merge] ] data_to_merge = [data_matrix[col] for col in merge_col_nums] merged_data.append(_merge_lists(data_to_merge, "all_else")) merged_data[i_merge][0] = merge_col_names_list[i_merge] out_matrix = [[t_data_matrix[i_row][col] for col in header_index] for i_row in range(fn.size(t_data_matrix, 0))] # Transpose merged_data and append them to out_matrix. if len(merged_data) != 0: t_merged_data = _transpose(merged_data) for i_row in range(len(out_matrix)): out_matrix[i_row] = out_matrix[i_row] + t_merged_data[i_row] # Create column from which null index will be created. # Remove all instances of NULL by creating an index of NULL occurrences # and removing them from out_matrix. null_column_names = null_cols.get(task) null_column_index = [ header_index[header_list.index(column)] for column in null_column_names ] nulls_to_merge = [data_matrix[col_num] for col_num in null_column_index] merged_nulls_list = _merge_lists(nulls_to_merge, "all_null") null_index = sorted([ i_row for i_row in range(len(merged_nulls_list)) if merged_nulls_list[i_row] == "NULL" ], reverse=True) [out_matrix.pop(null_row) for null_row in null_index] try: with open(out_file, "wb") as fo: file_ = csv.writer(fo) for row in out_matrix: file_.writerow(row) print("Output file successfully created- {0}".format(out_file)) except IOError: print("Can't open output file- {0}".format(out_file))
def interactive_plot(arg_x, arg_y, x_min=0.0, x_max=1.0, x_stp=0.01, y_amp=1): button_color = '#fafad0' left_curve_color = '#00ff5f' right_curve_color = '#ff3f00' # TIMEIT = True TIMEIT = False fig, ax = plt.subplots( nrows=1, ncols=2, ) line, = ax[0].plot( arg_x, arg_y, ) ax[0].set(xlabel='k, 1/cm', ylabel='I r. u.', title="Raw spectra and sine") ax[0].grid() # right graph with rew spectra line_, = ax[1].plot( arg_x, arg_y, ) ax[1].set(xlabel='k, 1/cm', ylabel='I r. u.', title="Raw spectra and substracted spectra") ax[1].grid() # secondary axes def k2eV(arg): return 1.23984 * arg / 10000 def eV2k(arg): return 1.23984 * arg / 10000 secax = ax[0].secondary_xaxis('top', functions=(k2eV, eV2k)) secax.set_xlabel('E, eV') secax = ax[1].secondary_xaxis('top', functions=(k2eV, eV2k)) secax.set_xlabel('E, eV') #sine generator @njit def signal(amp, freq, phase, offset, cd_left, wd_left, cd_right, wd_right): # x = t but transformed to calculate large exponents x = map_(t, 0, 1) def gauss_func(): return (1 / ((np.exp((-x - cd_left + offset) / wd_left)) + (np.exp( (x - cd_right - offset) / wd_right)) + 1)) gauss = gauss_func() return ((amp * sin(2 * pi * freq * t + phase)) * gauss) # Adjust the subplots region to leave some space for the sliders and buttons fig.subplots_adjust(top=0.89, bottom=0.46, left=0.065, right=0.99, hspace=0.19, wspace=0.15) # t = np.arange(min(arg_x), max(arg_x), (max(arg_x) - min(arg_x))/1000) t = np.arange(x_min, x_max, x_stp) print("size of t: " + str(size(t))) values = namedtuple('values', 'min max default') amp_0 = values(0.01, 0.5, y_amp) freq_0 = values(0.00001, 0.01, 0.0001) if __name__ == "__main__": freq_0 = values(0.01, 10, 0.1) phase_0 = values(0, 2 * np.pi, np.pi) offset_0 = values(-1, 1, 0) cd_R = values(0, 1, 1) wd_R = values(0, 1, 0.1) cd_L = values(0, 1, 1) wd_L = values(0, 1, 0.1) # amp, freq, phase, offset, cd_left, wd_left, cd_right, wd_right placed in tuple default_sine_config = { 'amp': amp_0.default, 'freq': freq_0.default, 'phase': phase_0.default, 'offset': offset_0.default, 'wd_left': wd_L.default, 'cd_left': cd_L.default, 'cd_right': cd_R.default, 'wd_right': wd_R.default } # Draw the initial plot # The 'line' variable is used for modifying the line later line, = ax[0].plot(t, signal(**default_sine_config), linewidth=2, color=right_curve_color) ax[0].set_xlim([min(arg_x), max(arg_x)]) ax[0].set_ylim([min(arg_y), max(arg_y)]) line_, = ax[1].plot(arg_x, arg_y - signal(**default_sine_config), color=left_curve_color) # region # Add sliders for tweaking the parameters # Define an axes area and draw a slider in it amp_slider_ax = fig.add_axes( [0.25, 0.15, 0.6, 0.03], facecolor=button_color) #, axisbg=button_color amp_slider = Slider(amp_slider_ax, 'Amp', amp_0.min, amp_0.max, valinit=amp_0.default) # Draw frequency slider freq_slider_ax = fig.add_axes([0.25, 0.1, 0.6, 0.03], facecolor=button_color) freq_slider = Slider(freq_slider_ax, 'Freq', freq_0.min, freq_0.max, valinit=freq_0.default) #phase slider phase_slider_ax = fig.add_axes([0.25, 0.05, 0.6, 0.03], facecolor=button_color) phase_slider = Slider(phase_slider_ax, 'Phase', phase_0.min, phase_0.max, valinit=phase_0.default) #offset slider offset_slider_ax = fig.add_axes([0.25, 0.0, 0.6, 0.03], facecolor=button_color) offset_slider = Slider(offset_slider_ax, 'Offset', offset_0.min, offset_0.max, valinit=offset_0.default) # amount of attenuation by gauss function from left side cd_slider_ax_L = fig.add_axes([0.25, 0.25, 0.6, 0.03], facecolor=button_color) cd_slider_L = Slider(cd_slider_ax_L, 'Cd left', cd_L.min, cd_L.max, valinit=cd_L.default) # amount of attenuation by gauss function from right side cd_slider_ax_R = fig.add_axes([0.25, 0.35, 0.6, 0.03], facecolor=button_color) cd_slider_R = Slider(cd_slider_ax_R, 'Cd right', cd_R.min, cd_R.max, valinit=cd_R.default) # intensity of attenuation by gauss function from left side wd_slider_ax_L = fig.add_axes([0.25, 0.2, 0.6, 0.03], facecolor=button_color) wd_slider_L = Slider( wd_slider_ax_L, 'Wd left', wd_L.min, wd_L.max, valinit=wd_L.default, ) # intensity of attenuation by gauss function from right side wd_slider_ax_R = fig.add_axes([0.25, 0.3, 0.6, 0.03], facecolor=button_color) wd_slider_R = Slider(wd_slider_ax_R, 'Wd right', wd_R.min, wd_R.max, valinit=wd_R.default) # Define an action for modifying the line when any slider value changes def sliders_on_changed(val): if (TIMEIT): start = timer() val_sine_config = { 'amp': amp_slider.val, 'freq': freq_slider.val, 'phase': phase_slider.val, 'offset': offset_slider.val, 'cd_left': cd_slider_L.val, 'wd_left': wd_slider_L.val, 'cd_right': cd_slider_R.val, 'wd_right': wd_slider_R.val } line.set_ydata(signal(**val_sine_config)) line_.set_ydata(arg_y - signal(**val_sine_config)) fig.canvas.draw_idle() if (TIMEIT): print("time: " + str(timer() - start) + " sec") amp_slider.on_changed(sliders_on_changed) freq_slider.on_changed(sliders_on_changed) phase_slider.on_changed(sliders_on_changed) offset_slider.on_changed(sliders_on_changed) cd_slider_L.on_changed(sliders_on_changed) wd_slider_L.on_changed(sliders_on_changed) cd_slider_R.on_changed(sliders_on_changed) wd_slider_R.on_changed(sliders_on_changed) # Add a button for resetting the parameters reset_button_ax = fig.add_axes([0.05, 0.05, 0.1, 0.04], facecolor=button_color) reset_button = Button(reset_button_ax, 'Reset', color=button_color, hovercolor='0.975') def reset_button_on_clicked(mouse_event): freq_slider.reset() amp_slider.reset() phase_slider.reset() offset_slider.reset() cd_slider_R.reset() wd_slider_R.reset() cd_slider_L.reset() wd_slider_L.reset() reset_button.on_clicked(reset_button_on_clicked) # add a help button with breath info about how to use this app help_button_ax = fig.add_axes([0.05, 0.1, 0.1, 0.04], facecolor=button_color) help_button = Button(help_button_ax, 'Help', color=button_color, hovercolor='0.975') def help_button_on_clicked(mouse_event): hlp = help_window_class() hlp.main_winow() help_button.on_clicked(help_button_on_clicked) # TODO buttons to save and load slider values # TODO get max and min values of sliders automatically? but am not sure about that # endregion figManager = plt.get_current_fig_manager() try: figManager.window.showMaximized() except: pass fig.canvas.manager.set_window_title('PR spectra handler') plt.show()
''' 列表生成式能够快度的创建list 生成式 ''' from numpy.core.fromnumeric import size L=list(range(15,20)) print(L) L=list(x*x for x in range(1,11))# 输出1到10的平方 print(L) L=[x*x for x in range(1,11) if x%2 ==0] #输出1到10偶数的平方 print(L) L=[m*n for m in range(1,11) for n in range(11,21) if m%2==0 and n%2!=0 ] #双重循环 print(L) print(size(L)) import os print([d for d in os.listdir('.')]) #输出当前目录下的文件和目录 L1 = ['Hello', 'World', 18, 'Apple', None] L2=[x for x in L1 if isinstance(x, str)] #判断是不是字符串 print(L2)