Best Python code snippet using avocado_python
timed_decision_making_lib.py
Source:timed_decision_making_lib.py
1import numpy as np2from matplotlib import pyplot as plt3import os4from numba import jit5from .. import run6fs = 10 # font size7_color_list = ['blue', 'red', 'black', 'yellow', 'pink']8plt.rcParams["font.family"] = "Helvetica"9plt.style.use('default')10SMALL_SIZE = 811MEDIUM_SIZE = 1012BIGGER_SIZE = 1213plt.rc('font', size=fs) # controls default text sizes14plt.rc('axes', titlesize=fs) # fontsize of the axes title15plt.rc('axes', labelsize=fs) # fontsize of the x and y labels16plt.rc('xtick', labelsize=fs) # fontsize of the tick labels17plt.rc('ytick', labelsize=fs) # fontsize of the tick labels18plt.rc('legend', fontsize=fs) # legend fontsize19plt.rc('figure', titlesize=fs)20class LeftAlignAvr:21 def __init__(self, max_length):22 self.value = np.zeros((max_length,))23 self.value_2 = np.zeros((max_length,))24 self.number = np.zeros((max_length,))25 self.max_length = max_length26 def add(self, add_value):27 temp_length = len(add_value)28 self.value[0:temp_length] += add_value29 self.value_2[0:temp_length] += add_value * add_value30 self.number[0:temp_length] += 131 def return_average(self):32 zero_number_idx = np.argwhere(self.number <= 1)33 self.number = np.delete(self.number, zero_number_idx)34 self.value = np.delete(self.value, zero_number_idx)35 self.value_2 = np.delete(self.value_2, zero_number_idx)36 return self.value/self.number37 def return_sem(self):38 zero_number_idx = np.argwhere(self.number <= 1)39 self.number = np.delete(self.number, zero_number_idx)40 self.value = np.delete(self.value, zero_number_idx)41 self.value_2 = np.delete(self.value_2, zero_number_idx)42 return np.sqrt((self.value_2/self.number)-(self.value/self.number)**2)/np.sqrt(self.number)43class RightAlignAvr:44 def __init__(self, max_length):45 self.value = np.zeros((max_length,))46 self.value_2 = np.zeros((max_length,))47 self.number = np.zeros((max_length,))48 self.max_length = max_length49 def add(self, add_value):50 temp_length = len(add_value)51 self.value[self.max_length-temp_length:self.max_length] += add_value52 self.value_2[self.max_length-temp_length:self.max_length] += add_value * add_value53 self.number[self.max_length-temp_length:self.max_length] += 154 def return_average(self):55 zero_number_idx = np.argwhere(self.number <= 1)56 self.number = np.delete(self.number, zero_number_idx)57 self.value = np.delete(self.value, zero_number_idx)58 self.value_2 = np.delete(self.value_2, zero_number_idx)59 return self.value/self.number60 def return_sem(self):61 zero_number_idx = np.argwhere(self.number <= 1)62 self.number = np.delete(self.number, zero_number_idx)63 self.value = np.delete(self.value, zero_number_idx)64 self.value_2 = np.delete(self.value_2, zero_number_idx)65 return np.sqrt((self.value_2/self.number)-(self.value/self.number)**2)/np.sqrt(self.number)66@jit(nopython=True)67def local_maximum_location(signal, loc):68 if loc == 0:69 for x in range(len(signal)-1):70 if signal[x] >= signal[x+1]:71 return x72 return len(signal)-173 elif loc == len(signal)-1:74 for x in range(len(signal)-1, 0, -1):75 if signal[x-1] < signal[x]:76 return x77 return 078 elif signal[loc-1] < signal[loc]:79 for x in range(loc, len(signal) - 1):80 if signal[x] >= signal[x + 1]:81 return x82 return len(signal) - 183 else:84 for x in range(loc-1, 0, -1):85 if signal[x-1] < signal[x]:86 return x87 return 088@jit(nopython=True)89def no_greater_than_loc(sorted_array, value):90 for i in range(len(sorted_array)):91 if sorted_array[i] >= value:92 return i93 return len(sorted_array)94#@jit(nopython=True)95def p_n_neuron_split(output_neurons, input_neuron, local_peak_outputs, local_peak_input):96 index_of_duplicate = np.argwhere(output_neurons==input_neuron)97 if local_peak_outputs[-1] < local_peak_input:98 delim = len(local_peak_outputs)99 else:100 for i in range(len(local_peak_outputs)):101 if local_peak_outputs[i] >= local_peak_input:102 delim = i103 break104 if len(index_of_duplicate) == 0:105 return np.arange(delim, len(output_neurons)), np.arange(0, delim)106 else:107 if index_of_duplicate[0,0]>=delim:108 return np.concatenate([np.arange(delim, index_of_duplicate[0,0]), np.arange(index_of_duplicate[0,0]+1, len(output_neurons))]), np.arange(0, delim)109 else:#index_of_duplicate[0,0]<delim110 return np.arange(delim, len(output_neurons)), np.concatenate([np.arange(0, index_of_duplicate[0,0]), np.arange(index_of_duplicate[0,0]+1, delim)])111class WeightConnection:112 def __init__(self, stim_n, func_relevance_threshold=2.):113 '''114 :param firing_rate_binder: shape (stim, time, neuron)115 :param weight_hh: shape (input_n, output_n)116 :param time_points: shape (time_n,)117 '''118 self.stim_n = stim_n119 self.func_relevance_threshold = func_relevance_threshold120 self.p_result_list = [LeftAlignAvr(100) for i in range(self.stim_n)]121 self.n_result_list = [RightAlignAvr(100) for i in range(self.stim_n)]122 def reset_parameter(self, firing_rate_binder, weight_hh, time_points):123 self.firing_rate_binder = firing_rate_binder#.astype(np.float64)124 self.weight_hh = weight_hh125 self.time_points = time_points126 self.func_relevant_neuron = firing_rate_binder>self.func_relevance_threshold127 def weight_connection(self, input_neurons_1, output_neurons_1, local_peak_inputs, local_peak_outputs, stim_idx1, stim_idx2):128 order_idx_inputs = np.argsort(local_peak_inputs)129 order_idx_outputs = np.argsort(local_peak_outputs)130 local_peak_inputs = local_peak_inputs[order_idx_inputs]131 local_peak_outputs = local_peak_outputs[order_idx_outputs]132 input_neurons = input_neurons_1[order_idx_inputs]133 output_neurons = output_neurons_1[order_idx_outputs]134 weight = self.weight_hh[input_neurons, :][:, output_neurons]135 #print(weight.shape)136 stim_diff = np.abs(stim_idx1-stim_idx2)137 for i in range(len(local_peak_inputs)):138 p_neuron, n_neuron = p_n_neuron_split(output_neurons, input_neurons[i], local_peak_outputs, local_peak_inputs[i])139 self.p_result_list[stim_diff].add(weight[i, p_neuron])140 self.n_result_list[stim_diff].add(weight[i, n_neuron])141 def do(self):142 for time_point in self.time_points:143 func_relevance_neuron = np.argwhere(np.sum(self.func_relevant_neuron[:, time_point, :], axis=0) > 0).flatten()144 firing_rate = self.firing_rate_binder[:, time_point, func_relevance_neuron]145 max_stim = np.argmax(firing_rate, axis=0)146 func_relevant_neuron_single_time = [func_relevance_neuron[np.argwhere(max_stim==stim_idx).flatten()] for stim_idx in range(self.stim_n)]147 #func_relevant_neuron_single_time = [np.argwhere(self.func_relevant_neuron[stim_idx, time_point, :]).squeeze() for stim_idx in range(self.stim_n)]148 for stim_idx1 in range(self.stim_n):149 input_neurons = func_relevant_neuron_single_time[stim_idx1]150 #print(input_neurons)151 #print([x for x in input_neurons])152 local_peak_inputs = np.array([local_maximum_location(self.firing_rate_binder[stim_idx1, :, x], time_point) for x in input_neurons]) # peak location when c = 0.01153 for stim_idx2 in range(stim_idx1, self.stim_n):154 output_neurons = func_relevant_neuron_single_time[stim_idx2]155 local_peak_outputs = np.array([local_maximum_location(self.firing_rate_binder[stim_idx2, :, x], time_point) for x in output_neurons]) # peak location when c = 0.01156 self.weight_connection(input_neurons, output_neurons, local_peak_inputs, local_peak_outputs, stim_idx1, stim_idx2)157 def return_mean(self):158 delete_num = 1159 p_mean = [x.return_average()[:-delete_num] for x in self.p_result_list]160 n_mean = [x.return_average()[delete_num:] for x in self.n_result_list]161 return p_mean, n_mean162 def return_sem(self):163 delete_num = 1164 p_sem = [x.return_sem()[:-delete_num] for x in self.p_result_list]165 n_sem = [x.return_sem()[delete_num:] for x in self.n_result_list]166 return p_sem, n_sem167def weight_connection_with_time(serial_idxes, epoch='interval', gamma_bar=np.array([1]), c=np.array([0.01, -0.01]), time_points=np.array([600]), func_relevance_threshold=2, noise_on=False):168 weight_connection_obj = WeightConnection(len(c))169 time_points = (time_points/20).astype(np.int)170 dly_interval = 1600171 prod_intervals = np.array([1200])172 prod_intervals, c = np.meshgrid(prod_intervals, c)173 prod_intervals = prod_intervals.flatten()174 c = c.flatten()175 batch_size = len(prod_intervals)176 gamma_bar = np.array([gamma_bar] * batch_size).flatten()177 dly_intervals = np.array([dly_interval] * batch_size)178 for serial_idx in serial_idxes:179 model_dir = './core/model/' + 'timed_decision_making/' + str(serial_idx)180 if not os.path.exists(model_dir):181 continue182 runnerObj = run.Runner(model_dir=model_dir, rule_name='timed_decision_making', is_cuda=False, noise_on=noise_on)183 trial_input, run_result = runnerObj.run(batch_size=batch_size, prod_interval=prod_intervals, dly_interval=dly_intervals,184 gamma_bar=gamma_bar, c=c)185 stim1_off, stim2_on = trial_input.epochs[epoch]186 firing_rate_binder = run_result.firing_rate_binder.detach().cpu().numpy()187 firing_rate_binder = np.concatenate(list(firing_rate_binder[stim1_off[i]:stim2_on[i], i, :][np.newaxis, :, :] for i in range(0, batch_size)), axis=0)188 weight_connection_obj.reset_parameter(firing_rate_binder, runnerObj.model.weight_hh.detach().cpu().numpy(), time_points)189 weight_connection_obj.do()190 p_mean, n_mean = weight_connection_obj.return_mean()191 p_std, n_std = weight_connection_obj.return_sem()192 fig = plt.figure(figsize=(2.5, 2.1))193 ax = fig.add_axes([0.3, 0.2, 0.7*0.9, 0.6])194 ax.spines['top'].set_visible(False)195 ax.spines['right'].set_visible(False)196 mean_same = np.concatenate([n_mean[0], p_mean[0]])197 std_same = np.concatenate([n_std[0], p_std[0]])198 x_coord_same = np.concatenate([-np.flip(np.arange(len(n_mean[0])), axis=0)-1, np.arange(len(p_mean[0]))])199 plt.plot(x_coord_same, mean_same, label='Same choice pref.')200 plt.fill_between(x_coord_same, mean_same-std_same, mean_same+std_same, alpha=0.5)201 mean_diff = np.concatenate([n_mean[1], p_mean[1]])202 std_diff = np.concatenate([n_std[1], p_std[1]])203 x_coord_diff = np.concatenate([-np.flip(np.arange(len(n_mean[1])), axis=0)-1, np.arange(len(p_mean[1]))])204 plt.plot(x_coord_diff, mean_diff, label='Diff. choice pref.')205 plt.fill_between(x_coord_diff, mean_diff-std_diff, mean_diff+std_diff, alpha=0.5)206 plt.gca().set_xlabel('Peak order difference', fontsize=fs)207 plt.gca().set_ylabel('Recurrent weight', fontsize=fs)208 #plt.plot([-13, 11], [0, 0], '--', color='black')209 min_x = np.min([x_coord_same[0], x_coord_diff[0]])210 max_x = np.max([x_coord_same[-1], x_coord_diff[-1]])211 plt.plot([min_x, max_x], [0, 0], '--', color='black')212 plt.xlim([min_x, max_x])213 if min_x<=-10 and max_x>=10:214 plt.xticks([-10,0,9], [-10, 1, 10], fontsize=fs)215 else:216 plt.xticks([-10+5,0,9-5], [-10+5, 1, 10-5], fontsize=fs)217 fig.legend(loc='best', fontsize=fs, frameon=False)218 plt.show()...
main.py
Source:main.py
1import jieba2import OpenHowNet3# OpenHowNet.download()4hownet_dict = OpenHowNet.HowNetDict()5hownet_dict_advanced = OpenHowNet.HowNetDict(init_sim=True)6file = open("D:\\1353776970\\æ件æ¥æ¶ï¼\\å¤åè¯è®º.csv", "r", encoding="utf-8")7line = file.readline()8positive_list = ["ç¾å³", "è¿
é", "æ¯æ", "å¤", "å¼å¿"]9negative_list = ["æ¶å¿", "ç¨å°", "è«å", "slow", "æè´µ"] # "太æ
¢", "太å°"10p_result_list = dict()11n_result_list = dict()12def deal_with_str(str_list):13 while 'ï¼' in str_list:14 str_list.remove('ï¼')15 while '\n' in str_list:16 str_list.remove('\n')17 while 'ã' in str_list:18 str_list.remove('ã')19 while 'ï¼' in str_list:20 str_list.remove('ï¼')21def p_oneword(oneword, list_p, list_n):22 if oneword not in p_result_list:23 Polarity = 024 Polarity1 = 025 Polarity2 = 026 for test_word in list_p:27 Polarity1 += hownet_dict_advanced.calculate_word_similarity(oneword, test_word)28 Polarity1 = Polarity1 / len(list_p)29 for test_word in list_n:30 Polarity2 += hownet_dict_advanced.calculate_word_similarity(oneword, test_word)31 Polarity2 = Polarity2 / len(list_n)32 Polarity = Polarity1 - Polarity233 p_result_list[oneword] = Polarity34 else:35 pass36def p_word_deal(str_list):37 while str_list:38 p_oneword(str_list.pop(0), positive_list, negative_list)39 return40def n_oneword(oneword, list_p, list_n):41 if oneword not in n_result_list:42 Polarity = 043 Polarity1 = 044 Polarity2 = 045 for test_word in list_p:46 Polarity1 += hownet_dict_advanced.calculate_word_similarity(oneword, test_word)47 Polarity1 = Polarity1 / len(list_p)48 for test_word in list_n:49 Polarity2 += hownet_dict_advanced.calculate_word_similarity(oneword, test_word)50 Polarity2 = Polarity2 / len(list_n)51 Polarity = Polarity1 - Polarity252 n_result_list[oneword] = Polarity53 else:54 pass55def n_word_deal(str_list):56 while str_list:57 n_oneword(str_list.pop(0), positive_list, negative_list)58 return59def dealwithdict(list, dict):60 for i in list:61 if i in dict:62 del dict[i]63while True:64 line = file.readline()65 if line:66 case = int(line[0])67 # seg_list = jieba.cut(line[2:], cut_all=True)68 seg_list = jieba.cut_for_search(line[2:])69 seglist = list(seg_list)70 deal_with_str(seglist)71 if case == 1:72 p_word_deal(seglist)73 else:74 n_word_deal(seglist)75 else:76 break77p_result_list_ordered = sorted(p_result_list.items(), key=lambda x: x[1], reverse=True)78n_result_list_ordered = sorted(n_result_list.items(), key=lambda x: x[1], reverse=False)79positive_file = open("positive_word.txt", "w")80negative_file = open("negative_word.txt", "w")81rp_dict = dict(p_result_list_ordered[0:60])82np_dict = dict(n_result_list_ordered[0:60])83dealwithdict(positive_list, rp_dict)84dealwithdict(negative_list, np_dict)85i = 186for key, value in rp_dict.items():87 if i > 50:88 break89 positive_file.write(str(i)+":" +key + "\n")90 i += 191i = 192for key, value in np_dict.items():93 if i > 50:94 break95 negative_file.write(str(i)+":" +key + "\n")96 i += 197file.close()98positive_file.close()...
quene_recent_requests.py
Source:quene_recent_requests.py
1'''2Calculate how many events occurred in the past 10,000 milliseconds, including the current event;3that is, for each element k in the list, calculate how many elements in the entire list are between k-10000 and k (Both ends are included).4Input format:5A sorted list mylist, all elements are non-negative integers, record the occurrence time of each request, the unit is milliseconds.6Output format:7A list of the same length as mylist.8Input sample:9[0,10,100,1000,10000,20000,100000]10Sample output:11[1,2,3,4,5,2,1]12'''13class Queue:14 def __init__(self):15 self.items = []16 def isEmpty(self):17 return self.items == []18 def enqueue(self, item):19 self.items.insert(0,item)20 def dequeue(self):21 return self.items.pop()22 def size(self):23 return len(self.items)24def func(S):25 q=Queue()26 result_list=[]27 count_previous_repeat=028 #check every element in the input list29 for s in S:30 #check if previous n items are the same, such as [0,1,1,1], mark with a counter31 if not q.isEmpty() and q.items[0]==s:32 count_previous_repeat+=133 elif not q.isEmpty() and q.items[0]!=s:34 count_previous_repeat=035 # add the testing element into the quene36 q.enqueue(s)37 # keep removing the last element in quene until the last one less than s-1000038 while s-10000> q.items[-1]:39 q.dequeue()40 # if the current element is the same sa the previous ones, then need to update the quantity of previous element in the output list41 n_result_list=len(result_list)42 ## remove previous repeated items43 while result_list!=[] and len(result_list) > n_result_list - count_previous_repeat:44 result_list.pop()45 ## update with new items46 while len(result_list) < n_result_list + 1:47 # the size of the quene is the result, which is appended at the end of the list48 result_list.append(q.size())49 return result_list50if __name__ == "__main__":51 #S = [0,0,0,1000,1000,10000,20000,100000] #test list52 S = eval(input())...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!