blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
133
path
stringlengths
2
333
src_encoding
stringclasses
30 values
length_bytes
int64
18
5.47M
score
float64
2.52
5.81
int_score
int64
3
5
detected_licenses
listlengths
0
67
license_type
stringclasses
2 values
text
stringlengths
12
5.47M
download_success
bool
1 class
26a403a5d8d07e2554c907bce0414c31419b7cf5
Python
Guruprasadsd/PythonSem6
/DAY-2/d2prg18.py
UTF-8
217
3.78125
4
[]
no_license
import math d=int(input("Enter a degree")) x=math.radians(d) sum=x t=0 n=25 for i in range(3,n,2): t+=x**i/math.factorial(i) print("sin(",x,")=",sum-t) print("Using math function Sin(",x,")=",math.sin(x))
true
023a48f0bd779816cced4103087d175e1489745e
Python
morristech/Python-Coding-for-Kids-EduBlocks
/14.Trigonometry.py
UTF-8
160
3.34375
3
[]
no_license
import math print("Sin 90 Value is") x = math.sin(90) print(x) x = math.sin(90) print("Cos 90 Value is") print(x) print("math.sin(90)") print("math.sin(90)")
true
cbd619e3b5abcebd66ba2f4d28338aad472ae8f2
Python
guilhermejcmarinho/Praticas_Python_Elson
/02-Estrutura_de_Decisao/06-Maior_de_tres.py
UTF-8
438
3.90625
4
[]
no_license
numero01 = int(input('Informe o primeiro numero:')) numero02 = int(input('Informe o segundo numero:')) numero03 = int(input('Informe o terceiro numero:')) if numero01>numero02 and numero01>numero03: print('Primeiro numero: {} é o maior.'.format(numero01)) elif numero01<numero02 and numero02>numero03: print('Primeiro numero: {} é o maior.'.format(numero02)) else: print('Primeiro numero: {} é o maior.'.format(numero03))
true
83aa82a18540d6d4b7e1e9025730c1f6ede249bc
Python
Lguerrer31/python
/tournament/tournament.py
UTF-8
1,882
3.3125
3
[]
no_license
def tally(rows): results = [row.split(';') for row in rows] teams = {} for result in results: if result[0] not in teams: teams[result[0]] = Team(result[0]) if result[1] not in teams: teams[result[1]] = Team(result[1]) if result[2] == 'win': teams[result[0]].setResult(1) teams[result[1]].setResult(-1) elif result[2] == 'loss': teams[result[0]].setResult(-1) teams[result[1]].setResult(1) else: teams[result[0]].setResult(0) teams[result[1]].setResult(0) table = ['Team | MP | W | D | L | P'] for team in teams: teams[team].calcPoints() teams = sorted([teams[team] for team in teams], reverse=True) for team in teams: print(team.display()) return table + [team.display() for team in teams] class Team(object): def __init__(self, name): self.name = name self.matches = 0 self.wins = 0 self.draws = 0 self.losses = 0 self.points = 0 def __gt__(self, other): if self.points > other.points: return True elif self.points < other.points: return False else: if self.name > other.name: return False else: return True def display(self): line = '{}| {} | {} | {} | {} | {}' return line.format(self.name.ljust(31), self.matches, self.wins, self.draws, self. losses, self.points) def setResult(self, result): self.matches += 1 if result == 1: self.wins += 1 elif result == -1: self.losses += 1 else: self.draws += 1 def calcPoints(self): self.points = self.wins * 3 + self.draws
true
57ae6b5e2048299943d8b7698039befd96f8f19c
Python
zurowski/k-means
/src/k_means/gen_data.py
UTF-8
1,670
3.3125
3
[ "MIT" ]
permissive
import os import random MAX_VALUE = 1000 def generate_file(number_of_records, dimension, file_name): """ Generate random set of data, save it to file in data directory :param int number_of_records: number of records in the dataset :param int dimension: dimension of a record (point) in dataset :param str file_name: name of the file in which dataset will be saved """ data_dir = '' try: file_dir = os.path.dirname(os.path.realpath('__file__')) data_dir = os.path.join(file_dir, 'data') os.makedirs(data_dir) except OSError as e: print('directory already exists') file_path = os.path.join(data_dir, file_name) with open(file_path, 'w') as file: for i in range(number_of_records): res = '' for j in range(dimension): res += str(random.randrange(MAX_VALUE)) + ',' res = res[:-1] res += '\n' file.write(res) def save_to_file(data, file_name): """ Save passed data to a file in data directory :param iterable data: data to be saved in a file :param str file_name: name of a file """ data_dir = '' try: file_dir = os.path.dirname(os.path.realpath('__file__')) data_dir = os.path.join(file_dir, 'data') os.makedirs(data_dir) except OSError as e: print('directory already exists') file_path = os.path.join(data_dir, file_name) with open(file_path, 'w') as file: for el in data: (r_val, g_val, b_val, alpha) = el res = str(r_val) + ',' + str(g_val) + ',' + str(b_val) + '\n' file.write(res)
true
a7393ac355ac0ea3d5c53b9fa7130e5fa4bf75e6
Python
zhuligs/physics
/old_compressibility.py
UTF-8
979
2.859375
3
[]
no_license
#!/usr/bin/env python """ calculate the compressibility from PV data """ import os, sys, commands, glob import numpy from scipy import integrate def main(): # Retrieve user input try: f = open(sys.argv[1],'r') lines = f.readlines() if '#' in lines[0]: lines.pop(0) f.close() except: print '\n usage: '+sys.argv[0]+' file_with_rs_and_P_as_first_two_colums.dat.\n' sys.exit(0) # Read in data and calculate the volumes rs, P = [], [] for line in lines: row = line.split() rs.append(float(row[0])) P.append(float(row[1])) V = (numpy.pi*4.0/3.0)*numpy.array(rs)**3 # Use forward difference method out = open('compressibility.dat','w') for i in range(len(P)-1): dP = P[i+1] - P[i] dV = V[i+1] - V[i] kT = -1.0/V[i] * dV/dP out.write(str(rs[i])+' '+str(kT)+' '+str(P[i])+'\n') out.close() if __name__ == '__main__': main()
true
65c1fc0fa001893d6ae3205663d005cdfb5c9408
Python
SGrosse-Holz/polychromosims
/polychromosims/save_module_to_script.py
UTF-8
2,835
3.34375
3
[ "MIT" ]
permissive
import numpy as np def str_extended(value): """ A small helper function to convert a python object into executable code reproducing that object. Supported types --------------- None, bool, int, float, complex, str, list, dict, tuple, numpy.ndarray """ np.set_printoptions(threshold=np.inf) def str_str(val): return "'"+val+"'" def str_list(val): if len(val) == 0: return "[]" ret = "[" for v in val: ret += str_extended(v)+", " # Remove the last ", " return ret[:-2]+"]" def str_dict(val): if len(val) == 0: return "{}" ret = "{" for key in val.keys(): ret += str_extended(key)+" : "+str_extended(val[key])+", " return ret[:-2]+"}" def str_tuple(val): if len(val) == 0: return "()" ret = "(" for v in val: ret += str_extended(v)+", " # Remove the last ", " return ret[:-2]+")" def str_nparray(val): return "np."+repr(val) case_dict = { type(None) : str, bool : str, int : str, float : str, complex : str, str : str_str, list : str_list, dict : str_dict, tuple : str_tuple, np.ndarray : str_nparray } try: return case_dict[type(value)](value) except KeyError as key: try: # Maybe it's some numpy type? return case_dict[type(value.item())](value) except: raise ValueError("Unsupported type: "+str(key)+" for attribute "+str(value)) def mod2py(mod, path, ignoreModules=True): """ This function generates a python script containing all the values in the module. This is designed to print configuration modules in an easy-to-reload-and-inspect manner. Parameters ---------- mod : a python module the module to save path : str the file to save to ignoreModules : bool skip anything that's itself a module. True by default. """ to_write = [attr for attr in dir(mod) if not attr[:2] == "__"] with open(path, 'xt') as myfile: print("import numpy as np", file=myfile) print("", file=myfile) for attr in to_write: try: print(attr+" = "+str_extended(getattr(mod, attr)), file=myfile) except ValueError as VE: cur_type = type(getattr(mod, attr)) if not ( (cur_type == type(np) and ignoreModules) or (cur_type == type(mod2py) and getattr(mod, attr).__name__ == "gen_start_conf") ): raise VE
true
a8d27e83a3a9071b2918df0560ddee1ca21dff39
Python
QmF0c3UK/ARL
/app/services/crtshClient.py
UTF-8
1,090
2.640625
3
[]
no_license
from app import utils logger = utils.get_logger() class CrtshClient: def __init__(self): self.url = "https://crt.sh/" def search(self, domain): param = { "output": "json", "q": domain } data = utils.http_req(self.url, 'get', params=param, timeout=(30.1, 50.1)).json() return data def crtsh_search(domain): name_list = [] try: c = CrtshClient() items = c.search(domain) for item in items: for name in item["name_value"].split(): name = name.strip() name = name.strip("*.") name = name.lower() if "@" in name: continue if not utils.domain_parsed(domain): continue if name.endswith("."+domain): name_list.append(name) name_list = list(set(name_list)) logger.info("search crtsh {} {}".format(domain, len(name_list))) except Exception as e: logger.exception(e) return name_list
true
3af243a79233104f0775ac3c34c59b7fae43be3d
Python
wsrf16/tedt
/grammar/numpy_operation.py
UTF-8
418
2.96875
3
[]
no_license
import numpy as np import os class Operation(object): def do(self): x = np.array([[1, 2], [3, 4]]) n = 2 y1 = x + n y2 = x * n n = np.array([[5, 7]]) y1 = x + n y2 = x * n n = np.array([[5], [7]]) y1 = x + n y2 = x * n n = np.array([[5, 7], [11, 13]]) y1 = x + n y2 = x * n os.system("pause");
true
9e413237bdc8757c3ba060803bdb8e828f40a2d5
Python
mwbaert/Integratieproject_github
/matching_with_searchwindow.py
UTF-8
4,394
2.609375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Feb 24 09:56:00 2017 @author: Mattijs """ import numpy as np import cv2 def EvaluateMatch(img1,img2): MIN_MATCH_COUNT = 5; # Initiate ORB detector orb = cv2.ORB_create(nfeatures=100000) # find the keypoints and descriptors with ORB kp1, des1 = orb.detectAndCompute(img1,None) kp2, des2 = orb.detectAndCompute(img2,None) ######################BRUTEFORCE############################ # create BFMatcher object bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) # Match descriptors. matches = bf.match(des1,des2) # Sort them in the order of their distance. matches = sorted(matches, key = lambda x:x.distance) ############################################################ #Convert the array of best matches to an two dimensional array #So that the best matches can be determined w, h = 2, len(matches)/2; Matrix = [[0 for x in range(w)] for y in range(h)] for i in range (0, len(matches)/2): for j in range (0, 2): Matrix[i][j] = matches[i+j] #tresholding the matches good = [] for m,n in Matrix: if m.distance < 0.97*n.distance: good.append(m) #taking the i.e. the 10 matches with the shortest distance #better results if it's certain the larger image contains the pattern #for i in range (1, 25): # good.append(matches[i-1]) if len(good)>MIN_MATCH_COUNT: # x, y coordinates of the jeypoints in the source file src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2) # x, y coordinates of the jeypoints in the destination file dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2) #seeking the min and max y-coordinate in the destination file #so that the founded pattern/object can be deleted #saves the index!! max = 0; min = img2.shape[0] #height of searching object for i in range (0,len(dst_pts)-1): print dst_pts[i][0][1] if dst_pts[i][0][1] < min: min = i if dst_pts[i][0][1] > max: max = i print "min :", max M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC,5.0) matchesMask = mask.ravel().tolist() pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2) #print pts dst = cv2.perspectiveTransform(pts,M) img2 = cv2.polylines(img2,[np.int32(dst)],True,255,3, cv2.LINE_AA) print "Match found!" else: print "Not enough matches are found - %d/%d" % (len(good),MIN_MATCH_COUNT) matchesMask = None draw_params = dict(matchColor = (0,255,0), singlePointColor = (255,0,0), flags = 2) img3 = cv2.drawMatches(img1,kp1,img2,kp2,good,None,**draw_params) cv2.imshow('image',img3) cv2.waitKey(0) cv2.destroyAllWindows() ####################################################################################################### #MIN_WIDTH_SW = 10; #minimum width of search window #MIN_HEIGHT_SW = 5; #minimum height of search window STEP_SIZE_PARAM = 5 #rate that search window increases print cv2.__version__ singleCarpet = cv2.imread('carpet_1_orig.jpg') # SingleCarpet frame = cv2.imread('repeat.jpg') # ComposedCarpet full_width = frame.shape[1] #comparing with MIN_WIDTH_SW this is the maximum full_height = frame.shape[0] #idem #concreate increment of searchwindow step_size_width = full_width/STEP_SIZE_PARAM #step_size_height = full_height/STEP_SIZE_PARAM current_width = step_size_width #current_height = step_size_height #full image loaded full_flag = 0; teller = 0; while(full_flag == 0): teller = teller + 1 #searchwindow = frame[0:current_height, 0:current_width] searchwindow = frame[0:full_height, 0:current_width] #current_height = current_height + step_size_height current_width = current_width + step_size_width EvaluateMatch(singleCarpet,searchwindow) # cv2.imshow('image',searchwindow) # cv2.waitKey(0) # cv2.destroyAllWindows() if teller == STEP_SIZE_PARAM: full_flag = 1
true
47d31d6c245e8cc51a5140499cad55c5cdb20719
Python
AliveSnaker/L5
/L5/2.py
UTF-8
143
3.609375
4
[]
no_license
note = [7, 6, 8, 10, 5] note[0], note[4] = note[4], note[0] note[1], note[3] = note[3], note[1] print(note) note.reverse() print("Lista", note)
true
871c2faab7880ec14c2fc08f8f17254addb054b6
Python
jek343/StanfordMedical
/ml/model/regression/gradient_boosting/square_error_decision_tree_boosted_regressor.py
UTF-8
1,623
2.65625
3
[]
no_license
from ml.model.regression.gradient_boosting.decision_tree_boosted_regressor import DecisionTreeBoostedRegressor from ml.model.regression.loss.pointwise_square_error_loss import PointwiseSquareErrorLoss import numpy as np class SquareErrorDecisionTreeBoostedRegressor(DecisionTreeBoostedRegressor): def __init__(self, depth_range, num_learners, learner_regularizer, num_features_range, weak_learner_point_percent_range): DecisionTreeBoostedRegressor.__init__(self, PointwiseSquareErrorLoss(), num_learners, learner_regularizer, depth_range, num_features_range, weak_learner_point_percent_range) def set_params(self, num_learners, learner_regularizer, depth_range, num_features_range, weak_learner_point_percent_range): DecisionTreeBoostedRegressor.set_params(self, PointwiseSquareErrorLoss(), num_learners, learner_regularizer, depth_range, num_features_range, weak_learner_point_percent_range) ''' gamma_m has a closed-form solution for square pointwise error, and it is significantly faster to use over some optimization method ''' def _solve_for_gamma_m(self, X, y, current_model_preds, h_m): #each gamma is 1 because in the pointwise square error, the pseudo-residuals #are just y[i] - pred(y)[i]. This can be found logistically, or by closed-form #based solution by setting partial derivative to zero. return 1 ''' h_m_preds = h_m(X) gamma_numerator = np.sum(h_m_preds * (y - current_model_preds)) gamma_denominator = np.sum(np.square(h_m_preds)) return gamma_numerator/gamma_denominator '''
true
e303d2bf23023bf7e38af10fac045c08d029fe77
Python
Namenaro/networks_zoo
/utils.py
UTF-8
6,041
2.515625
3
[]
no_license
# -*- coding: utf-8 -* import matplotlib.pyplot as plt import numpy as np import easygui import pickle as pkl from keras.models import load_model import os import wfdb from sklearn.preprocessing import normalize # plt.xkcd() def draw_reconstruction_to_png(ecg_true, ecg_predicted, png_filename): """ :param ecg_true: истинная экг :param ecg_predicted: предсказанное :param png_filename: имя для файла с картинкой :return: """ ecg_true = reshape_ecg_tensor(ecg_true) ecg_predicted = reshape_ecg_tensor(ecg_predicted) assert ecg_true.shape == ecg_predicted.shape len_of_time = len(ecg_true[0]) t = [i for i in range(len_of_time)] rows = len(ecg_true) # кол-во каналов cols = 2 # true и predicted - 2 столбика f, axarr = plt.subplots(nrows=rows, ncols=cols, sharex=True, sharey=True) for i in range(rows): true_i_chanel = ecg_true[i] predicted_i_chanel = ecg_predicted[i] axarr[i, 0].plot(t, true_i_chanel) axarr[i, 1].plot(t, predicted_i_chanel) plt.savefig(png_filename+".png") def reshape_ecg_tensor(ecg): # превратим (252, 1, 12) в (12, 252) print("форма тезора с экг = " + str(ecg.shape)) ecg = ecg[:, 0, :] ecg = np.transpose(ecg) print("форма тезора с экг (после напильника) =" + str(ecg)) return ecg def save_history(history, canterpillar_name): plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.savefig(canterpillar_name+"_loss.png") if 'acc' in history.history.keys(): plt.plot(history.history['acc']) plt.plot(history.history['val_acc']) plt.title('model loss') plt.ylabel('acc') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left') plt.savefig(canterpillar_name + "_acc.png") def show_reconstruction_by_ae(ecg_sample, name): filepath = easygui.fileopenbox("выберите файл с обученной моделью .h5") trained_model = load_model(filepath) trained_model.summary() ecg_sample = np.array([ecg_sample]) prediction = trained_model.predict(ecg_sample) draw_reconstruction_to_png(ecg_sample[0], prediction[0], name) def get_addon_mask(annotations_in): addon = np.zeros((1, annotations_in.shape[1], 1)) for i in range(0, annotations_in.shape[1]): sum = annotations_in[:, i, 0] + annotations_in[:, i, 1] + annotations_in[:, i, 2] if (sum == 0): addon[0:1, i, 0:1] = 1 else: continue return addon def open_pickle(path): infile = open(path, 'rb') load_pkl = pkl.load(infile) infile.close() return load_pkl def get_ecg_data(record_path): annotator = 'q1c' annotation = wfdb.rdann(record_path, extension=annotator) Lstannot = list( zip(annotation.sample, annotation.symbol, annotation.aux_note)) FirstLstannot = min(i[0] for i in Lstannot) LastLstannot = max(i[0] for i in Lstannot)-1 record = wfdb.rdsamp(record_path, sampfrom=FirstLstannot, sampto=LastLstannot, channels=[0]) annotation = wfdb.rdann(record_path, annotator, sampfrom=FirstLstannot, sampto=LastLstannot) VctAnnotations = list(zip(annotation.sample, annotation.symbol)) mask_p = np.zeros(record[0].shape) mask_qrs = np.zeros(record[0].shape) mask_t = np.zeros(record[0].shape) for i in range(len(VctAnnotations)): try: if VctAnnotations[i][1] == "p": if VctAnnotations[i-1][1] == "(": pstart = VctAnnotations[i-1][0] if VctAnnotations[i+1][1] == ")": pend = VctAnnotations[i+1][0] if VctAnnotations[i+3][1] == "N": rpos = VctAnnotations[i+3][0] if VctAnnotations[i+2][1] == "(": qpos = VctAnnotations[i+2][0] if VctAnnotations[i+4][1] == ")": spos = VctAnnotations[i+4][0] # search for t (sometimes the "(" for the t is missing ) for ii in range(0, 8): if VctAnnotations[i+ii][1] == "t": tpos = VctAnnotations[i+ii][0] if VctAnnotations[i+ii+1][1] == ")": tendpos = VctAnnotations[i+ii+1][0] mask_p[pstart-FirstLstannot:pend-FirstLstannot] = 1 mask_qrs[qpos-FirstLstannot:spos-FirstLstannot] = 1 mask_t[tpos-FirstLstannot:tendpos-FirstLstannot] = 1 except IndexError: pass sum_p = np.sum(mask_p) sum_qrs = np.sum(mask_qrs) sum_t = np.sum(mask_t) print(sum_p) print(sum_qrs) print(sum_t) lst = list(record) lst[0] = normalize(record[0], axis=0, norm='max') record = tuple(lst) if (sum_p == 0): print("P FAIL") return -1 if (sum_qrs == 0): print("QRS FAIL") return -1 if (sum_t == 0): print("T FAIL") return -1 print(record[0]) record_tens = np.reshape(record[0], (1, np.size(record[0]), 1)) mask_p = np.reshape(mask_p, (1, np.size(mask_p), 1)) mask_qrs = np.reshape(mask_qrs, (1, np.size(mask_qrs), 1)) mask_t = np.reshape(mask_t, (1, np.size(mask_t), 1)) mask_tens = np.empty((1, np.size(mask_p), 0)) mask_tens = np.concatenate((mask_tens, mask_p), axis=2) mask_tens = np.concatenate((mask_tens, mask_qrs), axis=2) mask_tens = np.concatenate((mask_tens, mask_t), axis=2) #print("Parser output: ") #print(record_tens.shape) #print(mask_tens.shape) return record_tens, mask_tens
true
f21a1baaeb147365e91ed16fecd7a322dc85d34b
Python
hagne/atm-py
/atmPy/aerosols/physics/hygroscopicity.py
UTF-8
49,470
2.8125
3
[ "MIT" ]
permissive
import numpy as _np from scipy.optimize import fsolve as _fsolve from scipy.optimize import curve_fit as _curve_fit from scipy import signal as _signal import pandas as _pd import atmPy.general.timeseries as _timeseries import warnings as _warnings from atmPy.tools import math_functions as _math_functions from atmPy.tools import plt_tools as _plt_tools import matplotlib.pylab as _plt from atmPy.aerosols.size_distribution import sizedistribution as _sizedistribution def kappa_simple(k, RH, refractive_index = None, inverse = False): """Returns the growth factor as a function of kappa and RH. This function is based on a simplified version of a model originally introduced by Rissler et al. (2005). It ignores the curvature effect and is therefore independend of the exact particle diameter. Due to this simplification this function is valid only for particles larger than 100 nm Patters and Kreidenweis (2007). Petters, M. D., & Kreidenweis, S. M. (2007). A single parameter representation of hygroscopic growth and cloud condensation nucleus activity, 1961-1971. doi:10.5194/acp-7-1961-2007 Rissler, J., Vestin, A., Swietlicki, E., Fisch, G., Zhou, J., Artaxo, P., & Andreae, M. O. (2005). Size distribution and hygroscopic properties of aerosol particles from dry-season biomass burning in Amazonia. Atmospheric Chemistry and Physics Discussions, 5(5), 8149-8207. doi:10.5194/acpd-5-8149-2005 latex expression: gf = \left(1 + \kappa \cdot \frac{RH}{100 - RH}\right)^{\frac{1}{3}} gf = \sqrt[3]{1 + \kappa \cdot \frac{RH}{100 - RH}} Arguments --------- k: float kappa value between 0 (no hygroscopicity) and 1.4 (NaCl; most hygroscopic material found in atmospheric aerosols) If inverse is True than this is the growth factor. RH: float Relative humidity -> between 0 and 100 (i don't think this simplified version will be correct at higher RH?!?) inverse: bool. if function is inversed, which means instead of the growth factor is calculated as a function of the kappa value, it is the other way around. Returns ------- float: The growth factor of the particle. if refractive_index is given a further float is returned which gives the new refractiv index of the grown particle """ if not inverse: if _np.any(k > 1.4) or _np.any(k < 0): # txt = '''The kappa value has to be between 0 and 1.4.''' # txt = txt + '\nk[k>1.4]:\n%s'%(k[k>1.4]) +'\nk[k<0]:\n%s'%(k[k<0]) # print(txt) # raise ValueError(txt) if _np.any(k > 1.4): _warnings.warn('There are kappa values lareger than 1.4 in this dataset!') if _np.any(k < 0): _warnings.warn('There are kappa values smaller than 0 in this dataset!') if _np.any(RH > 100) or _np.any(RH < 0): txt = """RH has to be between 0 and 100""" raise ValueError(txt) if inverse: kappa = lambda gf,RH: (gf**3 - 1) / (RH / (100 - RH)) out = kappa(k,RH) else: growths_factor = lambda k,RH: (1 + (k * (RH/(100 - RH))))**(1/3.) out = growths_factor(k,RH) # adjust index of refraction if not inverse: if _np.any(refractive_index): nw = 1.33 # n_mix = lambda n,gf: (n + ((gf-1)*nw))/gf n_mix = lambda n, gf: (n + (nw * (gf ** 3 - 1))) / gf ** 3 # This is the correct function for volume mixing ratio if type(refractive_index).__name__ == 'DataFrame': refractive_index = refractive_index.iloc[:,0] return out, n_mix(refractive_index, out) return out def kappa_from_fofrh_and_sizedist(f_of_RH, dist, wavelength, RH, verbose = False, f_of_RH_collumn = None): """ Calculates kappa from f of RH and a size distribution. Parameters ---------- f_of_RH: TimeSeries dist: SizeDist wavelength: float RH: float Relative humidity at which the f_of_RH is taken. column: string when f_of_RH has more than one collumn name the one to be used verbose: bool Returns ------- TimeSeries """ def minimize_this(gf, sr, f_rh_soll, ext, wavelength, verbose = False): gf = float(gf) sr_g = sr.apply_growth(gf, how='shift_bins') sr_g_opt = sr_g.calculate_optical_properties(wavelength) ext_g = sr_g_opt.extinction_coeff_sum_along_d.data.values[0][0] f_RH = ext_g / ext out = f_RH - f_rh_soll if verbose: print('test growhtfactor: %s'%gf) print('f of RH soll/is: %s/%s'%(f_rh_soll,f_RH)) print('diviation from soll: %s'%out) print('---------') return out # make sure f_of_RH has only one collumn if f_of_RH.data.shape[1] > 1: if not f_of_RH_collumn: txt = 'f_of_RH has multiple collumns (%s). Please name the one you want to use by setting the f_of_RH_collumn argument.'%(f_of_RH.data.columns) raise ValueError(txt) else: f_of_RH = f_of_RH._del_all_columns_but(f_of_RH_collumn) n_values = dist.data.shape[0] gf_calc = _np.zeros(n_values) kappa_calc = _np.zeros(n_values) f_of_RH_aligned = f_of_RH.align_to(dist) for e in range(n_values): frhsoll = f_of_RH_aligned.data.values[e][0] if _np.isnan(frhsoll): kappa_calc[e] = _np.nan gf_calc[e] = _np.nan continue if type(dist.index_of_refraction).__name__ == 'float': ior = dist.index_of_refraction else: ior = dist.index_of_refraction.iloc[e][0] if _np.isnan(ior): kappa_calc[e] = _np.nan gf_calc[e] = _np.nan continue sr = dist.copy() sr.data = sr.data.iloc[[e],:] sr.index_of_refraction = ior sr_opt = sr.calculate_optical_properties(wavelength) ext = sr_opt.extinction_coeff_sum_along_d.data.values[0][0] if ext == 0: kappa_calc[e] = _np.nan gf_calc[e] = _np.nan continue if verbose: print('goal for f_rh: %s'%frhsoll) print('=======') gf_out = _fsolve(minimize_this, 1, args = (sr, frhsoll, ext, wavelength, verbose), factor=0.5, xtol = 0.005) gf_calc[e] = gf_out if verbose: print('resulting gf: %s'%gf_out) print('=======\n') kappa_calc[e] = kappa_simple(gf_out, RH, inverse=True) ts_kappa = _timeseries.TimeSeries(_pd.DataFrame(kappa_calc, index = f_of_RH_aligned.data.index, columns= ['kappa'])) ts_kappa._data_period = f_of_RH_aligned._data_period ts_kappa._y_label = '$\kappa$' ts_gf = _timeseries.TimeSeries(_pd.DataFrame(gf_calc, index = f_of_RH_aligned.data.index, columns= ['growth factor'])) ts_kappa._data_period = f_of_RH_aligned._data_period ts_gf._y_label = 'growth factor$' return ts_kappa, ts_gf ######################### ##### f of RH def f_RH_kappa(RH, k, RH0 = 0): """ References: Petters, M.D., Kreidenweis, S.M., 2007. A single parameter representation of hygroscopic growth and cloud condensation nucleus activity. Atmos. Chem. Phys. 7, 1961–1971. doi:10.5194/acp-7-1961-2007 Latex: f_{RH,\kappa} = \frac{\sigma_{wet}}{\sigma_{dry}} = \frac{1 + k \frac{RH_{wet}}{100 - RH_{wet}}}{1 + k \frac{RH_{dry}}{100 - RH_{dry}}} Args: RH: k: RH0: Returns: """ f_RH = (1 + (k * (RH/(100 - RH)))) / (1 + (k * (RH0/(100 - RH0)))) return f_RH def f_RH_gamma(RH, g, RH0 = 0): """" Latex: f_{RH,\gamma} = \frac{\left( 1 - \frac{RH_{wet\phantom{j}}}{100}\right) ^{-\gamma}}{ \left( 1 - \frac{RH_{dry}}{100}\right) ^{-\gamma}} References: Kasten, F., 1969. Visibility forecast in the phase of pre-condensation. Tellus 21, 631–635. doi:10.3402/tellusa.v21i5.10112 """ # f_RH = ((1 - (RH / 100))**(-g)) / ((1 - (RH0 / 100))**(-g)) f_RH = ((100 - RH0) / (100 - RH))**(g) return f_RH def get_f_of_RH_from_dry_sizedistribution(size_dist, RH_low, RH_high): """Get the f of RH from a dry sizedistribution between the two RH values RH_low and RH_high Parameters ---------- size_dist: sizedistribution instance RH_low: float RH_high: float """ size_dist.parameters4reductions._check_opt_prop_param_exist() sdhigh = size_dist.copy() sdlow = size_dist.copy() sdhigh.hygroscopicity.parameters.RH = RH_high scattcoff_high = sdhigh.hygroscopicity.grown_size_distribution.optical_properties.scattering_coeff.copy() if RH_low == 0: scattcoff_low = sdlow.optical_properties.scattering_coeff.copy() else: sdlow.hygroscopicity.parameters.RH = RH_low scattcoff_low = sdlow.hygroscopicity.grown_size_distribution.optical_properties.scattering_coeff.copy() out = {} # out['f_rh'] = scattcoff_high/scattcoff_low out['scattcofflow'] = scattcoff_low out['scattcoffhigh'] = scattcoff_high out['sdhigh'] = sdhigh out['sdlow'] = sdlow out['f_RH'] = scattcoff_high/scattcoff_low return out['f_RH'] def fofRH_from_dry_wet_scattering(scatt_dry, scatt_wet,RH_dry, RH_wet, data_period = 60, return_fits = False, verbose = False): """ This function was originally written for ARM's AOS dry wet nephelometer proceedure. Programming will likely be needed to make it work for something else. Notes ----- For each RH scan in the wet nephelometer an experimental f_RH curve is created by deviding scatt_wet by scatt_dry. This curve is then fit by a gamma as well as a kappa parametrizaton. Here the dry nephelometer is NOT considered as RH = 0 but its actuall RH (averaged over the time of the scann) is considered. I was hoping that this will eliminated a correlation between "the ratio" and the dry nephelometer's RH ... it didn't :-( Parameters ---------- scatt_dry: TimeSeries scatt_wet: TimeSeries RH_dry: TimeSeries RH_wet: TimeSeries data_period: int,float measurement frequency. Might only be needed if return_fits = True ... double check return_fits: bool If the not just the fit results but also the corresponding curves are going to be returned Returns ------- pandas.DataFrame containing the fit results pandas.DataFrame containing the fit curves (only if retun_fits == True) """ # some modification to the kappa function so it can be used in the fit routine later f_RH_kappa_RH0 = lambda RH0: (lambda RH, k: f_RH_kappa(RH, k, RH0)) f_RH_gamma_RH0 = lambda RH0: (lambda RH, g: f_RH_gamma(RH, g, RH0)) # crate the f(RH)/f(RH0) # scatt_dry = _timeseries._timeseries(_pd.DataFrame(scatt_dry)) # scatt_dry._data_period = data_period # scatt_wet = _timeseries._timeseries(_pd.DataFrame(scatt_wet)) # scatt_wet._data_period = data_period f_RH = scatt_wet / scatt_dry f_RH.data.columns = ['f_RH'] # f_RH = _timeseries._timeseries(_pd.DataFrame(f_RH, columns=['f_RH'])) # f_RH._data_period = data_period # get start time for next RH-ramp (it always start a few minutes after the full hour) start, end = f_RH.get_timespan() start_first_section = _np.datetime64('{:d}-{:02d}-{:02d} {:02d}:00:00'.format(start.year, start.month, start.day, start.hour)) if (start.minute + start.second + start.microsecond) > 0: start_first_section += _np.timedelta64(1, 'h') # select one hour starting with time defined above. Also align/merge dry and wet RH to it i = -1 fit_res_list = [] results = _pd.DataFrame(columns=['kappa', 'kappa_std', 'f_RH_85_kappa', 'f_RH_85_kappa_std', # 'f_RH_85_kappa_errp', # 'f_RH_85_kappa_errm', 'gamma', 'gamma_std', 'f_RH_85_gamma', 'f_RH_85_gamma_std', 'wet_neph_max', 'dry_neph_mean', 'dry_neph_std', 'wet_neph_min'], dtype = _np.float64) while i < 30: i += 1 # stop if section end is later than end of file section_start = start_first_section + _np.timedelta64(i, 'h') section_end = start_first_section + _np.timedelta64(i, 'h') + _np.timedelta64(45, 'm') if (end - section_end) < _np.timedelta64(0, 's'): break if verbose: print('================') print('start of section: ', section_start) print('end of section: ', section_end) try: section = f_RH.zoom_time(section_start, section_end) except IndexError: if verbose: print('section has no data in it!') results.loc[section_start] = _np.nan continue df = section.data.copy().dropna() if df.shape[0] < 2: if verbose: print('no data in section.dropna()!') results.loc[section_start] = _np.nan continue # section = section.merge(out.RH_nephelometer._del_all_columns_but('RH_NephVol_Wet')) # section = section.merge(out.RH_nephelometer._del_all_columns_but('RH_NephVol_Dry')).data section = section.merge(RH_wet) section = section.merge(RH_dry).data # this is needed to get the best parameterization dry_neph_mean = section.RH_NephVol_Dry.mean() dry_neph_std = section.RH_NephVol_Dry.std() wet_neph_min = section.RH_NephVol_Wet.min() wet_neph_max = section.RH_NephVol_Wet.max() # clean up section.dropna(inplace=True) section = section[section.f_RH != _np.inf] section = section[section.f_RH != -_np.inf] timestamps = section.index.copy() section.index = section.RH_NephVol_Wet section.drop('RH_NephVol_Wet', axis=1, inplace=True) section.drop('RH_NephVol_Dry', axis=1, inplace=True) # fitting!! if dry_neph_mean > wet_neph_max: if verbose: print('dry_neph_mean > wet_neph_max!!! something wrong with dry neph!!') results.loc[section_start] = _np.nan continue kappa, [k_varience] = _curve_fit(f_RH_kappa_RH0(dry_neph_mean), section.index.values, section.f_RH.values) gamma, [varience] = _curve_fit(f_RH_gamma_RH0(dry_neph_mean), section.index.values, section.f_RH.values) frame_this = {'kappa': kappa[0], 'kappa_std': _np.sqrt(k_varience[0]), 'f_RH_85_kappa': f_RH_kappa(85, kappa[0]), 'f_RH_85_kappa_std': - f_RH_kappa(85, kappa[0]) + f_RH_kappa(85, kappa[0] + _np.sqrt(k_varience[0])), # 'f_RH_85_kappa_errp': f_RH_kappa(85, kappa[0] + _np.sqrt(k_varience[0])), # 'f_RH_85_kappa_errm': f_RH_kappa(85, kappa[0] - _np.sqrt(k_varience[0])), 'gamma': gamma[0], 'gamma_std': _np.sqrt(varience[0]), 'f_RH_85_gamma': f_RH_gamma(85, gamma[0]), 'f_RH_85_gamma_std': - f_RH_gamma(85, gamma[0]) + f_RH_gamma(85, gamma[0] + _np.sqrt(varience[0])), 'dry_neph_mean': dry_neph_mean, 'dry_neph_std': dry_neph_std, 'wet_neph_min': wet_neph_min, 'wet_neph_max': wet_neph_max} results.loc[section_start] = frame_this if return_fits: # plotting preparation RH = section.index.values # RH = _np.linspace(0,100,20) fit = f_RH_gamma_RH0(dry_neph_mean)(RH, gamma) fit_std_p = f_RH_gamma_RH0(dry_neph_mean)(RH, gamma + _np.sqrt(varience)) fit_std_m = f_RH_gamma_RH0(dry_neph_mean)(RH, gamma - _np.sqrt(varience)) fit_k = f_RH_kappa_RH0(dry_neph_mean)(RH, kappa) fit_k_std_p = f_RH_kappa_RH0(dry_neph_mean)(RH, kappa + _np.sqrt(k_varience)) fit_k_std_m = f_RH_kappa_RH0(dry_neph_mean)(RH, kappa - _np.sqrt(k_varience)) df['fit_gamma'] = _pd.Series(fit, index=df.index) df['fit_gamma_stdp'] = _pd.Series(fit_std_p, index=df.index) df['fit_gamma_stdm'] = _pd.Series(fit_std_m, index=df.index) df['fit_kappa'] = _pd.Series(fit_k, index=df.index) df['fit_kappa_stdp'] = _pd.Series(fit_k_std_p, index=df.index) df['fit_kappa_stdm'] = _pd.Series(fit_k_std_m, index=df.index) fit_res_list.append(df) if results.shape[0] == 0: results.loc[start] = _np.nan results = _timeseries.TimeSeries(results) results._data_period = 3600 if return_fits: fit_res = _pd.concat(fit_res_list).sort_index() ts = _timeseries.TimeSeries(fit_res) ts._data_period = data_period fit_res = ts.close_gaps() return results, fit_res else: return results ############## ### def _fit_normals(sd): """Fits a normal distribution to a """ log = True # was thinking about having the not log fit at some point ... maybe some day?!? def find_peak_arg(x, y, start_w=0.2, bounds=None): """ Parameters ---------- x: nd_array log10 of the diameters y: nd_array intensities (number, volume, surface ...) start_w: float some reasonalble width for a log normal distribution (in log normal) tol: float Tolerance ratio for start_w""" med = _np.median(x[1:] - x[:-1]) # print(med) low = _np.floor((bounds[0]) / med) cent = int(start_w / med) top = _np.ceil((bounds[1]) / med) widths = _np.arange(low, top) # print(widths) peakind = _signal.find_peaks_cwt(y, widths) return peakind def multi_gauss(x, *params, verbose=False): # print(params) y = _np.zeros_like(x) for i in range(0, len(params), 3): if verbose: print(len(params), i) amp = params[i] pos = params[i + 1] sig = params[i + 2] y = y + _math_functions.gauss(x, amp, pos, sig) return y out = {} x = sd.index.values y = sd.values x = x[~ _np.isnan(y)] y = y[~ _np.isnan(y)] if len(x) == 0: out['res_gf_contribution'] = None # raise ValueError('nothing to fit') return out # return False if log: x_orig = x.copy() # we have to keep it to avoide rounding errors when doing a back and forth calculation x = _np.log10(x) out['as_fitted'] = (x, y) # [5.3,0.12,0.03] start_width = 0.02 width_ll = 0.01 width_ul = 0.035 peak_args = find_peak_arg(x, y, start_w=start_width, bounds=(width_ll, width_ul)) out['peak_args'] = peak_args param = [] bound_l = [] bound_h = [] for pa in peak_args: # amp # print('amp: ', y[pa]) param.append(y[pa]) # bound_l.append(-np.inf) bound_l.append(0) bound_h.append(_np.inf) # pos # print('pos: ', 10**x[pa]) param.append(x[pa]) pllt = x[pa] * (1 - 0.1) pult = x[pa] * (1 + 0.1) # swap if upper limit lower than lower limet ... which happens if position is negative if pult < pllt: pult, pllt = [pllt, pult] bound_l.append(pllt) bound_h.append(pult) # sig # ul_ll_ratio = 2 # wllt = 0.1 * 10**(x[pa]) # wult = wllt * ul_ll_ratio # ul_ll_ratio = 2 wllt = 0.01 wult = wllt * 10 ** (x[pa]) * 1.8 param.append((wllt + wult) / 2.) # print('pos: {}; wllt: {}; wult: {}; diff: {}'.format(10**(x[pa]), wllt, wult, (wult-wllt))) if (wult - wllt) < 0: raise ValueError('upper bound must be higher than lower bound. wul:{}, wll:{}'.format(wult, wllt)) if (pult - pllt) < 0: raise ValueError('upper bound must be higher than lower bound. pul:{}, pll:{}'.format(pult, pllt)) bound_l.append(wllt) bound_h.append(wult) # sometimes fits don't work, following tries to fix it x = x.astype(float) y = y.astype(float) try: param, pcov = _curve_fit(multi_gauss, x, y, p0=param, bounds=(bound_l, bound_h)) except RuntimeError: # file sgptdmahygC1.b1.20110226.003336.cdf at '2011-02-26 11:49:44' is fittable after deviding the amplitudes by 2 paramt = _np.array(param) paramt[::3] /= 10 try: param, pcov = _curve_fit(multi_gauss, x, y, p0=paramt, bounds=(bound_l, bound_h)) except RuntimeError: # increas of number of evaluation as needed in sgptdmahygC1.b1.20110331.075458.cdf paramt = _np.array(param) param, pcov = _curve_fit(multi_gauss, x, y, p0=paramt, bounds=(bound_l, bound_h), max_nfev = 10000) out['fit_pcov'] = pcov y_fit = multi_gauss(x, *param) param = param.reshape(len(peak_args), 3).transpose() param_df = _pd.DataFrame(param.transpose(), columns=['amp', 'pos', 'sig']) out['fit_res_param_pre'] = param_df.copy() #### individual peaks gaus = _pd.DataFrame(index=x) for idx in param_df.index: gaus[idx] = _pd.Series( _math_functions.gauss(x, param_df.loc[idx, 'amp'], param_df.loc[idx, 'pos'], param_df.loc[idx, 'sig']), index=x) sum_peaks = gaus.sum(axis=1) #### fix x axis back to diameter if log: param[1] = 10 ** param[1] x = 10 ** x # dist_by_type.index = x_orig param_df.index.name = 'peak' out['fit_res_param'] = param_df fit_res = _pd.DataFrame(y_fit, index=x, columns=['fit_res']) fit_res['data'] = _pd.Series(y, index=x) out['fit_res'] = fit_res out['fit_res_std'] = _np.sqrt(((fit_res.data - fit_res.fit_res) ** 2).sum()) # dist_by_type.index.name = 'growth factor' # dist_by_type.columns.name = 'peak_no' # out['dist_by_type'] = dist_by_type gaus.index = x out['fit_res_individual'] = gaus res_gf_contribution = _pd.DataFrame(gaus.sum() * (1 / gaus.sum().sum()), columns=['ratio']) res_gf_contribution['gf'] = param_df['pos'] res_gf_contribution[res_gf_contribution.ratio < 0.01 / (2 ** 6 / 1)] = _np.nan res_gf_contribution.dropna(inplace=True) out['res_gf_contribution'] = res_gf_contribution return out def calc_mixing_state(growth_modes): """Calculate a value that represents how aerosols are mixed, internally or externally. Therefor, the pythagoras of the ratios of aerosols in the different growth modes is calculated. E.g. if there where 3 growth modes and the respective aerosol ratios in each mode is r1, r2, and r3 the mixing_state would be sqrt(r1**2 + r2**2 + r3**2) Parameters ---------- growth_modes: pandas.DataFrame The DataFrame should contain the ratios of has particles in the different growth modes Returns ------- mixing_state: float """ if isinstance(growth_modes,type(None)): return _np.nan ms = _np.sqrt((growth_modes.ratio ** 2).sum()) return ms def apply_growth2sizedist(sd, gf): assert(False), 'Maybe just make sure to go to numberconcentration before applying any of this below!!! Warning, this function has a problem when the growth is larger than a single bin width, check the function grow_sizedistribution in the sizedistribution function' def apply_growth_factor_gf_const(data, gf, bins): if gf == 1.: return data.copy(), bins.copy() if _np.isnan(gf): data = data.copy() data.iloc[:, :] = _np.nan return data, bins.copy() # In case gf smaller then inverted = False if gf < 1: inverted = True gf = 1 / gf binst = bins[::-1] data = data.iloc[:, ::-1] dividx = binst.shape[0] // 2 binslog = _np.log10(binst) tmp = binslog.max() + binslog.min() transform = lambda x: -1 * (x - tmp) binslogn = transform(binslog) binsn = 10 ** binslogn bins = binsn gfp = gf - 1 width = bins[1:] - bins[:-1] widthlog = _np.log10(bins[1:]) - _np.log10(bins[:-1]) width_in_percent_of_low_bin_edge = width / bins[:-1] no_extra_bins = int(_np.ceil(gfp / width_in_percent_of_low_bin_edge[-1])) # new / extra bins extra_bins = _np.zeros(no_extra_bins) extra_bins[:] = widthlog[-1] extra_bins = extra_bins.cumsum() extra_bins += _np.log10(bins[-1]) extra_bins = 10 ** extra_bins bins_new = _np.append(bins, extra_bins) # width_new = bins_new[1:] - bins_new[:-1] # widthlog_new = _np.log10(bins_new[1:]) - _np.log10(bins_new[:-1]) # width_in_percent_of_low_bin_edge_extra_bins = width_new / bins_new[:-1] bins_grown = bins_new * gf i = no_extra_bins while 1: end = i - 1 if end == 0: end = None else: end = -end in_first_bin = (bins_new[i:] - bins_grown[:-i]) / (bins_grown[1:end] - bins_grown[:-i]) if _np.any(in_first_bin >= 1): # break i -= 1 continue else: break in_second_bin = (bins_grown[1:end] - bins_new[i:]) / (bins_grown[1:end] - bins_grown[:-i]) if _np.any(in_second_bin < 0): txt = 'This should not be possible' raise ValueError(txt) # data with extra bins bincenters_new = ((bins_new[1:] + bins_new[:-1]) / 2).astype(_np.float32) bincenters = ((bins[1:] + bins[:-1]) / 2).astype(_np.float32) # depending how data was created (POPS, ARM, ...) the type data.columns = bincenters # can vary between float32 and float64, this is to unify them. df = _pd.DataFrame(columns=bincenters_new) data = _pd.concat([df, data]) ####### # print('shape_data_new', data.shape) # print('shape_data_slice', data.iloc[:, :end].values.shape) # print('shape_firstb', in_first_bin.shape) # print('+++++++++++') ###### # shift and make new data data_in_first_bin = data.iloc[:, :end].values * in_first_bin data_in_second_bin = data.iloc[:, :end].values * in_second_bin dffb = _pd.DataFrame(data_in_first_bin, columns=data.iloc[:, i - 1:].columns) dfsb = _pd.DataFrame(data_in_second_bin[:, :-1], columns=data.iloc[:, i:].columns) dffsb = dffb + dfsb data_t = _pd.concat([df, dffsb]) data_new = _pd.DataFrame(data_t) data_new.index = data.index data_new = data_new.astype(float) if inverted: bins_new = 10 ** transform(_np.log10(bins_new))[::-1] data_new = data_new.iloc[:, ::-1] return data_new, bins_new sd = sd.convert2numberconcentration() # ensure that gf is either float or ndarray if type(gf).__name__ in ('ndarray', 'float', 'float16', 'float32', 'float64', 'float128'): pass elif type(gf).__name__ == 'DataFrame': gf = gf.iloc[:, 0].values elif hasattr(gf, 'data'): gf = gf.data.iloc[:, 0].values # if gf-ndarray consists of identical values ... convert to float if type(gf).__name__ == 'ndarray': unique = _np.unique(gf) if unique.shape[0] == 1: gf = unique[0] # if gf is still ndarray, loop through all gf if type(gf).__name__ == 'ndarray': # ensure that length is correct if gf.shape[0] != sd.data.shape[0]: txt = 'length of growhfactor (shape: {}) does not match that of the size distribution (shape: {}).'.format( gf.shape, sd.data.shape) raise ValueError(txt) data_new_list = [] bins_list = [] for e, gfs in enumerate(gf): data_new, bins_new = apply_growth_factor_gf_const(sd.data.iloc[[e], :], gfs, sd.bins) data_new_list.append(data_new) bins_list.append(bins_new) bins_list.sort(key=lambda x: x.max()) bins_new = bins_list[-1] data_new = _pd.concat(data_new_list) else: data_new, bins_new = apply_growth_factor_gf_const(sd.data, gf, sd.bins) if type(sd).__name__ == "SizeDist_LS": sd_grown = type(sd)(data_new, bins_new, 'numberConcentration', sd.layerbounderies) elif type(sd).__name__ == "SizeDist": sd_grown = type(sd)(data_new, bins_new, 'numberConcentration') else: sd_grown = type(sd)(data_new, bins_new, 'numberConcentration', ignore_data_gap_error = True) sd_grown.optical_properties.parameters.wavelength = sd.parameters4reductions.wavelength.value sd.data = data_new sd.bins = bins_new return sd def apply_hygro_growth2sizedist(sizedist, how='shift_data', adjust_refractive_index=True): """Note kappa values are !!NOT!! aligned to self in case its timesersies how: string ['shift_bins', 'shift_data'] If the shift_bins the growth factor has to be the same for all lines in data (important for timeseries and vertical profile. If gf changes (as probably the case in TS and LS) you want to use 'shift_data' """ sizedist.parameters4reductions._check_growth_parameters_exist() dist_g = sizedist.convert2numberconcentration() kappa = dist_g.parameters4reductions.kappa.value RH = dist_g.parameters4reductions.RH.value refract_idx = dist_g.parameters4reductions.refractive_index.value # make sure kappa and RH have the appropriate types if type(kappa).__name__ in ('ndarray','float', 'float16', 'float32', 'float64', 'float128'): pass elif type(kappa).__name__ == 'DataFrame': kappa = kappa.iloc[:, 0].values elif hasattr(kappa, 'data'): kappa = kappa.data.iloc[:, 0].values if type(RH).__name__ in ('ndarray', 'float', 'float16', 'float32', 'float64', 'float128'): pass elif type(RH).__name__ == 'DataFrame': RH = RH.iloc[:, 0].values elif hasattr(RH, 'data'): RH = RH.data.iloc[:, 0].values gf = kappa_simple(kappa, RH, refractive_index = refract_idx) if type(gf) == tuple: gf, n_mix = gf else: n_mix = None if how == 'shift_bins': if not isinstance(gf, (float, int)): txt = '''If how is equal to 'shift_bins' RH has to be of type int or float. It is %s''' % (type(RH).__name__) raise TypeError(txt) dist_g = apply_growth2sizedist(dist_g, gf) dist_g.gf = gf if how == 'shift_bins': dist_g.parameters4reductions.refractive_index = n_mix elif how == 'shift_data': if adjust_refractive_index: if type(n_mix).__name__ in ('float', 'int', 'float64','NoneType', 'complex'): nda = _np.zeros(dist_g.data.index.shape) nda[:] = n_mix n_mix = nda df = _pd.DataFrame(n_mix) df.columns = ['index_of_refraction'] df.index = dist_g.data.index dist_g.parameters4reductions.refractive_index = df else: dist_g.parameters4reductions.refractive_index = sizedist.parameters4reductions.refractive_index return dist_g # def apply_growth_distribution_on_sizedist(sd, growth_dist, RH_high): # """Apply hygroscopic growth on dry sizedistribution (sd) by applying a growth distribution (growth_dist). # Parameters # ---------- # sd: sizedist_TS instance # growth_dist: growth_distribution instance # RH: float # Relative humidity at which the grown sizedistribution is supposed to calculated""" # gmk = growth_dist.growth_modes_kappa # sdtsumlist = [] # sd_growth_res = {} # for u,i in enumerate(gmk.index.unique()): # # get sizedist and kappa for the particular time ... kappa contains likely multiple values # gmkt = gmk.loc[i,:] # sdd = sd.data.loc[i,:] # # # make a size distribution from the particular slice # sdsd = _sizedistribution.SizeDist_TS(_pd.DataFrame(sdd).transpose(), sd.bins, sd.distributionType) # sdsd.hygroscopicity.parameters.refractive_index = sd.parameters4reductions.refractive_index # sdsd.hygroscopicity.parameters.RH = RH_high # datasum = None # sd_growth_res_dict = {} # sd_growth_dict_list = [] # for e, (_,gm) in enumerate(gmkt.iterrows()): # sd_growth_dict = {} # sdt = sdsd.copy() # sdt.data *= gm.ratio # if gm.kappa < 0: # kappa = 0.0001 #in principle this is a bug ... does not like kappa == 0 # else: # kappa = gm.kappa # # sdt.hygroscopicity.parameters.kappa = kappa # sdtg = sdt.hygroscopicity.grown_size_distribution # # sd_growth_dict['kappa'] = kappa # sd_growth_dict['size_dist_grown'] = sdtg # # ###### # # in order to be able merge size distributions we have to find the biggest bins # if e == 0: # datasum = sdtg.data # lastbin = sdtg.bins[-1] # bins = sdtg.bins.copy() # tbins = sdtg.bins.copy() # else: # if sdtg.bins[-1] > lastbin: # lastbin = sdtg.bins[-1] # bins = sdtg.bins.copy() # lbins = sdtg.bins.copy() # datasum = datasum.add(sdtg.data, fill_value = 0) # # ##### # # add dict to list # sd_growth_dict_list.append(sd_growth_dict) # # # sdtsum = _sizedistribution.SizeDist(datasum, bins, sdtg.distributionType) # sdtsumlist.append(sdtsum) # sd_growth_res_dict['index'] = i # sd_growth_res_dict['individual'] = sd_growth_dict_list # sd_growth_res_dict['sum'] = sdtsum # if u == 0: # sdtsumall = sdtsum.data # binsall = bins.copy() # lastbinall = bins[-1] # else: # if bins[-1] > lastbinall: # binsall = bins.copy() # lastbinall = bins[-1] # sdtsumall = sdtsumall.add(sdtsum.data, fill_value = 0) # ## enter into res dictionary # sd_growth_res[i] = sd_growth_res_dict # # if u == 19: # # break # # # sdtsout = _sizedistribution.SizeDist_TS(sdtsumall, binsall, sdtg.distributionType) # out = {} # out['grown_size_dists_sum'] = sdtsout # out['grown_size_dists_individual'] = sd_growth_res # return SizeDistGrownByGrowthDistribution(out) class HygroscopicityAndSizedistributions(object): """In the future it would be nice if this class handles how a size distributions react to hygroscopic growth. As you can see, the class points back to function in sizeditribution. Would be nice to move all that stuff here at some point""" def __init__(self, parent): self._parent_sizedist = parent self.parameters = _sizedistribution._Parameters4Reductions_hygro_growth(parent) self._grown_size_distribution = None self._f_RH = None self._f_RH_85_0 = None self._f_RH_85_40 = None # #todo: this needs to be integrated better # self.RH = None def _get_f_RH(self, RH_low, RH_high): return get_f_of_RH_from_dry_sizedistribution(self._parent_sizedist, RH_low, RH_high) @property def f_RH(self): if not self._f_RH: self._f_RH = get_f_of_RH_from_dry_sizedistribution(self._parent_sizedist, 0, self.parameters.RH.value) return self._f_RH @property def f_RH_85_0(self): if not self._f_RH_85_0: self._f_RH_85_0 = get_f_of_RH_from_dry_sizedistribution(self._parent_sizedist, 0, 85) return self._f_RH_85_0 @property def f_RH_85_40(self): if not self._f_RH_85_40: self._f_RH_85_40 = get_f_of_RH_from_dry_sizedistribution(self._parent_sizedist, 40, 85) return self._f_RH_85_40 @property def grown_size_distribution(self): if not self._grown_size_distribution: self.parameters._check_growth_parameters_exist() if self.parameters.kappa: # self._grown_size_distribution = self._parent_sizedist.apply_hygro_growth(self.parameters.kappa.value, self.parameters.RH.value) self._grown_size_distribution = apply_hygro_growth2sizedist(self._parent_sizedist) else: self._grown_size_distribution = SizeDistGrownByGrowthDistribution(self) #apply_growth_distribution_on_sizedist(self._parent_sizedist, self.parameters.growth_distribution.value, self.parameters.RH.value) return self._grown_size_distribution # @property # def fRH_85(self): # """f(RH) at 85 and 0 RH""" # sd.hygroscopicity.parameters.RH = 85 # scattcoff85 = sd.hygroscopicity.grown_size_distribution.optical_properties.scattering_coeff.copy() # sd.hygroscopicity.parameters.RH = 40 # scattcoff40 = sd.hygroscopicity.grown_size_distribution.optical_properties.scattering_coeff.copy() class SizeDistGrownByGrowthDistribution(object): """When applying a growth distribution to a sizeditribution you get a lot of sizedistributionthat are grown by a different amount. This class is here to take care of it.""" def __init__(self, parent): self._parent = parent self._grown_sizedistribution = None self._sum_of_all_sizeditributions = None self._individual_sizedistributions = None self._optical_properties = None @property def sum_of_all_sizeditributions(self): self._result return self._sum_of_all_sizeditributions @property def individual_sizedistributions(self): self._result return self._individual_sizedistributions @property def optical_properties(self): if not self._optical_properties: self._optical_properties = SizeDistGrownByGrowthDistributionOpticalProperties(self) return self._optical_properties @property def _result(self): if not self._grown_sizedistribution: self._grown_sizedistribution = self._apply_growth_distribution_on_sizedist() return self._grown_sizedistribution def _apply_growth_distribution_on_sizedist(self): """Apply hygroscopic growth on dry sizedistribution (sd) by applying a growth distribution (growth_dist). Parameters ---------- sd: sizedist_TS instance growth_dist: growth_distribution instance RH: float Relative humidity at which the grown sizedistribution is supposed to calculated""" gmk = self._parent.parameters.growth_distribution.value.growth_modes_kappa RH_heigh = self._parent.parameters.RH.value sd = self._parent._parent_sizedist.convert2numberconcentration() sdtsumlist = [] sd_growth_res = {} first_timestamp = True for u, i in enumerate(gmk.index.unique()): sd_growth_res_dict = {} sd_growth_dict_list = [] # get sizedist, refractive index, and kappa for the particular time ... kappa contains likely multiple values gmkt = gmk.loc[[i], :] # sometimes there a growth mode by no tdmaaps file (no idea why that is, its the same instrument ... there should at least be one thats labeled as bad?!?) try: sdd = sd.data.loc[i, :] except KeyError: continue if _np.isnan(gmkt.kappa.iloc[0]): sd_growth_dict = {} sd_growth_dict['kappa'] = _np.nan sdd.loc[:] = _np.nan sdsd = _sizedistribution.SizeDist_TS(_pd.DataFrame(sdd).transpose(), sd.bins, sd.distributionType) sdsd.hygroscopicity.parameters.refractive_index = 1.5 #the actual number here does not matter since there is no size distribution data to begin with sd_growth_dict['size_dist_grown'] = sdsd sd_growth_dict_list.append(sd_growth_dict) datasum = sdsd.data bins = sdsd.bins.copy().astype(_np.float32) else: if type(sd.parameters4reductions.refractive_index.value).__name__ == 'DataFrame': ref_idx = sd.parameters4reductions.refractive_index.value.loc[i].values[0] elif 'float' in type(sd.parameters4reductions.refractive_index.value).__name__: ref_idx = sd.parameters4reductions.refractive_index.value elif 'int' in type(sd.parameters4reductions.refractive_index.value).__name__: ref_idx = sd.parameters4reductions.refractive_index.value elif type(sd.parameters4reductions.refractive_index.value).__name__ == 'NoneType': ref_idx = None # make a size distribution from the particular slice sdsd = _sizedistribution.SizeDist_TS(_pd.DataFrame(sdd).transpose(), sd.bins, sd.distributionType) sdsd.hygroscopicity.parameters.refractive_index = ref_idx #sd.parameters4reductions.refractive_index.value sdsd.hygroscopicity.parameters.RH = RH_heigh datasum = None for e, (_, gm) in enumerate(gmkt.iterrows()): sd_growth_dict = {} sdt = sdsd.copy() sdt.data *= gm.ratio if gm.kappa < 0: kappa = 0.0001 # in principle this is a bug ... does not like kappa == 0 else: kappa = gm.kappa sdt.hygroscopicity.parameters.kappa = kappa sdtg = sdt.hygroscopicity.grown_size_distribution sd_growth_dict['kappa'] = kappa sd_growth_dict['size_dist_grown'] = sdtg ###### # in order to be able merge size distributions we have to find the biggest bins if e == 0: datasum = sdtg.data lastbin = sdtg.bins[-1] bins = sdtg.bins.copy() # tbins = sdtg.bins.copy() else: if sdtg.bins[-1] > lastbin: lastbin = sdtg.bins[-1] bins = sdtg.bins.copy() datasum = datasum.add(sdtg.data, fill_value=0) ##### # add dict to list sd_growth_dict_list.append(sd_growth_dict) sdtsum = _sizedistribution.SizeDist(datasum, bins, sd.distributionType) sdtsum.data.columns = sdtsum.data.columns.values.astype(_np.float32) sdtsumlist.append(sdtsum) sd_growth_res_dict['index'] = i sd_growth_res_dict['individual'] = sd_growth_dict_list sd_growth_res_dict['sum'] = sdtsum if first_timestamp: sdtsumall = sdtsum.data binsall = bins.copy() lastbinall = bins[-1] first_timestamp = False else: if bins[-1] > lastbinall: binsall = bins.copy() lastbinall = bins[-1] sdtsumall = sdtsumall.add(sdtsum.data, fill_value=0) ## enter into res dictionary sd_growth_res[i] = sd_growth_res_dict # if u == 19: # break # import pdb; pdb.set_trace() sdtsout = _sizedistribution.SizeDist_TS(sdtsumall, binsall, sd.distributionType, ignore_data_gap_error = True) out = {} out['grown_size_dists_sum'] = sdtsout self._sum_of_all_sizeditributions = sdtsout out['grown_size_dists_individual'] = sd_growth_res self._individual_sizedistributions = sd_growth_res return SizeDistGrownByGrowthDistribution(out) class SizeDistGrownByGrowthDistributionOpticalProperties(object): def __init__(self, parent): self._parent = parent self._optical_properties = None self._scattering_coeff = None @property def _result(self): if not self._optical_properties: self._optical_properties = self._calculate_optical_properties() return self._optical_properties @property def scattering_coeff(self): self._result return self._scattering_coeff def _calculate_optical_properties(self): for a, index in enumerate(self._parent.individual_sizedistributions.keys()): for e, indi in enumerate(self._parent.individual_sizedistributions[index]['individual']): sdgt = indi['size_dist_grown'] sdgt.optical_properties.parameters.wavelength = self._parent._parent._parent_sizedist.optical_properties.parameters.wavelength if e == 0: scattering_coeff = sdgt.optical_properties.scattering_coeff.data.copy() else: scattering_coeff += sdgt.optical_properties.scattering_coeff.data if a == 0: scattering_coeff_ts = scattering_coeff.copy() else: scattering_coeff_ts = _pd.concat([scattering_coeff_ts, scattering_coeff]) scattering_coeff_ts.sort_index(inplace=True) self._scattering_coeff = _timeseries.TimeSeries(scattering_coeff_ts, sampling_period= self._parent._parent._parent_sizedist._data_period) return True class HygroscopicGrowthFactorDistributions(_timeseries.TimeSeries_2D): def __init__(self, *args, RH_high = None, RH_low = None): super().__init__(*args) self._reset() self.RH_high = RH_high self.RH_low = RH_low def _reset(self): self.__fit_results = None self._growth_modes_kappa = None @property def _fit_results(self): if not self.__fit_results: self._mixing_state = _pd.DataFrame(index=self.data.index, columns=['mixing_state']) for e, i in enumerate(self.data.index): hd = self.data.loc[i, :] # hd = self.data.iloc[15,:] fit_res = _fit_normals(hd) ### mixing_state = calc_mixing_state(fit_res['res_gf_contribution']) self._mixing_state.loc[i, 'mixing_state'] = mixing_state self._fit_res_of_last_distribution = fit_res groth_modes_t = fit_res['res_gf_contribution'] if isinstance(groth_modes_t, type(None)): groth_modes_t = _pd.DataFrame(index=[i], columns=['ratio', 'gf']) else: groth_modes_t['datetime'] = _pd.Series() groth_modes_t['datetime'] = i groth_modes_t.index = groth_modes_t['datetime'] groth_modes_t.drop('datetime', axis=1, inplace=True) if e == 0: self._growth_modes = groth_modes_t else: self._growth_modes = self._growth_modes.append(groth_modes_t) # break self.__fit_results = True @property def growth_modes_gf(self): self._fit_results return self._growth_modes @property def growth_modes_kappa(self): if not _np.any(self._growth_modes_kappa): gm = self.growth_modes_gf.copy() gm['kappa'] = _pd.Series(kappa_simple(gm.gf.values, self.RH_high, inverse=True), index=gm.index) gm.drop('gf', axis=1, inplace=True) self._growth_modes_kappa = gm return self._growth_modes_kappa @property def mixing_state(self): self._fit_results return self._mixing_state def plot(hgfd, growth_modes=True, scatter_kw = {}, **kwargs): f, a, pc, cb = super().plot(**kwargs) # pc_kwargs={ # # 'cmap': plt_tools.get_colorMap_intensity_r(), # 'cmap': plt.cm.gist_earth, # }) pc.set_cmap(_plt.cm.gist_earth) # cols = plt_tools.color_cycle[1] if growth_modes: a.scatter(hgfd.growth_modes_gf.index, hgfd.growth_modes_gf.gf, s=hgfd.growth_modes_gf.ratio * 200, **scatter_kw # color=_plt_tools.color_cycle[1] ) return f, a, pc, cb
true
6cc729afb119a596159d908ab12b4947150d7a14
Python
ejhigson/nestcheck
/nestcheck/data_processing.py
UTF-8
31,846
2.96875
3
[ "MIT" ]
permissive
#!/usr/bin/env python r"""Module containing functions for loading and processing output files produced by nested sampling software. Background: threads ------------------- ``nestcheck``'s error estimates and diagnostics rely on the decomposition of a nested sampling run into multiple runs, each with a single live point. We refer to these constituent single live point runs as *threads*. See "Sampling Errors In Nested Sampling Parameter Estimation" (Higson et al. 2018) for a detailed discussion, including an algorithm for dividing nested sampling runs into their constituent threads. Nested sampling run format -------------------------- ``nestcheck`` stores nested sampling runs in a standard format as python dictionaries. For a run with :math:`n_\mathrm{samp}` samples, the keys are: logl: 1d numpy array Loglikelihood values (floats) for each sample. Shape is (:math:`n_\mathrm{samp}`,). thread_labels: 1d numpy array Integer label for each point representing which thread each point belongs to. Shape is (:math:`n_\mathrm{samp}`,). For some thread label k, the thread's start (birth) log-likelihood and end log-likelihood are given by thread_min_max[k, :]. thread_min_max: 2d numpy array Shape is (:math:`n_\mathrm{threads}`, 2). Each row with index k contains the logl from within which the first point in the thread with label k was sampled (the "birth contour") and the logl of the final point in the thread. The birth contour is -inf if the thread began by sampling from the whole prior. theta: 2d numpy array Parameter values for samples - each row represents a sample. Shape is (:math:`n_\mathrm{samp}`, d) where d is number of dimensions. nlive_array: 1d numpy array Number of live points present between the previous point and this point. output: dict (optional) Dict containing extra information about the run. Samples are arranged in ascending order of logl. Processing nested sampling software output ------------------------------------------ To process output files for a nested sampling run into the format described above, the following information is required: * Samples' loglikelihood values; * Samples' parameter values; * Information allowing decomposition into threads and identifying each thread's birth contour (starting logl). The first two items are self-explanatory, but the latter is more challenging as it can take different formats and may not be provided by all nested sampling software packages. Sufficient information for thread decomposition and calculating the number of live points (including for dynamic nested sampling) is provided by a list of the loglikelihoods from within which each point was sampled (the points' birth contours). This is output by ``PolyChord`` >= v1.13 and ``MultiNest`` >= v3.11, and is used in the output processing for these packages via the ``birth_inds_given_contours`` and ``threads_given_birth_inds`` functions. Also sufficient is a list of the indexes of the point which was removed at the step when each point was sampled ("birth indexes"), as this can be mapped to the birth contours and vice versa. ``process_dynesty_run`` does not require the ``birth_inds_given_contours`` and ``threads_given_birth_inds`` functions as ``dynesty`` results objects already include thread labels via their ``samples_id`` property. If the ``dynesty`` run is dynamic, the ``batch_bounds`` property is need to determine the threads' starting birth contours. Adding a new processing function for another nested sampling package -------------------------------------------------------------------- You can add new functions to process output from other nested sampling software, provided the output files include the required information for decomposition into threads. Depending on how this information is provided you may be able to adapt ``process_polychord_run`` or ``process_dynesty_run``. If thread decomposition information if provided in a different format, you will have to write your own helper functions to process the output into the ``nestcheck`` dictionary format described above. """ import os import re import warnings import copy import numpy as np import nestcheck.io_utils import nestcheck.ns_run_utils import nestcheck.parallel_utils @nestcheck.io_utils.save_load_result def batch_process_data(file_roots, **kwargs): """Process output from many nested sampling runs in parallel with optional error handling and caching. The result can be cached using the 'save_name', 'save' and 'load' kwargs (by default this is not done). See save_load_result docstring for more details. Remaining kwargs passed to parallel_utils.parallel_apply (see its docstring for more details). Parameters ---------- file_roots: list of strs file_roots for the runs to load. base_dir: str, optional path to directory containing files. process_func: function, optional function to use to process the data. func_kwargs: dict, optional additional keyword arguments for process_func. errors_to_handle: error or tuple of errors, optional which errors to catch when they occur in processing rather than raising. save_name: str or None, optional See nestcheck.io_utils.save_load_result. save: bool, optional See nestcheck.io_utils.save_load_result. load: bool, optional See nestcheck.io_utils.save_load_result. overwrite_existing: bool, optional See nestcheck.io_utils.save_load_result. Returns ------- list of ns_run dicts List of nested sampling runs in dict format (see the module docstring for more details). """ base_dir = kwargs.pop('base_dir', 'chains') process_func = kwargs.pop('process_func', process_polychord_run) func_kwargs = kwargs.pop('func_kwargs', {}) func_kwargs['errors_to_handle'] = kwargs.pop('errors_to_handle', ()) data = nestcheck.parallel_utils.parallel_apply( process_error_helper, file_roots, func_args=(base_dir, process_func), func_kwargs=func_kwargs, **kwargs) # Sort processed runs into the same order as file_roots (as parallel_apply # does not preserve order) data = sorted(data, key=lambda x: file_roots.index(x['output']['file_root'])) # Extract error information and print errors = {} for i, run in enumerate(data): if 'error' in run: try: errors[run['error']].append(i) except KeyError: errors[run['error']] = [i] for error_name, index_list in errors.items(): message = (error_name + ' processing ' + str(len(index_list)) + ' / ' + str(len(file_roots)) + ' files') if len(index_list) != len(file_roots): message += ('. Roots with errors have (zero based) indexes: ' + str(index_list)) print(message) # Return runs which did not have errors return [run for run in data if 'error' not in run] def process_error_helper(root, base_dir, process_func, errors_to_handle=(), **func_kwargs): """Wrapper which applies process_func and handles some common errors so one bad run does not spoil the whole batch. Useful errors to handle include: OSError: if you are not sure if all the files exist AssertionError: if some of the many assertions fail for known reasons; for example is there are occasional problems decomposing runs into threads due to limited numerical precision in logls. Parameters ---------- root: str File root. base_dir: str Directory containing file. process_func: func Function for processing file. errors_to_handle: error type or tuple of error types Errors to catch without throwing an exception. func_kwargs: dict Kwargs to pass to process_func. Returns ------- run: dict Nested sampling run dict (see the module docstring for more details) or, if an error occured, a dict containing its type and the file root. """ try: return process_func(root, base_dir, **func_kwargs) except errors_to_handle as err: run = {'error': type(err).__name__, 'output': {'file_root': root}} return run def process_polychord_run(file_root, base_dir, process_stats_file=True, **kwargs): """Loads data from a PolyChord run into the nestcheck dictionary format for analysis. N.B. producing required output file containing information about the iso-likelihood contours within which points were sampled (where they were "born") requies PolyChord version v1.13 or later and the setting write_dead=True. Parameters ---------- file_root: str Root for run output file names (PolyChord file_root setting). base_dir: str Directory containing data (PolyChord base_dir setting). process_stats_file: bool, optional Should PolyChord's <root>.stats file be processed? Set to False if you don't have the <root>.stats file (such as if PolyChord was run with write_stats=False). kwargs: dict, optional Options passed to ns_run_utils.check_ns_run. Returns ------- ns_run: dict Nested sampling run dict (see the module docstring for more details). """ # N.B. PolyChord dead points files also contains remaining live points at # termination samples = np.loadtxt(os.path.join(base_dir, file_root) + '_dead-birth.txt') ns_run = process_samples_array(samples, **kwargs) ns_run['output'] = {'base_dir': base_dir, 'file_root': file_root} if process_stats_file: try: ns_run['output'] = process_polychord_stats(file_root, base_dir) except (OSError, IOError, ValueError, IndexError, NameError, TypeError) as err: warnings.warn( ('process_polychord_stats raised {} processing {}.stats file. ' ' I am proceeding without the .stats file.').format( type(err).__name__, os.path.join(base_dir, file_root)), UserWarning) return ns_run def process_multinest_run(file_root, base_dir, **kwargs): """Loads data from a MultiNest run into the nestcheck dictionary format for analysis. N.B. producing required output file containing information about the iso-likelihood contours within which points were sampled (where they were "born") requies MultiNest version 3.11 or later. Parameters ---------- file_root: str Root name for output files. When running MultiNest, this is determined by the nest_root parameter. base_dir: str Directory containing output files. When running MultiNest, this is determined by the nest_root parameter. kwargs: dict, optional Passed to ns_run_utils.check_ns_run (via process_samples_array) Returns ------- ns_run: dict Nested sampling run dict (see the module docstring for more details). """ # Load dead and live points dead = np.loadtxt(os.path.join(base_dir, file_root) + 'dead-birth.txt') live = np.loadtxt(os.path.join(base_dir, file_root) + 'phys_live-birth.txt') # Remove unnecessary final columns dead = dead[:, :-2] live = live[:, :-1] assert dead[:, -2].max() < live[:, -2].min(), ( 'final live points should have greater logls than any dead point!', dead, live) ns_run = process_samples_array(np.vstack((dead, live)), **kwargs) assert np.all(ns_run['thread_min_max'][:, 0] == -np.inf), ( 'As MultiNest does not currently perform dynamic nested sampling, all ' 'threads should start by sampling the whole prior.') ns_run['output'] = {} ns_run['output']['file_root'] = file_root ns_run['output']['base_dir'] = base_dir return ns_run def process_dynesty_run(results): """Transforms results from a dynesty run into the nestcheck dictionary format for analysis. This function has been tested with dynesty v9.2.0. Note that the nestcheck point weights and evidence will not be exactly the same as the dynesty ones as nestcheck calculates logX volumes more precisely (using the trapezium rule). This function does not require the birth_inds_given_contours and threads_given_birth_inds functions as dynesty results objects already include thread labels via their samples_id property. If the dynesty run is dynamic, the batch_bounds property is need to determine the threads' starting birth contours. Parameters ---------- results: dynesty results object N.B. the remaining live points at termination must be included in the results (dynesty samplers' run_nested method does this if add_live_points=True - its default value). Returns ------- ns_run: dict Nested sampling run dict (see the module docstring for more details). """ samples = np.zeros((results.samples.shape[0], results.samples.shape[1] + 3)) samples[:, 0] = results.logl samples[:, 1] = results.samples_id samples[:, 3:] = results.samples unique_th, first_inds = np.unique(results.samples_id, return_index=True) assert np.array_equal(unique_th, np.asarray(range(unique_th.shape[0]))) thread_min_max = np.full((unique_th.shape[0], 2), np.nan) is_dynamic_dynesty = False try: # Try processing standard nested sampling results assert unique_th.shape[0] == results.nlive assert np.array_equal( np.unique(results.samples_id[-results.nlive:]), np.asarray(range(results.nlive))), ( 'perhaps the final live points are not included?') thread_min_max[:, 0] = -np.inf except AttributeError: # If results has no nlive attribute, it must be dynamic nested sampling assert unique_th.shape[0] == sum(results.batch_nlive) # if the object has a samples_n attribute, it is from dynesty if hasattr(results, 'samples_n'): is_dynamic_dynesty = True #numpy diff goes out[i] = samples[i+1] - samples[i], so it records the #samples added/removed at samples[i] diff_nlive = np.diff(results.samples_n) #results.samples_n tells us how many live samples there are at a given iteration, #so use the diff of this to assign the samples[change_in_nlive_at_sample (col 2)] #value. We know we want the last n_live to end with 1 samples[:-1,2] = diff_nlive for th_lab, ind in zip(unique_th, first_inds): thread_min_max[th_lab, 0] = ( results.batch_bounds[results.samples_batch[ind], 0]) for th_lab in unique_th: final_ind = np.where(results.samples_id == th_lab)[0][-1] thread_min_max[th_lab, 1] = results.logl[final_ind] if not is_dynamic_dynesty: samples[final_ind, 2] = -1 assert np.all(~np.isnan(thread_min_max)) run = nestcheck.ns_run_utils.dict_given_run_array(samples, thread_min_max) nestcheck.ns_run_utils.check_ns_run(run) return run def process_polychord_stats(file_root, base_dir): """Reads a PolyChord <root>.stats output file and returns the information contained in a dictionary. Parameters ---------- file_root: str Root for run output file names (PolyChord file_root setting). base_dir: str Directory containing data (PolyChord base_dir setting). Returns ------- output: dict See PolyChord documentation for more details. """ filename = os.path.join(base_dir, file_root) + '.stats' output = {'base_dir': base_dir, 'file_root': file_root} with open(filename, 'r') as stats_file: lines = stats_file.readlines() output['logZ'] = float(lines[8].split()[2]) output['logZerr'] = float(lines[8].split()[4]) # Cluster logZs and errors output['logZs'] = [] output['logZerrs'] = [] for line in lines[14:]: if line[:5] != 'log(Z': break output['logZs'].append(float( re.findall(r'=(.*)', line)[0].split()[0])) output['logZerrs'].append(float( re.findall(r'=(.*)', line)[0].split()[2])) # Other output info nclust = len(output['logZs']) output['ncluster'] = nclust output['nposterior'] = int(lines[20 + nclust].split()[1]) output['nequals'] = int(lines[21 + nclust].split()[1]) output['ndead'] = int(lines[22 + nclust].split()[1]) output['nlive'] = int(lines[23 + nclust].split()[1]) try: output['nlike'] = [int(x) for x in lines[24 + nclust].split()[1:]] if len(output['nlike']) == 1: output['nlike'] = output['nlike'][0] except ValueError: # if nlike has too many digits, PolyChord just writes ***** to .stats # file. This causes a ValueError output['nlike'] = np.nan line = lines[25 + nclust].split() i = line.index('(') # If there are multiple parameter speeds then multiple values are written # for avnlike and avnlikeslice output['avnlike'] = [float(x) for x in line[1:i]] # If only one value, keep as float if len(output['avnlike']) == 1: output['avnlike'] = output['avnlike'][0] output['avnlikeslice'] = [float(x) for x in line[i+1:-3]] # If only one value, keep as float if len(output['avnlikeslice']) == 1: output['avnlikeslice'] = output['avnlikeslice'][0] # Means and stds of dimensions (not produced by PolyChord<=1.13) if len(lines) > 29 + nclust: output['param_means'] = [] output['param_mean_errs'] = [] for line in lines[29 + nclust:]: if '------------------' in line: # A line of dashes is used to show the start of the derived # parameters in the .stats file for later versions of # PolyChord continue output['param_means'].append(float(line.split()[1])) output['param_mean_errs'].append(float(line.split()[3])) return output def process_samples_array(samples, **kwargs): """Convert an array of nested sampling dead and live points of the type produced by PolyChord and MultiNest into a nestcheck nested sampling run dictionary. Parameters ---------- samples: 2d numpy array Array of dead points and any remaining live points at termination. Has #parameters + 2 columns: param_1, param_2, ... , logl, birth_logl kwargs: dict, optional Options passed to birth_inds_given_contours Returns ------- ns_run: dict Nested sampling run dict (see the module docstring for more details). Only contains information in samples (not additional optional output key). """ samples = samples[np.argsort(samples[:, -2])] ns_run = {} ns_run['logl'] = samples[:, -2] ns_run['theta'] = samples[:, :-2] birth_contours = samples[:, -1] # birth_contours, ns_run['theta'] = check_logls_unique( # samples[:, -2], samples[:, -1], samples[:, :-2]) birth_inds = birth_inds_given_contours( birth_contours, ns_run['logl'], **kwargs) ns_run['thread_labels'] = threads_given_birth_inds(birth_inds) unique_threads = np.unique(ns_run['thread_labels']) assert np.array_equal(unique_threads, np.asarray(range(unique_threads.shape[0]))) # Work out nlive_array and thread_min_max logls from thread labels and # birth contours thread_min_max = np.zeros((unique_threads.shape[0], 2)) # NB delta_nlive indexes are offset from points' indexes by 1 as we need an # element to represent the initial sampling of live points before any dead # points are created. # I.E. birth on step 1 corresponds to replacing dead point zero delta_nlive = np.zeros(samples.shape[0] + 1) for label in unique_threads: thread_inds = np.where(ns_run['thread_labels'] == label)[0] # Max is final logl in thread thread_min_max[label, 1] = ns_run['logl'][thread_inds[-1]] thread_start_birth_ind = birth_inds[thread_inds[0]] # delta nlive indexes are +1 from logl indexes to allow for initial # nlive (before first dead point) delta_nlive[thread_inds[-1] + 1] -= 1 if thread_start_birth_ind == birth_inds[0]: # thread minimum is -inf as it starts by sampling from whole prior thread_min_max[label, 0] = -np.inf delta_nlive[0] += 1 else: assert thread_start_birth_ind >= 0 thread_min_max[label, 0] = ns_run['logl'][thread_start_birth_ind] delta_nlive[thread_start_birth_ind + 1] += 1 ns_run['thread_min_max'] = thread_min_max ns_run['nlive_array'] = np.cumsum(delta_nlive)[:-1] return ns_run def birth_inds_given_contours(birth_logl_arr, logl_arr, **kwargs): """Maps the iso-likelihood contours on which points were born to the index of the dead point on this contour. MultiNest and PolyChord use different values to identify the inital live points which were sampled from the whole prior (PolyChord uses -1e+30 and MultiNest -0.179769313486231571E+309). However in each case the first dead point must have been sampled from the whole prior, so for either package we can use init_birth = birth_logl_arr[0] If there are many points with the same logl_arr and dup_assert is False, these points are randomly assigned an order (to ensure results are consistent, random seeding is used). Parameters ---------- logl_arr: 1d numpy array logl values of each point. birth_logl_arr: 1d numpy array Birth contours - i.e. logl values of the iso-likelihood contour from within each point was sampled (on which it was born). dup_assert: bool, optional See ns_run_utils.check_ns_run_logls docstring. dup_warn: bool, optional See ns_run_utils.check_ns_run_logls docstring. Returns ------- birth_inds: 1d numpy array of ints Step at which each element of logl_arr was sampled. Points sampled from the whole prior are assigned value -1. """ dup_assert = kwargs.pop('dup_assert', False) dup_warn = kwargs.pop('dup_warn', False) if kwargs: raise TypeError('Unexpected **kwargs: {0}'.format(kwargs)) assert logl_arr.ndim == 1, logl_arr.ndim assert birth_logl_arr.ndim == 1, birth_logl_arr.ndim # Check for duplicate logl values (if specified by dup_assert or dup_warn) nestcheck.ns_run_utils.check_ns_run_logls( {'logl': logl_arr}, dup_assert=dup_assert, dup_warn=dup_warn) # Random seed so results are consistent if there are duplicate logls state = np.random.get_state() # Save random state before seeding np.random.seed(0) # Calculate birth inds init_birth = birth_logl_arr[0] assert np.all(birth_logl_arr <= logl_arr), ( logl_arr[birth_logl_arr > logl_arr]) birth_inds = np.full(birth_logl_arr.shape, np.nan) birth_inds[birth_logl_arr == init_birth] = -1 for i, birth_logl in enumerate(birth_logl_arr): if not np.isnan(birth_inds[i]): # birth ind has already been assigned continue dup_deaths = np.where(logl_arr == birth_logl)[0] if dup_deaths.shape == (1,): # death index is unique birth_inds[i] = dup_deaths[0] continue # The remainder of this loop deals with the case that multiple points # have the same logl value (=birth_logl). This can occur due to limited # precision, or for likelihoods with contant regions. In this case we # randomly assign the duplicates birth steps in a manner # that provides a valid division into nested sampling runs dup_births = np.where(birth_logl_arr == birth_logl)[0] assert dup_deaths.shape[0] > 1, dup_deaths if np.all(birth_logl_arr[dup_deaths] != birth_logl): # If no points both are born and die on this contour, we can just # randomly assign an order np.random.shuffle(dup_deaths) inds_to_use = dup_deaths else: # If some points are both born and die on the contour, we need to # take care that the assigned birth inds do not result in some # points dying before they are born try: inds_to_use = sample_less_than_condition( dup_deaths, dup_births) except ValueError: raise ValueError(( 'There is no way to allocate indexes dup_deaths={} such ' 'that each is less than dup_births={}.').format( dup_deaths, dup_births)) try: # Add our selected inds_to_use values to the birth_inds array # Note that dup_deaths (and hence inds to use) may have more # members than dup_births, because one of the duplicates may be # the final point in a thread. We therefore include only the first # dup_births.shape[0] elements birth_inds[dup_births] = inds_to_use[:dup_births.shape[0]] except ValueError: warnings.warn(( 'for logl={}, the number of points born (indexes=' '{}) is bigger than the number of points dying ' '(indexes={}). This indicates a problem with your ' 'nested sampling software - it may be caused by ' 'a bug in PolyChord which was fixed in PolyChord ' 'v1.14, so try upgrading. I will try to give an ' 'approximate allocation of threads but this may ' 'fail.').format( birth_logl, dup_births, inds_to_use), UserWarning) extra_inds = np.random.choice( inds_to_use, size=dup_births.shape[0] - inds_to_use.shape[0]) inds_to_use = np.concatenate((inds_to_use, extra_inds)) np.random.shuffle(inds_to_use) birth_inds[dup_births] = inds_to_use[:dup_births.shape[0]] assert np.all(~np.isnan(birth_inds)), np.isnan(birth_inds).sum() np.random.set_state(state) # Reset random state return birth_inds.astype(int) def sample_less_than_condition(choices_in, condition): """Creates a random sample from choices without replacement, subject to the condition that each element of the output is greater than the corresponding element of the condition array. condition should be in ascending order. """ output = np.zeros(min(condition.shape[0], choices_in.shape[0])) choices = copy.deepcopy(choices_in) for i, _ in enumerate(output): # randomly select one of the choices which meets condition avail_inds = np.where(choices < condition[i])[0] selected_ind = np.random.choice(avail_inds) output[i] = choices[selected_ind] # remove the chosen value choices = np.delete(choices, selected_ind) return output def threads_given_birth_inds(birth_inds): """Divides a nested sampling run into threads, using info on the indexes at which points were sampled. See "Sampling errors in nested sampling parameter estimation" (Higson et al. 2018) for more information. Parameters ---------- birth_inds: 1d numpy array Indexes of the iso-likelihood contours from within which each point was sampled ("born"). Returns ------- thread_labels: 1d numpy array of ints labels of the thread each point belongs to. """ unique, counts = np.unique(birth_inds, return_counts=True) # First get a list of all the indexes on which threads start and their # counts. This is every point initially sampled from the prior, plus any # indexes where more than one point is sampled. thread_start_inds = np.concatenate(( unique[:1], unique[1:][counts[1:] > 1])) thread_start_counts = np.concatenate(( counts[:1], counts[1:][counts[1:] > 1] - 1)) thread_labels = np.full(birth_inds.shape, np.nan) thread_num = 0 for nmulti, multi in enumerate(thread_start_inds): for i, start_ind in enumerate(np.where(birth_inds == multi)[0]): # unless nmulti=0 the first point born on the contour (i=0) is # already assigned to a thread if i != 0 or nmulti == 0: # check point has not already been assigned assert np.isnan(thread_labels[start_ind]) thread_labels[start_ind] = thread_num # find the point which replaced it next_ind = np.where(birth_inds == start_ind)[0] while next_ind.shape != (0,): # check point has not already been assigned assert np.isnan(thread_labels[next_ind[0]]) thread_labels[next_ind[0]] = thread_num # find the point which replaced it next_ind = np.where(birth_inds == next_ind[0])[0] thread_num += 1 if not np.all(~np.isnan(thread_labels)): warnings.warn(( '{} points (out of a total of {}) were not given a thread label! ' 'This is likely due to small numerical errors in your nested ' 'sampling software while running the calculation or writing the ' 'input files. ' 'I will try to give an approximate answer by randomly assigning ' 'these points to threads.' '\nIndexes without labels are {}' '\nIndexes on which threads start are {} with {} threads ' 'starting on each.').format( (np.isnan(thread_labels)).sum(), birth_inds.shape[0], np.where(np.isnan(thread_labels))[0], thread_start_inds, thread_start_counts)) inds = np.where(np.isnan(thread_labels))[0] state = np.random.get_state() # Save random state before seeding np.random.seed(0) # make thread decomposition is reproducible for ind in inds: # Get the set of threads with members both before and after ind to # ensure we don't change nlive_array by extending a thread labels_to_choose = np.intersect1d( # N.B. this removes nans too thread_labels[:ind], thread_labels[ind + 1:]) if labels_to_choose.shape[0] == 0: # In edge case that there is no intersection, just randomly # select from non-nan thread labels labels_to_choose = np.unique( thread_labels[~np.isnan(thread_labels)]) thread_labels[ind] = np.random.choice(labels_to_choose) np.random.set_state(state) # Reset random state assert np.all(~np.isnan(thread_labels)), ( '{} points still do not have thread labels'.format( (np.isnan(thread_labels)).sum())) assert np.array_equal(thread_labels, thread_labels.astype(int)), ( 'Thread labels should all be ints!') thread_labels = thread_labels.astype(int) # Check unique thread labels are a sequence from 0 to nthreads-1 assert np.array_equal( np.unique(thread_labels), np.asarray(range(sum(thread_start_counts)))), ( str(np.unique(thread_labels)) + ' is not equal to range(' + str(sum(thread_start_counts)) + ')') return thread_labels
true
52bd433032e7683329c6d7c1bb8d00bbb0374d86
Python
ryanmao725/FireMaze
/submit/Code1_eef45_rym15/Maze.py
UTF-8
28,987
4.0625
4
[]
no_license
import random import math # Math functions import time # Time function to test our algorithm speeds import copy # Allows us to deep copy a 2D array from collections import deque # Importing a simple queue since pop(0) on a list is O(n) time where n is the size of the list import heapq # Importing functions to treat lists as heaps/prioirty queues # These offsets allow us to define all squares that potentially can be reached from a 'current' square nearby_offsets = [(-1, 0), (0, 1), (1, 0), (0, -1)] #========================================# # Some helper functions def is_valid(square: tuple, n: int): """ Determines whether or not a given square is within the maze square matrix """ square_i, square_j = square if (square_i < n and square_i >= 0 and square_j < n and square_j >= 0): return True return False def euclidean_distance(square_one: tuple, square_two: tuple): """ Find the euclidean distance between two squares """ return math.sqrt((square_one[0] - square_two[0]) ** 2 + (square_one[1] - square_two[1]) ** 2) def search_time(search_algo, maze_size: int = 2): """ Returns the search time it takes for a given algorithm to find a valid path for a given maze size. search_algo - the search algorithm returns - the time taken for a maze (that has a valid path) """ while (True): # print("Trying...") start_time = time.time() # Define start time as current time result = search_algo(gen_maze(maze_size, 0.3), (0, 0), (maze_size - 1, maze_size - 1)) # Run algo end_time = time.time() # Define end time as current time try: result_iter = iter(result) # Checks whether or not the return is a tuple or just a single value except TypeError: if (result): # If there was a path return end_time - start_time else: if (result[0]): # If there was a path return end_time - start_time def print_maze(maze: list): """ Prints our maze in 2D format for readability maze - a square 2D array """ n = len(maze) for i in range(n): print(maze[i]) #========================================# def gen_maze(dim, p): """Generate a maze with a given dimension and obstacle density p""" maze = [] for i in range(dim): maze.append([]) for j in range(dim): if(random.uniform(0, 1) < p): maze[i].append(1) else: maze[i].append(0) maze[0][0] = 0 maze[dim - 1][dim - 1] = 0 return maze def gen_fire_maze(maze): """Generate a maze with one empty cell on fire""" maze_f = copy.deepcopy(maze) dim = len(maze) num_empty = 0 # count the number of empty cells in the maze for i in maze_f: num_empty += (dim-sum(i)) # chose an empty cell to set on fire fire_spawn = random.randrange(num_empty) # iterate over chosen number of empty cells before setting one on fire for i in range(dim): for j in range(dim): if(maze_f[i][j] == 0 and fire_spawn == 0): maze_f[i][j] = 2 # set cell to be on fire return (maze_f, (i, j)) elif(maze_f[i][j] == 0): fire_spawn -= 1 # decrement counter # function should always return before loop is completed return -1 def advance_fire_one_step(maze, q): """ Spread fire through maze using the following criteria 1. cells on fire stay on fire 2. empty cells with no adjacent cells on fire stay empty 3. blocked cells cannot be set on fire 4. empty cells with k adjacent cells on fire are set on fire with probability 1-(1-q)^k """ n = len(maze) # get dimension of maze next_maze = copy.deepcopy(maze) # create a copy of previous maze # iterate over all cells in the maze for i in range(n): for j in range(n): # check if cell is empty if(next_maze[i][j] == 0): k = 0 # count number of adjacent cells that are on fire for x in range(len(nearby_offsets)): offset_i, offset_j = nearby_offsets[x] possible = (i + offset_i, j + offset_j) if(is_valid(possible, n) and next_maze[possible[0]][possible[1]] == 2): k += 1 # use random variable to determine whether cells should be set on fire if(random.uniform(0, 1) < 1-((1-q) ** k)): # represent cell to be set on fire differently than fire cell to avoid affecting future calculations next_maze[i][j] = 3 # iterate over all cells in the maze for i in range(n): for j in range(n): # if cell should be set on fire, set it on fire if(next_maze[i][j] == 3): next_maze[i][j] = 2 # return maze with fire advanced on step return next_maze def advance_fire_probability(maze, q): """ Calculates probabilities of fire spreading to cells in next step 1. cells on fire stay on fire 2. empty cells with no adjacent cells on fire stay empty 3. blocked cells cannot be set on fire 4. empty cells with k adjacent cells on fire are set to their probability value 1-(1-q)^k """ n = len(maze) # get dimension of maze next_maze = copy.deepcopy(maze) # create a copy of previous maze # iterate over all cells in the maze for i in range(n): for j in range(n): # check if cell is empty if(next_maze[i][j] == 0): k = 0 # count number of adjacent cells that are on fire for x in range(len(nearby_offsets)): offset_i, offset_j = nearby_offsets[x] possible = (i + offset_i, j + offset_j) if(is_valid(possible, n) and next_maze[possible[0]][possible[1]] == 2): k += 1 #set value to probability maze will be set on fire in the next step next_maze[i][j] = 1-((1-q) ** k) # return maze with fire advanced on step return next_maze def reachable(maze: list, start: tuple, goal: tuple): """ Determines whether or not there exists a path between the start square and the goal square. maze - a square 2D array start - an ordered pair of the indices representing the start square goal - an ordered pair of the indices representing the goal square """ n = len(maze) # Get the dimension of the maze #========================================# # Some data checking statements if (not is_valid(start, n)): print("reachable: Start indices outside maze dimensions") return False elif (not is_valid(goal, n)): print("reachable: Goal indices outside maze dimensions") return False # End data checking statements #========================================# # We can use a copy of the maze to keep track of visited squares (Considered using a set here, thought that time efficiency was important) visited = copy.deepcopy(maze) # visited = list(map(list, maze)) # Alternative to using copy.deepcopy stack = [] # Define our stack of "fringe" squares stack.append(start) # Push the start square onto our stack visited[start[0]][start[1]] = 1 # Set our start to visited while (len(stack)): # While there exists items in the stack current = stack.pop() # Pop the last element if (current == goal): return True # If current is the goal, we found it! current_i, current_j = current # Unpack the current pair # Now we want to add all unvisited squares that are possible to get to from the current square for i in range(len(nearby_offsets)): offset_i, offset_j = nearby_offsets[i] possible = (current_i + offset_i, current_j + offset_j) # print(f"Current possible: {possible_i} {possible_j}") # DEBUG if (is_valid(possible, n)): # If the calculated square is within the maze matrix if (not visited[possible[0]][possible[1]]): stack.append(possible) visited[possible[0]][possible[1]] = 1 return False # If the while loop goes out, and the stack is empty, then there is no possible path def BFS(maze: list, start: tuple, goal: tuple): """ Determines the shortest path (if it exists) between a start square and an end square using BFS (dijkstra's). maze - a square 2D array start - an ordered pair of the indices representing the start square goal - an ordered pair of the indices representing the goal square returns - an ordered triple, with the first element either True or False, representing whether or not it is possible to form a path. The second element is a list of ordered pairs representing (one of) the shortest path(s). The third element is the number of nodes visited. """ n = len(maze) # Get the dimension of the maze #========================================# # Some data checking statements if (not is_valid(start, n)): print("BFS: Start indices outside maze dimensions") return False elif (not is_valid(goal, n)): print("BFS: Goal indices outside maze dimensions") return False # End data checking statements #========================================# number_of_nodes_visited = 0 visited = copy.deepcopy(maze) # We can use a copy of the maze to keep track of visited squares (Considered using a set here, thought that time efficiency was important) # visited = list(map(list, maze)) # Alternative to using copy.deepcopy # Initialize a matrix of the same size as maze where each value is None. previous = [[None for i in range(n)] for j in range(n)] queue = deque() # Define our queue of "fringe" squares queue.append(start) # Push the start square into our queue visited[start[0]][start[1]] = 1 # Set our start to visited while (len(queue)): # While there exists items in the queue current = queue.popleft() # Pop the square at index 0 number_of_nodes_visited += 1 # Increase number of nodes visited if (current == goal): # If current is the goal, we found it! # We now want to traverse back to make a path using our 'previous' matrix path = [] while (current != None): path.append(current) current = previous[current[0]][current[1]] path.reverse() return (True, path, number_of_nodes_visited) current_i, current_j = current # Unpack the current pair # Now we want to add all unvisited squares that are possible to get to from the current square for i in range(len(nearby_offsets)): offset_i, offset_j = nearby_offsets[i] possible = (current_i + offset_i, current_j + offset_j) # print(f"Current possible: {possible_i} {possible_j}") # DEBUG if (is_valid(possible, n)): # If the calculated square is within the maze matrix # If possible has not been visited yet if (not visited[possible[0]][possible[1]]): queue.append(possible) # Add possible to our queue # Set possible to visited visited[possible[0]][possible[1]] = 1 # Set the previous square for possible to the current square previous[possible[0]][possible[1]] = current # If the while loop goes out, and the queue is empty, then there is no possible path return (False, [], number_of_nodes_visited) def fire_strategy_1(maze, q): """ Calculate the shortest path through a fire maze before any fire has spread Progress agent through maze as fire spreads Return false if agent touches fire cell on path Returns true otherwise """ n = len(maze) path = BFS(maze, (0, 0), (n-1, n-1)) # End if no path exists from start to goal if(not path[0]): return False route = path[1] timestep = 0 agent_pos = route[timestep] maze_f = copy.deepcopy(maze) while(timestep < len(route)): timestep += 1 # increase timer by 1 agent_pos = route[timestep] # update to new position # if agent moves into fire, report failure if(maze_f[agent_pos[0]][agent_pos[1]] != 0): # print_maze(maze_f) #print("timestep ", timestep) return False # if agent has reached goal, report success if(timestep == len(route)-1): # print_maze(maze_f) #print("timestep ", timestep) return True maze_f = advance_fire_one_step(maze_f, q) # advance fire # if fire spread into agent, report failure if(maze_f[agent_pos[0]][agent_pos[1]] != 0): # print_maze(maze_f) #print("timestep ", timestep) return False # function should always return before while loop is completed return False def fire_strategy_2(maze, q): """ Recalculate the shortest path through the fire at each timestep Return false if agent touches fire cell on path Returns true otherwise """ n = len(maze) timestep = 0 maze_f = copy.deepcopy(maze) agent_pos = (0, 0) while(agent_pos != (n-1, n-1)): path = BFS(maze_f, agent_pos, (n-1, n-1)) # End if no path exists from start to goal if(not path[0]): return False route = path[1] timestep += 1 # increase timer by 1 agent_pos = route[1] # update to new position # if agent moves into fire, report failure if(maze_f[agent_pos[0]][agent_pos[1]] != 0): return False # if agent has reached goal, report success if(agent_pos == (n-1, n-1)): return True maze_f = advance_fire_one_step(maze_f, q) # advance fire # if fire spread into agent, report failure if(maze_f[agent_pos[0]][agent_pos[1]] != 0): return False # function should always return before while loop is completed return False def fire_strategy_3(maze, q, alpha): """ Recalculate the shortest path through the fire at each timestep Return false if agent touches fire cell on path Returns true otherwise alpha - parameter for how adverse agent is to moving into a cell with probability of setting on fire """ n = len(maze) timestep = 0 maze_f = copy.deepcopy(maze) agent_pos = (0, 0) fire_start = (0,0) while(agent_pos != (n-1, n-1)): #call modified AStar to avoid future spread of the fire path = AStar_Modified(maze_f, agent_pos, (n-1, n-1), alpha, q, fire_start) # End if no path exists from start to goal if(not path[0]): return False route = path[1] timestep += 1 # increase timer by 1 agent_pos = route[1] # update to new position # if agent moves into fire, report failure if(maze_f[agent_pos[0]][agent_pos[1]] != 0): return False # if agent has reached goal, report success if(agent_pos == (n-1, n-1)): return True maze_f = advance_fire_one_step(maze_f, q) # advance fire # if fire spread into agent, report failure if(maze_f[agent_pos[0]][agent_pos[1]] != 0): return False # function should always return before while loop is completed return False def AStar(maze: list, start: tuple, goal: tuple): """ Determines the shortest path (if it exists) between a start square and an end square using A* algorithm. maze - a square 2D array start - an ordered pair of the indices representing the start square goal - an ordered pair of the indices representing the goal square returns - an ordered triple, with the first element either True or False, representing whether or not it is possible to form a path. The second element is a list of ordered pairs representing (one of) the shortest path(s). The third element is the number of nodes visited. """ n = len(maze) # Get the dimension of the maze #========================================# # Some data checking statements if (not is_valid(start, n)): print("AStar: Start indices outside maze dimensions") return False elif (not is_valid(goal, n)): print("AStar: Goal indices outside maze dimensions") return False # End data checking statements #========================================# number_of_nodes_visited = 0 # We can use a simple visited matrix since the heuristic (euclidean distance) is both admissible AND consistent visited = copy.deepcopy(maze) # We can use a copy of the maze to keep track of visited squares (Considered using a set here, thought that time efficiency was important) # visited = list(map(list, maze)) # Alternative to using copy.deepcopy g_cost = [[float('inf') for i in range(n)] for j in range(n)] # Initialize a matrix of the same size as maze where each value is 'infinity'. # f_cost = [[float('inf') for i in range(n)] for j in range(n)] # Initialize a matrix of the same size as maze where each value is 'infinity'. previous = [[None for i in range(n)] for j in range(n)] # Initialize a matrix of the same size as maze where each value is None. heap = [] # Define our 'heap' which is just a list, but all pushes and pops will be through the heapq library. heapq.heappush(heap, (0, start)) # Push our start onto the heap. It's ok for this to have 0 'f' value since it'll be immediately popped off anyway. g_cost[start[0]][start[1]] = 0 # f_cost[start[0]][start[1]] = euclidean_distance(start, goal) while (len(heap)): # While there exists items in the queue min_value = heapq.heappop(heap) # Pop the square with lowest 'f' value from our heap. number_of_nodes_visited += 1 # Increase number of nodes visited # if (visited[current[0]][current[1]] == False): # If we have not visited this node # visited[start[0]][start[1]] = 1 # Set it to visited current_f, current = min_value if (current == goal): # If current is the goal, we found it! # We now want to traverse back to make a path using our 'previous' matrix path = [] while (current != None): path.append(current) current = previous[current[0]][current[1]] path.reverse() return (True, path, number_of_nodes_visited) current_i, current_j = current # Unpack the current pair # Now we want to add all unvisited squares that are possible to get to from the current square for i in range(len(nearby_offsets)): offset_i, offset_j = nearby_offsets[i] possible = (current_i + offset_i, current_j + offset_j) # print(f"Current possible: {possible_i} {possible_j}") # DEBUG if (is_valid(possible, n)): # If the calculated square is within the maze matrix if (maze[possible[0]][possible[1]]): # If there is something there continue # Check to see if this path is better (just need to check g_cost since h_cost is always the same) possible_g_cost = g_cost[current[0]][current[1]] + 1 if (possible_g_cost < g_cost[possible[0]][possible[1]]): # If the cost is indeed less previous[possible[0]][possible[1]] = current g_cost[possible[0]][possible[1]] = possible_g_cost # Check to see if the node is in the heap, and if it is not, put it in. if (not visited[possible[0]][possible[1]]): heapq.heappush(heap, (possible_g_cost + euclidean_distance(possible, goal), possible)) visited[possible[0]][possible[1]] = 1 # found = False # for (f_cost, (square_i, square_j)) in heap: # if (square_i == possible[0] and square_j == possible[1]): # found = True # break # if (not found): # heapq.heappush(heap, (possible_g_cost + euclidean_distance(possible, goal), possible)) # if (visited[possible[0]][possible[1]]): # If this node has already been visited # # Check to see if this path is better (just need to check g_cost since h_cost is always the same) # if (f_cost[possible[0]][possible[1]] > possible_f_cost): # heapq.heappush(heap, (possible_f_cost, possible)) # Push this back onto the heap for re-examination # f_cost[possible[0]][possible[1]] = possible_f_cost # Assign the new f-cost # previous[possible[0]][possible[1]] = current # Update previous # else return (False, [], number_of_nodes_visited) # If the while loop goes out, and the queue is empty, then there is no possible path def AStar_Modified(maze: list, start: tuple, goal: tuple, alpha: float, q: float, fire_start: tuple): """ Determines the shortest path (if it exists) between a start square and an end square using A* algorithm where the cost to traverse from one square to another is increased by a value proportional to the likelyhood of fire spreading there in the next step maze - a square 2D array start - an ordered pair of the indices representing the start square goal - an ordered pair of the indices representing the goal square alpha - parameter for how adverse agent is to moving into a cell with probability of setting on fire q - parameter for how quickly the fire spreads returns - an ordered triple, with the first element either True or False, representing whether or not it is possible to form a path. The second element is a list of ordered pairs representing (one of) the shortest path(s). The third element is the number of nodes visited. """ n = len(maze) # Get the dimension of the maze #========================================# # Some data checking statements if (not is_valid(start, n)): print("AStar_Modified: Start indices outside maze dimensions") return False elif (not is_valid(goal, n)): print("AStar_Modified: Goal indices outside maze dimensions") return False # End data checking statements #========================================# number_of_nodes_visited = 0 # We can use a simple visited matrix since the heuristic (euclidean distance) is both admissible AND consistent visited = copy.deepcopy(maze) # We can use a copy of the maze to keep track of visited squares (Considered using a set here, thought that time efficiency was important) # visited = list(map(list, maze)) # Alternative to using copy.deepcopy g_cost = [[float('inf') for i in range(n)] for j in range(n)] # Initialize a matrix of the same size as maze where each value is 'infinity'. # f_cost = [[float('inf') for i in range(n)] for j in range(n)] # Initialize a matrix of the same size as maze where each value is 'infinity'. previous = [[None for i in range(n)] for j in range(n)] # Initialize a matrix of the same size as maze where each value is None. maze_future = copy.deepcopy(maze) #create maze that stores probabilities of where fire will be in next step maze_future = advance_fire_probability(maze_future,q) #calculate future probabilities heap = [] # Define our 'heap' which is just a list, but all pushes and pops will be through the heapq library. heapq.heappush(heap, (0, start)) # Push our start onto the heap. It's ok for this to have 0 'f' value since it'll be immediately popped off anyway. g_cost[start[0]][start[1]] = 0 # f_cost[start[0]][start[1]] = euclidean_distance(start, goal) while (len(heap)): # While there exists items in the queue min_value = heapq.heappop(heap) # Pop the square with lowest 'f' value from our heap. number_of_nodes_visited += 1 # Increase number of nodes visited # if (visited[current[0]][current[1]] == False): # If we have not visited this node # visited[start[0]][start[1]] = 1 # Set it to visited current_f, current = min_value if (current == goal): # If current is the goal, we found it! # We now want to traverse back to make a path using our 'previous' matrix path = [] while (current != None): path.append(current) current = previous[current[0]][current[1]] path.reverse() return (True, path, number_of_nodes_visited) current_i, current_j = current # Unpack the current pair # Now we want to add all unvisited squares that are possible to get to from the current square for i in range(len(nearby_offsets)): offset_i, offset_j = nearby_offsets[i] possible = (current_i + offset_i, current_j + offset_j) # print(f"Current possible: {possible_i} {possible_j}") # DEBUG if (is_valid(possible, n)): # If the calculated square is within the maze matrix if (maze[possible[0]][possible[1]]): # If there is something there continue # Check to see if this path is better (just need to check g_cost since h_cost is always the same) possible_g_cost = g_cost[current[0]][current[1]] + 1 #KEY MODIFICATION: Increase cost of moving to a node if there is a probability it will be on fire next turn possible_g_cost += alpha*maze_future[possible[0]][possible[1]] if (possible_g_cost < g_cost[possible[0]][possible[1]]): # If the cost is indeed less previous[possible[0]][possible[1]] = current g_cost[possible[0]][possible[1]] = possible_g_cost # Check to see if the node is in the heap, and if it is not, put it in. if (not visited[possible[0]][possible[1]]): heapq.heappush(heap, (possible_g_cost + euclidean_distance(possible, goal), possible)) visited[possible[0]][possible[1]] = 1 # found = False # for (f_cost, (square_i, square_j)) in heap: # if (square_i == possible[0] and square_j == possible[1]): # found = True # break # if (not found): # heapq.heappush(heap, (possible_g_cost + euclidean_distance(possible, goal), possible)) # if (visited[possible[0]][possible[1]]): # If this node has already been visited # # Check to see if this path is better (just need to check g_cost since h_cost is always the same) # if (f_cost[possible[0]][possible[1]] > possible_f_cost): # heapq.heappush(heap, (possible_f_cost, possible)) # Push this back onto the heap for re-examination # f_cost[possible[0]][possible[1]] = possible_f_cost # Assign the new f-cost # previous[possible[0]][possible[1]] = current # Update previous # else return (False, [], number_of_nodes_visited) # If the while loop goes out, and the queue is empty, then there is no possible path if __name__ == "__main__": """Testing the functions""" # n = 999 # maze = gen_maze(n + 1, 0.3) # print(maze) # print_maze(maze) # print(reachable(maze, (0, 0), (n, n))) # BFS_blah, BFS_result, BFS_number_of_nodes_visited = BFS(maze, (0, 0), (n, n)) # AStar_blah, AStar_result, AStar_number_of_nodes_visited = AStar(maze, (0, 0), (n, n)) # print(search_time(AStar, 2750)) # maze = gen_maze(200,0.3) # maze_f = gen_fire_maze(maze) # # print_maze(maze_f) # c1 = 0 # c2 = 0 # c3 = 0 # print('####') # for i in range(3000): # maze = gen_maze(15,0.3) # maze_f = gen_fire_maze(maze) # if(fire_strategy_1(maze_f,0.5)): # c1 +=1 # if(fire_strategy_2(maze_f,0.5)): # c2 +=1 # if(fire_strategy_3(maze_f,0.5,1)): # c3 +=1 # print(c1, c2, c3)
true
2172952ef0a46a4d5a5a1764637d84663975bec4
Python
afcarl/uct_atari
/agents.py
UTF-8
5,592
2.59375
3
[]
no_license
import numpy as np from keras.models import load_model from lasagne_model import build_model from utils import make_state import cv2 from collections import deque from keras.objectives import categorical_crossentropy import cPickle class BaseAgent(object): def __init__(self, n_actions, seed=None, not_sample=False): self.n_actions = n_actions self.rng = np.random.RandomState(seed) self.not_sample = not_sample def get_probs(self, frame): raise NotImplementedError def choose_action(self, frame, sample=True): probs = self.get_probs(frame) if self.not_sample: sample = False if sample: return self.rng.multinomial(1, probs-np.finfo(np.float32).epsneg).argmax() else: return probs.argmax() def seed(self, seed): self.rng.seed(seed) def reset(self): pass class RandomAgent(BaseAgent): """ Agent that chooses action randomly """ def __init__(self, n_actions): super(RandomAgent, self).__init__(n_actions) def get_probs(self, frame): return np.asarray([1./self.n_actions]*self.n_actions) def choose_action(self, frame, sample=True): return self.rng.randint(self.n_actions) class KerasAgent(BaseAgent): """Agent that uses keras model to predict action""" def __init__(self, model_path, flip_map=None, gray_state=True, **kwargs): # load model model = load_model( model_path, custom_objects={'loss_fn': categorical_crossentropy} ) if flip_map is not None: assert model.output_shape[1] == len(flip_map) super(KerasAgent, self).__init__(n_actions=model.output_shape[1], **kwargs) self.gray_state = gray_state if len(model.input_shape) == 5: self.n_frames = model.input_shape[2] self.rnn = True else: self.n_frames = model.input_shape[1] self.rnn = False if not gray_state: self.n_frames /= 3 self.height, self.width = model.input_shape[2:] self.model = model self.flip_map = flip_map self.reset() def reset(self): self.model.reset_states() self.buf = deque(maxlen=self.n_frames) def get_probs(self, frame): if self.flip_map: frame = cv2.flip(frame, 1) s = make_state(frame, self.buf, self.height, self.width, make_gray=self.gray_state) if self.rnn: probs = self.model.predict(np.asarray([s]))[0][0] else: probs = self.model.predict(s)[0] if self.flip_map: return probs[self.flip_map] return probs class LasagneAgent(BaseAgent): def __init__(self, model_path, observation_shape=(4, 84, 84), flip_map=None, **kwargs): # read weights with open(model_path, 'rb') as f: weights = cPickle.load(f) # build model and set weights n_actions = weights[-1].shape[-1] _, prob_fn, _, params = build_model(observation_shape, n_actions) for p, w in zip(params, weights): p.set_value(w) super(LasagneAgent, self).__init__(n_actions=n_actions, **kwargs) self.n_frames = observation_shape[0] self.height, self.width = observation_shape[-2:] self.flip_map = flip_map self.probs = prob_fn self.reset() def reset(self): self.buf = deque(maxlen=self.n_frames) def get_probs(self, frame): if self.flip_map: frame = cv2.flip(frame, 1) s = make_state(frame, self.buf, self.height, self.width, make_gray=True, average='cv2') probs = self.probs(s)[0] if self.flip_map: return probs[self.flip_map] return probs class EnsebleAgent(BaseAgent): """Agent that sample action randomly from other provided agents""" def __init__(self, agents, ensemble_mode='mean', weights=None, **kwargs): if weights is None: weights = [1./len(agents)]*len(agents) assert sum(weights) == 1 assert ensemble_mode in ('mean', 'sample_soft', 'sample_hard') super(EnsebleAgent, self).__init__(agents[0].n_actions, **kwargs) self.agents = agents self.weights = np.asarray(weights) self.ensemble_mode = ensemble_mode def get_probs(self, frame): probs_all = [agent.get_probs(frame) for agent in self.agents] return self.weights.dot(probs_all) def choose_action(self, frame, sample=True): # first get probs for all agents and then sample/argmax if self.ensemble_mode == 'mean': probs = self.get_probs(frame) if self.not_sample: sample = False if sample: return self.rng.multinomial(1, probs - np.finfo(np.float32).epsneg).argmax() else: return probs.argmax() # first get action for all agents then sample else: actions = [agent.choose_action(frame, sample) for agent in self.agents] if self.ensemble_mode == 'sample_soft': a_idx = self.rng.multinomial(len(actions), self.weights).argmax() return actions[a_idx] elif self.ensemble_mode == 'sample_hard': return self.rng.choice(actions) def reset(self): for agent in self.agents: agent.reset() def seed(self, seed): self.rng.seed(seed) for agent in self.agents: agent.seed(seed)
true
31a8e5477e67a0dce340298786ca799938f635bc
Python
MatthewKosloski/starting-out-with-python
/homework/line_numbers/line_numbers.py
UTF-8
407
4.0625
4
[]
no_license
# Matthew Kosloski # Exercise 6-3 # CPSC 3310-01 SP2018 def main(): filename = input('Name of the file: ') try: infile = open(filename, 'r') result = '' current_line = 1 for line in infile: result += f'{current_line}: {line}' current_line += 1 infile.close() except IOError: print(f'Failed to read file {filename}. :(') else: print(f'Contents of {filename}:\n') print(result) main()
true
2174f9e1b58ee3559ac3b944a9a31812fa151f6f
Python
burtawicz/N-Body-Simulation
/Test.py
UTF-8
3,265
3.265625
3
[]
no_license
from vector.Vector2D import Vector2D from vector.Vector3D import Vector3D from body.Body import Body def main(): #vector_test() body_test() def vector_test(): # vec1 = Vector2D(1.0, 5.5) # vec2 = Vector2D(6.6, 12.0) # #print(f'x = {vec1.x}\ny = {vec1.y}') # vec1.add(vec2) # #print(f'\nx = {vec1.x}\ny = {vec1.y}') # #print(f"\nDistance between: {vec1.get_distance_between(vec2)}") # vec3 = Vector3D(1.0, 5.5, 5.6) # vec4 = Vector3D(6.6, 12.0, 6.8) # vec5 = vec3.get_difference_vector(vec4) # print(f'x = {vec5.x}\ny = {vec5.y}\nz = {vec5.z}') # vec3.add(vec4) # #print(f'\nx = {vec3.x}\ny = {vec3.y}\nz = {vec3.z}') # #print(f"\nDistance between: {vec3.get_distance_between(vec4)}") pass def body_test(): bodies = [] bodies.append(Body("Sun", mass=1.989e30, position_vector=Vector2D(0.0, 0.0), velocity_vector=Vector2D(), acceleration_vector=Vector2D())) bodies.append(Body("Earth", mass=5.972e24, position_vector=Vector2D(1.49e8, 1.49e8), velocity_vector=Vector2D(108000.0, 0.0), acceleration_vector=Vector2D())) bodies.append(Body("Jupiter", mass=1.898e27, position_vector=Vector2D(8.166e8, 8.166e8), velocity_vector=Vector2D(105249.6, 0.0), acceleration_vector=Vector2D())) # print(f"\nThe distance between {bodies[0].name} and {bodies[1].name} is {bodies[0].get_distance_between(bodies[1].position)}.") # temp_acceleration = bodies[0].calculate_acceleration(bodies, 0) # print("The acceleration vector will add the following to the x and y coordinates.") # print(f"\nx += {temp_acceleration.x:.1E}") # print(f"\ny += {temp_acceleration.y:.1E}\n") print("Start") print(f"\nname : {bodies[0].name}") print(f"Position: x={bodies[0].position.x:.3E} y={bodies[0].position.y:.3E}") print(f"\nname : {bodies[1].name}") print(f"Position: x={bodies[1].position.x:.3E} y={bodies[1].position.y:.3E}") print(f"\nname : {bodies[2].name}") print(f"Position: x={bodies[2].position.x:.3E} y={bodies[2].position.y:.3E}") for index, body in enumerate(bodies): body.calculate_velocity(bodies, index=index, time_step=1.0) for body in bodies: body.update_position() print("First Iter") print(f"\nname : {bodies[0].name}") print(f"Position: x={bodies[0].position.x:.3E} y={bodies[0].position.y:.3E}") print(f"\nname : {bodies[1].name}\n") print(f"Position: x={bodies[1].position.x:.3E} y={bodies[1].position.y:.3E}") print(f"\nname : {bodies[2].name}") print(f"Position: x={bodies[2].position.x:.3E} y={bodies[2].position.y:.3E}") for index, body in enumerate(bodies): body.calculate_velocity(bodies, index=index, time_step=1.0) for body in bodies: body.update_position() print("Second Iter") print(f"\nname : {bodies[0].name}") print(f"Position: x={bodies[0].position.x:.3E} y={bodies[0].position.y:.3E}") print(f"\nname : {bodies[1].name}") print(f"Position: x={bodies[1].position.x:.3E} y={bodies[1].position.y:.3E}") print(f"\nname : {bodies[2].name}") print(f"Position: x={bodies[2].position.x:.3E} y={bodies[2].position.y:.3E}") if __name__ == "__main__": main()
true
52a1de373d7a4e9b0d0aaede0e5e280907ceb188
Python
AK-1121/code_extraction
/python/python_6167.py
UTF-8
119
2.734375
3
[]
no_license
# Python: Map float range [0.0, 1.0] to color range [red, green]? your_value * (1/3 of the maximum H value, often 255)
true
dbf82c37f9b714fc4d1889e3318d2d48393f8e48
Python
thakurarindam/student-alcohol-consumption-eda
/modules/main_credit scores.py
UTF-8
1,781
2.6875
3
[]
no_license
import general_utils as Ugen import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model from sklearn.cross_validation import train_test_split from sklearn.metrics import r2_score #accuracy_score is same as model.score() #cd ~/Documents/Programming/Python/Data\ Analyst\ ND/UD201/modules #GET DATA df=pd.read_csv('../default of credit card clients.csv',skiprows=[0]) #SET INDEPENDENT VARS x_vars=['LIMIT_BAL','SEX','EDUCATION','MARRIAGE','AGE'] # x_vars=['PAY_2'] #INIT MODEL Y=df['default payment next month'].values # X=df[x_vars].values X=df.drop('default payment next month',axis=1) #include all vars as predictors logreg = linear_model.LogisticRegression() #SPLIT TRAIN/TEST DATA train_X,test_X,train_Y,test_Y=train_test_split(X,Y,test_size=0.1,random_state=42) #FIT MODEL logreg.fit(train_X, train_Y) ###CHECK MODEL RESULTS # print(logreg.get_params()) print('Accuracy score is: %s'% logreg.score(test_X,test_Y)) print('R2 score is: %s'% r2_score(train_Y,logreg.predict(train_X))) print('Coefficients are: %s'% logreg.coef_) # print(logreg.predict([120000,2,2,1,21])) #######NOTES TO SELF############# ##currently getting accruacy score of ~70% no matter what variables are added ##looking at data, 80% of Y's are 0, so if you just guessed 0 you'd be right about 80% of the time.. ##in other words, we have no improvement over the mean... ######DIAGNOSIS: imbalanced dataset....apparently a common problem...research methods for dealing with this! # http://machinelearningmastery.com/tactics-to-combat-imbalanced-classes-in-your-machine-learning-dataset/ ##update: I am getting negative R2 scores with the given linear, logistic model ##this means that the model performs worse than a horizontal line
true
aa0a254e0a6294595cc83560f90754aa537a406e
Python
minaessam2015/AndroidForVision
/label_image.py
UTF-8
6,145
2.5625
3
[]
no_license
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import numpy as np import tensorflow as tf import os def load_graph(model_file): graph = tf.Graph() graph_def = tf.GraphDef() with open(model_file, "rb") as f: graph_def.ParseFromString(f.read()) with graph.as_default(): tf.import_graph_def(graph_def) return graph def read_tensor_from_image_file(file_name, input_height=299, input_width=299, input_mean=0, input_std=255): input_name = "file_reader" output_name = "normalized" file_reader = tf.read_file(file_name, input_name) if file_name.endswith(".png"): image_reader = tf.image.decode_png( file_reader, channels=3, name="png_reader") elif file_name.endswith(".gif"): image_reader = tf.squeeze( tf.image.decode_gif(file_reader, name="gif_reader")) elif file_name.endswith(".bmp"): image_reader = tf.image.decode_bmp(file_reader, name="bmp_reader") else: image_reader = tf.image.decode_jpeg( file_reader, channels=3, name="jpeg_reader") float_caster = tf.cast(image_reader, tf.float32) dims_expander = tf.expand_dims(float_caster, 0) resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width]) normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std]) sess = tf.Session() result = sess.run(normalized) return result def load_labels(label_file): label = [] proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines() for l in proto_as_ascii_lines: label.append(l.rstrip()) return label def get_ground_truth_label(file_name): """ Maps the predicted index with the original file index original file name index prediction index ------------------------------------------------ #2ch 1 | 2ch 0 #3ch 2 | 3ch 1 #4ch 3 | 4ch 2 #basal 4 | apical 3 #mid 5 | basal 4 #apical 6 | mid 5 ---------------------------------------------------- Input: image basename Returns : the correct index according to file name """ index = int(file_name.split('_')[2])-1 data = [0,1,2,4,5,3] return data[index] if __name__ == "__main__": file_name = "tensorflow/examples/label_image/data/grace_hopper.jpg" model_file = \ "tensorflow/examples/label_image/data/inception_v3_2016_08_28_frozen.pb" label_file = "tensorflow/examples/label_image/data/imagenet_slim_labels.txt" input_height = 299 input_width = 299 input_mean = 0 input_std = 255 input_layer = "input" output_layer = "InceptionV3/Predictions/Reshape_1" parser = argparse.ArgumentParser() parser.add_argument("--image", help="image to be processed") parser.add_argument("--graph", help="graph/model to be executed") parser.add_argument("--labels", help="name of file containing labels") parser.add_argument("--input_height", type=int, help="input height") parser.add_argument("--input_width", type=int, help="input width") parser.add_argument("--input_mean", type=int, help="input mean") parser.add_argument("--input_std", type=int, help="input std") parser.add_argument("--input_layer", help="name of input layer") parser.add_argument("--output_layer", help="name of output layer") args = parser.parse_args() if args.graph: model_file = args.graph if args.image: file_name = args.image if args.labels: label_file = args.labels if args.input_height: input_height = args.input_height if args.input_width: input_width = args.input_width if args.input_mean: input_mean = args.input_mean if args.input_std: input_std = args.input_std if args.input_layer: input_layer = args.input_layer if args.output_layer: output_layer = args.output_layer graph = load_graph(model_file) input_name = "import/" + input_layer output_name = "import/" + output_layer input_operation = graph.get_operation_by_name(input_name) output_operation = graph.get_operation_by_name(output_name) directory = False files = [] labels = load_labels(label_file) failures = open('testing_failures.txt', 'w') failures.write( "Image Name prediction GroundTruth confidence\n") failures.write( "---------------------------------------------------------------------------------------------------------\n") if not file_name.endswith('.jpg'): directory = True if directory: files = [os.path.join(file_name,f) for f in os.listdir(file_name)] else: files = [file_name] labels = load_labels(label_file) print(files) counter = 0 line = "" for subdir in files: print(subdir) for image in os.listdir(subdir): file_name = os.path.join(subdir,image) print(file_name) counter+=1 t = read_tensor_from_image_file( file_name, input_height=input_height, input_width=input_width, input_mean=input_mean, input_std=input_std) with tf.Session(graph=graph) as sess: results = sess.run(output_operation.outputs[0], { input_operation.outputs[0]: t }) results = np.squeeze(results) top_index = np.argmax(results) line += file_name+ " "+labels[top_index]+" "+labels[get_ground_truth_label(os.path.basename(file_name))]+" "+str(results[top_index])+"\n" failures.write(line) failures.close() print("total images "+str(counter)) #2ch 1 2ch #3ch 2 3ch #4ch 3 4ch #basal 4 apical #mid 5 basal #apical 6 mid
true
619bdd3db1e380083f9de5886cbf41a89f326111
Python
Uche-Clare/python-challenge-solutions
/ObasiEmmanuel/Phase 1/Python Basic 1/Day 4 task/Question 2.py
UTF-8
52
2.515625
3
[ "MIT" ]
permissive
tolu=[1,2,3,4,5,5,6,7,7,6,7,6] print(tolu.count(4))
true
05e5c3bb19f658dbf3d7762cf3197d74e66c1332
Python
EmuRaha/MyPythonCodes
/project57.py
UTF-8
696
3.25
3
[]
no_license
# File Handling f = open("MyText","r") #print(f.read()) print(f.readlines()) print(f.readlines()) #print(f.readline()) #print(f.readline()) #print(f.readline()) #print(f.readline()) #print(f.readline()) f1 = open("MyFile","w") for i in f: f1.write(i) f1.write("This is my file. I want to write something.") f1 = open("MyFile","r") #print(f1.read()) print(f.readlines(1)) print(f.readlines()) #print(f.readline(3)) #print(f.readline()) #print(f.readline()) #print(f.readline()) #print(f.readline()) p1 = open('Emu.jpg','rb') p2 = open('MyPic.txt','wb') for line in p1: p2.write(line)
true
ec893ebf331a95974ddfd2b2b4ab84110d07b1fa
Python
gabriellaec/desoft-analise-exercicios
/backup/user_195/ch20_2019_03_01_14_13_18_652981.py
UTF-8
139
3.40625
3
[]
no_license
pergunta1=input("Olá, NOME") if pergunta1=="Chris": print ("Todo mundo odeia o Chris") else: print ("Olá,{0}".format(pergunta1))
true
7e2a233a9787fba534a72d7d6992f8cde4223124
Python
SHANA2029/PROGRAMMING-LAB_PYTHON
/CO1_12.py
UTF-8
122
3.5
4
[]
no_license
filename=input("input the Filname:") f_externs=filename.split(".") print("The extension of the file is: ",f_externs[-1])
true
acb631b09ffe9ffba93b1b67c7aee94fdd95d99b
Python
vash050/start_python
/lesson_7/shcherbatykh_vasiliy/z_1.py
UTF-8
3,511
3.859375
4
[]
no_license
# Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод __init__()), # который должен принимать данные (список списков) для формирования матрицы. # Подсказка: матрица — система некоторых математических величин, расположенных в виде прямоугольной схемы. # Следующий шаг — реализовать перегрузку метода __str__() для вывода матрицы в привычном виде. # Далее реализовать перегрузку метода __add__() для реализации операции сложения двух объектов класса Matrix # (двух матриц). Результатом сложения должна быть новая матрица. # Подсказка: сложение элементов матриц выполнять поэлементно — первый элемент первой строки первой матрицы складываем # с первым элементом первой строки второй матрицы и т.д. # Проверка учитывает не все варианты. Пытался сделать проверку через len(), не хватило времени разобраться first_matrix = [ [5, 2, 12], [12, 6, 1], [13, 9, 0] ] second_matrix = [ [2, 6, 20], [1, 9, 0], [8, 0, 2] ] third_matrix = [ [0, 6, 11], [61, 6, 0], [8, 0, 9] ] class Matrix: def __init__(self, one_matrix): self.any_matrix = one_matrix def __str__(self): str_matrix = '' for element in self.any_matrix: str_matrix += f'{element}\n' return str_matrix def __add__(self, other): # if self.check(other): try: sum_matrix = [] sum_str = [] counter_str = 0 for el in self.any_matrix: counter_value = 0 for value in el: sum_str.append(value + other.any_matrix[counter_str][counter_value]) counter_value += 1 sum_matrix.append(sum_str.copy()) sum_str.clear() counter_str += 1 return Matrix(sum_matrix) except Exception as e: print('Матрицы имеют разное количество строк или столбцов') # def check(self, other): # try: # check_list = [] # # if len(self.any_matrix) == len(other): # count_for_check = 0 # for el in self.any_matrix: # if len(el) == len(other[count_for_check]): # check_list.append(True) # count_for_check += 1 # else: # check_list.append(False) # count_for_check += 1 # if not all(check_list): # raise # except RuntimeError as e: # print('Матрицы имеют разное количество строк или столбцов') # else: # return True init_1 = Matrix(first_matrix) init_2 = Matrix(second_matrix) init_3 = Matrix(third_matrix) sun_first_second = init_1 + init_2 + init_3 print(sun_first_second)
true
2bc2d8c6e8674ce78a692136fdee717e25a79f7c
Python
SGMartin/TCGAspot
/scripts/synthetic_letal_validation.py
UTF-8
3,456
2.859375
3
[]
no_license
#!/usr/bin/env python3 ''' Synthetic lethality validation: This module attempts to validate the presence in the TCGA of inferred synthethic lethal gene pairs predicted by VulcanSpot. To do so it tests whether the p. of both components of the pair being a LoF is significantly lower than expected if they were not associated. ''' #TODO: Note to Santi: keep in mind that at the moment only druggable pairs are # present in the database. Roughly 13k pairs. from scipy import stats from scipy.stats import fisher_exact from statsmodels.stats.multitest import multipletests import pandas as pd import numpy as np def main(): ## SNAKEMAKE I/O ## vulcan_db = snakemake.input[0] tcga_summary = snakemake.input[1] # Load datasets vulcan_db = pd.read_csv(vulcan_db, sep=',', usecols=['geneA', 'tissue', 'alteration', 'geneB'] ) # Drop duplicates due to removing drug info. vulcan_db = vulcan_db.drop_duplicates(keep='first') tcga_summary = pd.read_csv(tcga_summary, sep=',', usecols=['Hugo_Symbol', 'case_id', 'Context', 'Consequence' ] ) # Do not validate pairs with genA = genB as it makes no sense candidate_pairs = vulcan_db[vulcan_db['geneA'] != vulcan_db['geneB']] candidate_pairs['pvalue'] = candidate_pairs.apply(func=validate_synthetic_pair, axis='columns', args=(tcga_summary,) ) # Attempt to correct the p-value by FDR: Benjamini and Hochberg candidate_pairs['pvalue-c'] = multipletests(candidate_pairs['pvalue'], alpha=0.25, method='fdr_bh')[1] candidate_pairs.to_csv(snakemake.output[0], sep=',', index=False) def validate_synthetic_pair(synthetic_pair: pd.Series, tcga): ''' This method checks if a given synthethic lethal pair is less frequent than expected in validation_source dataframe, thus hinting the pair is indeed lethal. Returns an UNCORRECTED-FDR p-value of the test ''' geneA = synthetic_pair['geneA'] geneB = synthetic_pair['geneB'] alteration = synthetic_pair['alteration'] context = synthetic_pair['tissue'] print('Validating pair', geneA, alteration, geneB, 'in', context) if context == 'PANCANCER': patients = tcga # ignore context for these cases else: # select matched context patients patients = tcga[tcga['Context'] == context] # patients with gen A mutated with the same functional impact has_geneA = (patients['Hugo_Symbol'] == geneA) & (patients['Consequence'] == alteration) # patients with mutated gene B has_geneB = (patients['Hugo_Symbol'] == geneB) & (patients['Consequence'] == 'LoF') # get counts for each case: 1,2,3,4 in this order genA_genB_LoF = patients[has_geneA & has_geneB]['case_id'].nunique() genA_gen_B_WT = patients[~has_geneA & ~has_geneB]['case_id'].nunique() genA_LoF_genB_WT = patients[has_geneA & ~has_geneB]['case_id'].nunique() genA_WT_genB_LoF = patients[~has_geneA & has_geneB]['case_id'].nunique() ''' gene B LoF | gene B other alts + WT -------------------------------------------------- gene A Lof | 1 | 3 -------------------------------------------------- gene A WT + other alts | 4 | 2 -------------------------------------------------- ''' gene_table = [[genA_genB_LoF, genA_LoF_genB_WT], [genA_WT_genB_LoF, genA_gen_B_WT]] oddsratio, pvalue = fisher_exact(table=gene_table, alternative='less') return pvalue if __name__ == "__main__": main()
true
2293f6aa420be5b4303c5134c407f5545bfb93e8
Python
Aasthaengg/IBMdataset
/Python_codes/p02996/s297291821.py
UTF-8
227
3.421875
3
[]
no_license
n = int(input()) abl = [] for _ in range(n): a,b = map(int, input().split()) abl.append((b,a)) abl.sort() curr = 0 for b,a in abl: curr += a if curr > b: print('No') break else: print('Yes')
true
0d4bf06f7da19fcaa6ca22ec9be7c91791763c96
Python
rodrigo0li/Eliomar-Julian.github.io
/Resolucao-python/r18.py
UTF-8
349
4.125
4
[]
no_license
import math s = float(input('Digite um angulo para seno: ')) c = float(input('Digite um angulo para cosseno: ')) t = float(input('Digite um angulo para tangente: ')) seno = math.sin(math.radians(s)) cosseno = math.cos(math.radians(c)) tangente = math.tan(math.radians(t)) print(f'seno: {seno:.2f}\ncosseno: {cosseno:.2f}\ntangente: {tangente:.2f}')
true
2103e7b05048f929ce12819cf093e695f0070587
Python
riyapal/Characterising-Parser-Errors
/projective1.py
UTF-8
2,057
2.84375
3
[]
no_license
class Tree(object): leavee=0 def __init__(self,name,children=None): self.name=name self.children=[] self.visited=0 self.discovery=0 self.leave=0 def addChild(self,node): self.children.append(node) def dfs(self,vis): Tree.leavee+=1 self.visited=1 self.discovery=vis if len(self.children)==0: self.leave=vis+1 Tree.leavee+=1 for i in range(len(self.children)): self.children[i].dfs(vis+1) Tree.leavee+=1 if i==len(self.children)-1: self.leave=Tree.leavee def printTree(self): print self.name,self.discovery,self.leave for i in self.children: i.printTree() def buildtree(a,start,end): head=-1 for i in range(start,end): #print i if "0 main" in a[i]: head=i+1 assert (head > 0) print start,end ll=[] pro=[] for i in range(1,end-start+1): #created node temp=Tree(i) ll.append(temp) for i in range(start,end): #created tree assert a[i]!='\n' p=int(a[i].split()[6]) c=int(a[i].split()[0]) # print p, c if p>0: ll[p-1].addChild(ll[c-1]) assert (head > 0) ll[head-start-1].dfs(1) ll[head-start-1].printTree() pro=[] # print ll[p].discovery for i in range(start,end): p=a[i].split()[6] c=a[i].split()[0] temp=int(p) temp1=int(c) if(p>c): temp1=int(p) temp=int(c) count=0 # print "aaa" # print p,c # print p.discovery,p.leave for j in range(temp+1,temp1-1): # print ll[j].discovery,ll[j].leave if not ((ll[j].discovery < ll[int(p)].discovery) or (ll[j].leave > ll[int(p)].leave)): count+=1 if count==1: pro.append(start+j) break ll=[] return pro inp=raw_input("enter correct ") inp2=raw_input("enter parser ") f=open(inp) a=f.readlines() f.close() f=open(inp2) b=f.readlines() f.close() startsent=0 count=0 c=0 for i in range(len(a)): if a[i]=='\n': pro=[] pro=buildtree(a,startsent,i) if len(pro) >= 1: for j in range(startsent,i): if a[j]==b[j]: count+=1 c+=1 print "a" startsent=i+1 print print count print c
true
bf4eab0c3dcad3a80061031ae9ae285db7e584fc
Python
Mega-Victor/DigitRecgnizer
/dataVisu.py
UTF-8
827
3
3
[]
no_license
# !/usr/bin/python 3.5 # -*-coding:utf-8-*- from sklearn import datasets from sklearn import decomposition import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D mnist = datasets.load_digits() X = mnist.data y = mnist.target # 使用PCA把数据降为3维,寻找高维空间中, # 数据变化最快(方差最大)的方向,对空间的基进行变换, # 然后选取重要的空间基来对数据降维,以尽可能的保持数据特征的情况下对数据进行降维 pca = decomposition.PCA(n_components=3) # 训练算法,设置内部参数,数据转换。也就是合并fit和transform方法 new_X = pca.fit_transform(X) # 使用Axes3D进行3D绘图 fig = plt.figure() ax = fig.gca(projection='3d') ax.scatter(new_X[:, 0], new_X[:, 1], new_X[:, 2], c=y, cmap=plt.cm.spectral) plt.show()
true
5f91a34ff4fddbfa5d5371bf4826282e43235a0b
Python
xuelang201201/PythonCrashCourse
/11-测试代码/动手试一试/employee.py
UTF-8
774
4.25
4
[]
no_license
""" 雇员:编写一个名为 Employee 的类,其方法__init__()接受名、姓和年薪,并将它们都存储在属性中。编写一个名为 give_raise() 的方法,它默认将年薪增加 5000 美元,但也能够接受其他的年薪增加量。 为 Employee 编写一个测试用例,其中包含两个测试方法:test_give_default_raise()和 test_give_custom_raise()。使用方法 setUp(),以免在每个测试方法中都创建新的雇员实例。运行这个测试用例,确认两个测试都通过了。 """ class Employee: def __init__(self, f_name, l_name, salary): self.first = f_name.title() self.last = l_name.title() self.salary = salary def give_raise(self, amount=5000): self.salary += amount
true
dbde235fa4ff8dcd7bea770093e8493559bfe90a
Python
TuriViola/positioning
/plot_acouwaveform.py
UTF-8
1,022
2.625
3
[]
no_license
from get_acoudata import get_acoudata import matplotlib.pyplot as plt import numpy as np import argparse parser = argparse.ArgumentParser(description='waveform_plot') parser.add_argument('--filename', dest='filename', type=str, nargs='+', required=True, help='filename (e.g. raw_data_filename1 raw_data_filename2 ...)') args = parser.parse_args() filename = args.filename title_font = {'fontname':'Bitstream Vera Sans', 'size':'14', 'color':'black', 'weight':'normal', 'verticalalignment':'bottom'} # Bottom vertical alignment for more space axis_font = {'fontname':'Bitstream Vera Sans', 'size':'24'} plot_font = {'fontname':'Bitstream Vera Sans', 'size':'16'} data_plot=[] for i in range (0, len(filename)): time,data=get_acoudata(filename[i]) data_plot.extend(data) fs = 195312.4 plt.plot(np.arange(0,len(data_plot),1)/fs, data_plot, 'b') plt.xlabel('Time [s]',**axis_font) plt.ylabel('Amplitude',**axis_font) plt.rc('xtick', labelsize=16) plt.rc('ytick', labelsize=16) plt.grid() plt.show()
true
09be7ec57904eb8725d3870a645058eb1d357790
Python
ParthRoot/Basic-Python-Programms
/userinputarray.py
UTF-8
173
3.671875
4
[]
no_license
from array import * a = array('i',[]) n = int(input("Enter the length of array")) for i in range(n): x = int(input("Enter the element")) a.append(x) print(a)
true
ce75fd928d5e267794bec03bfc3866bd8595f3a6
Python
SublimeHaskell/SublimeHaskell
/hsdev/client.py
UTF-8
12,639
2.5625
3
[ "MIT" ]
permissive
"""The main API for the client-side of hsdev. """ import json import pprint import queue import random import socket import sys import threading import time import traceback import SublimeHaskell.internals.atomics as Atomics import SublimeHaskell.internals.logging as Logging import SublimeHaskell.internals.settings as Settings import SublimeHaskell.internals.utils as Utils def debug_send(): return Settings.COMPONENT_DEBUG.all_messages or Settings.COMPONENT_DEBUG.send_messages def debug_recv(): return Settings.COMPONENT_DEBUG.all_messages or Settings.COMPONENT_DEBUG.recv_messages class HsDevConnection(object): MAX_SOCKET_READ = 10240 '''Byte stream length that the client receiver will read from a socket at one time. ''' def __init__(self, sock, client, ident): super().__init__() self.socket = sock self.stop_event = threading.Event() self.client = client self.send_queue = queue.Queue() self.conn_ident = ident self.rcvr_thread = threading.Thread(name="hsdev recvr {0}".format(self.conn_ident), target=self.hsconn_receiver) self.send_thread = threading.Thread(name='hsdev sender {0}'.format(self.conn_ident), target=self.hsconn_sender) def start_connection(self): self.stop_event.clear() self.rcvr_thread.start() self.send_thread.start() def hsconn_receiver(self): '''Read from the connection's socket until encoutering a newline. The remaining part of the input stream is stashed in self.part for the next time the connection reads a request. ''' req_remain = '' while not self.stop_event.is_set() and self.socket is not None: # Note: We could have read a lot from the socket, which could have resulted in multiple request responses # being read (this can happen when the 'scan' command sends status updates): pre, sep, post = self.read_decoded_req().partition('\n') pre = ''.join([req_remain, pre]) while sep: resp = json.loads(pre) self.client.dispatch_response(resp) (pre, sep, post) = post.partition('\n') req_remain = pre def read_decoded_req(self): raw_req = bytearray() while self.socket is not None and not self.stop_event.is_set(): try: raw_req.extend(self.socket.recv(self.MAX_SOCKET_READ)) return raw_req.decode('utf-8').replace('\r\n', '\n').replace('\r', '\n') except UnicodeDecodeError: # Couldn't decode the string, so continue reading from the socket, accumulating # into stream_inp until utf-8 decoding succeeds. if debug_recv(): print(u'{0}.read_decoded_req: UnicodeDecodeError'.format(type(self).__name__)) except (OSError, socket.gaierror): # Socket problem. Just bail. self.stop_event.set() break return '' def hsconn_sender(self): while not self.stop_event.is_set(): try: # Block, but timeout, so that we can exit the loop gracefully request = self.send_queue.get(True, 6.0) if self.socket is not None: # Socket got closed and set to None in another thread... self.socket.sendall(request) if self.send_queue is not None: self.send_queue.task_done() except queue.Empty: pass except OSError: self.stop_event.set() def send_request(self, request): if self.send_queue is not None: msg = json.dumps(request, separators=(',', ':')) + '\n' self.send_queue.put(msg.encode('utf-8')) def close(self): try: self.stop_event.set() if self.socket is not None: self.socket.close() self.socket = None if self.rcvr_thread is not None and self.rcvr_thread.is_alive(): self.rcvr_thread.join() if self.send_thread is not None and self.send_thread.is_alive(): self.send_thread.join() self.client = None self.send_queue = None self.rcvr_thread = None self.send_thread = None except OSError: pass def __del__(self): # Paranoia. self.close() class HsDevClient(object): '''A client connection from SublimeHaskell to the hsdev server. It implements a primitive socket pool to maximize SublimeHaskell responsiveness (concurrency). ''' # Number of times we try to connect to the hsdev server CONNECT_TRIES = 10 # Delay between attempts if not successful CONNECT_DELAY = 2.0 # Initial number of available sockets N_SOCKETS = 4 def __init__(self, backend_mgr): # Primitive socket pool: self.backend_mgr = backend_mgr self.socket_pool = [] self.rcvr_event = threading.Event() self._request_map = Atomics.AtomicDuck() def __del__(self): self.close() @property def request_map(self): return self._request_map # Socket functions def connect(self, host, port): for i in range(0, self.N_SOCKETS): sock = self.create_connection(i, host, port) if sock is not None: hsconn = HsDevConnection(sock, self, i) self.socket_pool.insert(i, hsconn) else: # Something went wrong, terminate all connnections: for sock in self.socket_pool: try: sock.close() except OSError: pass self.socket_pool = [] return False # We were successful, start all of the socket threads, make them available... for sock in self.socket_pool: sock.start_connection() Logging.log('Connections established to \'hsdev\' server.', Logging.LOG_INFO) return True ## Rethink this in terms of multiple threads and a priority queue? def create_connection(self, idx, host, port): for retry in range(1, self.CONNECT_TRIES): try: Logging.log('[pool {0}]: connecting to hsdev server (attempt {1})...'.format(idx, retry), Logging.LOG_INFO) # Use 'localhost' instead of the IP dot-quad for systems (and they exist) that are solely # IPv6. Makes this code friendlier to IPv4 and IPv6 hybrid systems. return socket.create_connection((host, port)) except (socket.gaierror, IOError): # Captures all of the socket exceptions: msg = '[pool {0}]: Failed to connect to hsdev {1}:{2}:'.format(idx, host, port) Logging.log(msg, Logging.LOG_ERROR) print(traceback.format_exc()) time.sleep(self.CONNECT_DELAY) return None def close(self): self.rcvr_event.set() for sock in self.socket_pool: try: sock.close() except OSError: pass del self.socket_pool[:] def is_connected(self): return len(self.socket_pool) > 0 def verify_connected(self): return self.is_connected() def connection_lost(self, func_name, reason): self.close() Logging.log('{0}: connection to hsdev lost: {1}'.format(func_name, reason), Logging.LOG_ERROR) # send error to callbacks with self.request_map as requests: for (callbacks, _, _) in requests.values(): callbacks.call_on_error('connection lost', {}) requests.clear() def dispatch_response(self, resp): resp_id = resp.get('id') if not resp_id and 'request' in resp: # Error without an id, id is in the 'request' key's content. orig_req = json.loads(resp['request']) resp_id = orig_req.get('id') if resp_id: with self.request_map as requests: reqdata = requests.get(resp_id) if reqdata: callbacks, wait_event, _ = reqdata # Unconditionally call the notify callback: if 'notify' in resp: if Settings.COMPONENT_DEBUG.callbacks: print('id {0}: notify callback'.format(resp_id)) callbacks.call_notify(resp['notify']) if 'result' in resp or 'error' in resp: if wait_event: requests[resp_id] = (callbacks, wait_event, resp) # The wait-er calls callbacks, cleans up after the request. wait_event.set() else: # Enqueue for async receiver: Put the (resp_id, resp, reqdata) tuple onto the queue del requests[resp_id] if 'result' in resp: Utils.run_async('result {0}'.format(resp_id), callbacks.call_response, resp['result']) elif 'error' in resp: err = resp.pop("error") Utils.run_async('error {0}'.format(resp_id), callbacks.call_error, err, resp) else: msg = 'HsDevClient.receiver: request data expected for {0}, none found.'.format(resp_id) Logging.log(msg, Logging.LOG_WARNING) elif Logging.is_log_level(Logging.LOG_ERROR): print('HsDevClient.receiver: request w/o id\n{0}'.format(pprint.pformat(resp))) def call(self, command, opts, callbacks, wait, timeout): if not self.verify_connected(): return None if wait else False opts = opts or {} opts.update({'no-file': True, 'id': callbacks.ident, 'command': command}) wait_receive = threading.Event() if wait else None if debug_recv(): def client_call_error(exc, details): print('{0}.client_call_error: exc {1} details {2}'.format(type(self).__name__, exc, details)) callbacks.on_error.append(client_call_error) with self.request_map as requests: requests[callbacks.ident] = (callbacks, wait_receive, None) if debug_send(): print(u'HsDevClient.call[{0}] cmd \'{1}\' opts\n{2}'.format(callbacks.ident, command, pprint.pformat(opts))) try: # Randomly choose a connection from the pool -- even if we end up having a stuck sender, this should minimize # the probability of a complete hang. random.choice(self.socket_pool).send_request(opts) retval = True if wait: if debug_send(): print(u'HsDevClient.call: waiting to receive, timeout = {0}.'.format(timeout)) wait_receive.wait(timeout) if debug_send(): print(u'HsDevClient.call: done waiting.') with self.request_map as requests: if wait_receive.is_set(): callbacks, _, resp = requests[callbacks.ident] del requests[callbacks.ident] retval = resp if 'result' in resp: retval = callbacks.call_response(resp['result']) elif 'error' in resp: err = resp.pop("error") retval = callbacks.call_error(err, resp) if Settings.COMPONENT_DEBUG.callbacks: print('HsDevClient.call: wait {0} result {1}'.format(callbacks.ident, retval)) else: req = pprint.pformat(opts) errmsg = 'HsDevClient.call: wait_receive event timed out for id {0}\n{1}'.format(callbacks.ident, req) Logging.log(errmsg, Logging.LOG_ERROR) if Settings.COMPONENT_DEBUG.socket_pool: with self.request_map as request_map: print('id {0} request_map {1}'.format(callbacks.ident, len(request_map))) return retval except OSError: self.connection_lost('call', sys.exc_info()[1]) self.backend_mgr.lost_connection() return False
true
bc838224e8ebb1f480f67ca6f3a9d73a8464841e
Python
Dis-count/Python_practice
/practice/python-tutorial-master/32echart/city_map_demo.py
UTF-8
423
2.75
3
[ "Apache-2.0" ]
permissive
# -*- coding: utf-8 -*- """ @author:XuMing(xuming624@qq.com) @description: """ from pyecharts import Map value = [20, 190, 253, 77, 65] attr = ['汉阳区', '汉口区', '武昌区', '洪山区', '青山区'] map = Map("武汉地图示例", width=1200, height=600) map.add("", attr, value, maptype='武汉', is_visualmap=True, visual_text_color='#000', is_label_show=True) map.render("city_map.html")
true
bf833095a64d330071ad98441a146a793af59404
Python
hitochan777/kata
/atcoder/abc222/A.py
UTF-8
39
2.765625
3
[]
no_license
N = input() print("0" * (4-len(N)) + N)
true
8cfa581ab8d9e44fa98bedb5ac9738ae4b2e9c49
Python
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_201/1982.py
UTF-8
619
3.03125
3
[]
no_license
#!/usr/bin/env python3 T = int(input()) for t in range(1, T+1): N, K = [int(x) for x in input().split()] spaces = {(N,0)} out = [] inbox = {N: 1} def add_to_inbox(x, qty): if x > 0: if x in inbox: inbox[x] += qty else: inbox[x] = qty while len(out) < K: # odbrze? m = max(inbox) qty = inbox[m] out = out + [m] * qty del inbox[m] add_to_inbox(m // 2, qty) add_to_inbox((m-1) // 2, qty) m = out[K - 1] print("Case #{}: {} {}".format(t, m // 2, max(0, (m-1) // 2)))
true
22bf7e9985be6b63697716b3b1b508b2c633de42
Python
minthings/computer_science
/algorithm/baekjoon/1978.py
UTF-8
609
3.28125
3
[]
no_license
''' a= list(map(int, input().split())) 주어진 수 N개 중에서 소수가 몇 개인지 찾아서 출력하는 프로그램을 작성하시오. 첫 줄에 수의 개수 N이 주어진다. N은 100이하이다. 다음으로 N개의 수가 주어지는데 수는 1,000 이하의 자연수이다. 풀이 후기 : 소수가 나눠지는 수가 1과 자기자신이라는 뜻을 나머지가 1인 수 구하려고 함...하... 아프지말자... ''' n = int(input()) nums = list(map(int, input().split(' '))) result = 0 for i in nums: count = 0 for j in range(1, nums[1]+1): if i % j == 0:
true
0bb90961d45a585c1822bb70f01ba56fa11a97a8
Python
macmanes-lab/MCBS913
/code/jordan_final_scripts/error_finder.py
UTF-8
21,248
2.53125
3
[ "MIT" ]
permissive
#!/usr/local/bin/python """ Script: error_finder v3.14 Author: Jordan Ramsdell Desc: This script is meant to parse through metagenomic assemblie and find instances in which reads from different species map to the same contig. In such cases, the user can modify how these reads are filtered. The script can write the eronneous reads to a fasta file, and can also write the contigs in which these reads are located to a fasta file. """ import sys import re import cPickle from os import path import linecache from optparse import OptionParser, OptionGroup, IndentedHelpFormatter import mmap # declare global variables and useful types output = bytearray() output_contig = bytearray() counter = {} total_counter = 0 contigs = {} """:type : dict of [str, Contig]""" def create_parser(): """Creates the option parser used to parse through command-line args. Returns: options (like a dict, I guess): contains user-specified arguments. args (array): trailing arguments that are not paired with a flag. """ usage = "usage: %prog --sam SAM --coords COORDS --snps SNPS [options]" help_formatter = IndentedHelpFormatter() help_formatter.set_long_opt_delimiter(" ") help_formatter.indent_increment = 0 parser = OptionParser(usage, version="3.14", formatter=help_formatter) group_required = OptionGroup(parser, "Required parameters") group_flags = OptionGroup(parser, "Filtering options") group_debug_flags = OptionGroup(parser, "Debug options") group_output = OptionGroup(parser, "Output options") # SAM file argument group_required.add_option("--sam", dest="sam", help="Filepath to SAM file.") # coords file argument group_required.add_option("--coords", dest="coords", help="Filepath to COORDS file.") # mismatches argument (contained within the SNP file) group_required.add_option("--snps", dest="mismatches", help="Filepath to SNPS file.", metavar="SNPS") # parameter to output contigs where misaligned reads are located parser.add_option("--fasta", dest="contigs_filename", help="Fasta file containing contigs to extract" " if reads mapping to the wrong " "organisms are found.", metavar="FASTA") # optional output name for contigs group_output.add_option("--contigs", dest="output_contigs", help="Output name for contigs extracted from FASTA. " "Requires --fasta to be set.", metavar="CONTIGS") # flag to output the reads that came from different species group_output.add_option("--out", dest="output_reads", metavar="OUT", help="When set, writes misaligned reads to OUT") # flag to only consider reads near snps group_flags.add_option("--near_errors", dest="near_error", action="store_true", help="When set, only considers reads that are " "near (within 100 bp) mismatches found by " "aligning the contigs to " "the reference genomes via nucmer.") # flag to only consider reads near snps group_flags.add_option("--near_ends", dest="at_ends", action="store_true", help="When set, reads that are " "aligned to the ends of contigs (within 250 bp)" " are considered for checking for errors.") # option to filter contigs based on number of errors group_flags.add_option("--error_min", dest="error_min", help="Specifies the minimum number of error reads" "that must align to a contig before it is considered" "an error that is worth reporting (default is 2).", default=2, type="int", metavar="INT") # flag to show locations where reads from different species are mapping group_debug_flags.add_option("--show_regions", dest="show_regions", action="store_true", help="Shows the regions in contigs which " "reads from different species" " are mapping") # flag to show the misaligned read count from each species to each contig group_debug_flags.add_option("--show_counts", dest="read_count", action="store_true", help="Shows the number of reads in each contig" " that come from the wrong species.") parser.add_option_group(group_required) parser.add_option_group(group_output) parser.add_option_group(group_flags) parser.add_option_group(group_debug_flags) options, args = parser.parse_args() # raise error if required arguments are not supplied by the user error_message = "" if not options.mismatches: error_message = "missing --snps argument." elif not options.coords: error_message = "missing --coords argument." elif not options.sam: error_message = "missing --sam argument." if not error_message == "": parser.print_help() print "\nERROR: ", error_message exit(0) # parser.error(error_message) return options, args def parse_coords_file(coords_file): """Parses through *.coords file to get contig names and alignments. Returns: contigs (dict): contains Contig objects representing contigs in the assembly. Each one has alignment info to the reference. """ contigs = dict() try: f = open(coords_file, 'r') except IOError as e: print >> sys.stderr, "coords file does not exist: " + coords_file exit(1) f.readline() f.readline() for line in f: elements = line.split("|") ref_start, ref_stop, = elements[0].rstrip().split(" ") # PROBLEM: |'s in reference name are messing up parsing # SOLUTION: duct tape and bubblegum last_block = '%'.join(elements[4:]) split = last_block.split(" ") ref_name, contig_name = split[1], split[2] ref_name = str(re.match('.*?%(.*?)%', ref_name).group(1)) contig_name = contig_name.rstrip() ref_name = re.sub(".*?(?=NODE)", '', ref_name) c = Contig(ref_name, contig_name, ref_start, ref_stop) contigs[contig_name] = c f.close() return contigs def parse_sam_file(sam_file, contigs): """Parses through *.sam file to generate Read objects and add to contigs.""" try: f = open(sam_file, 'r+b') except IOError as e: print >> sys.stderr, "SAM file does not exist: " + sam_file exit(1) # FOR WINDOWS: mm = mmap.mmap(f.fileno(), 0, "ACCESS_READ") mm = mmap.mmap(f.fileno(), 0, mmap.MAP_PRIVATE, mmap.PROT_READ) line = mm.readline() idx = 0 while line: if line[0] == '@': line = mm.readline() continue idx += 1 elements = line.split("\t") contig = contigs.get(elements[2]) if contig: read_name = elements[0] aln_start = elements[3] sequence = elements[9] contig.read_params.append([read_name, aln_start, sequence]) line = mm.readline() print "The total number of reads in the sam file are: " + str(idx) mm.close() f.close() def parse_mismatch_file(mismatch_file, contigs): """Parses through mismatches/indels found in snp file. Adds to contigs.""" try: f = open(mismatch_file, 'r') except IOError as e: print >> sys.stderr, "snp file does not exist: " + mismatch_file exit(1) for line in f: elements = line.split("\t") contig = contigs.get(elements[1]) if not contig: continue contig.errors.append(int(elements[5])) f.close() class Contig(object): """Object that represents a contig in the assembly. Attributes: name (str): name of the contig. ref_name (str): name of the reference that this contig aligns to. ref_start (int): start of the contig's alignment to the reference. ref_stop (int): stop of the contig's alignment to the reference. reads (list): contains Read objects that align to this contig. errors (list): list of errors in this contig, based on snp calls. """ def __init__(self, ref_name, contig_name, ref_start, ref_stop): self.name = contig_name self.ref_name = ref_name self.ref_start = int(ref_start) self.ref_stop = int(ref_stop) self.reads = [] self.errors = [] self.sam_index = [] self.read_params = [] self.bad_read_count = 0 self.is_bad_contig = False self.ranges = [] m = re.match(".*?length_(.*?)_", self.name) self.length = int(m.group(1)) def get_reads(self): for i in self.read_params: read_name = i[0] aln_start = i[1] sequence = i[2] self.reads.append(Read(read_name, self.ref_start, self.ref_stop, aln_start, sequence)) def flush_reads(self): self.reads[:] = [] self.read_params[:] = [] def check_for_bad_alignment(self, verbose=False): """Iterates over each Read in read list. If the Read is not aligned properly, do something... """ bad_reads = 0 good_reads = 0 for read in self.reads: # is the read's start ref near our contig's start ref? read_start = read.read_ref_start contig_start = self.ref_start near_start = abs(read_start - contig_start) <= 1000 # if not, maybe it's near the end ref? (i.e. reverse direction) contig_stop = self.ref_stop near_stop = abs(read_start - contig_stop) <= 1000 # finally, maybe the read is just contained in the contig boundaries inside_boundaries = (contig_start <= read_start <= contig_stop) # if neither is true, we know the read aligned somewhere wrong. if not (near_stop or near_start or inside_boundaries): # this is where we report the problem. Insert stuff here bad_reads += 1 read.correct_alignment = False # else, this read is fine else: good_reads += 1 # don't give the user a report if we tell it to shut up. if not verbose: return print(self.name + " has " + str(good_reads) + " good reads and " + str(bad_reads) + " bads reads.") def check_for_reads_near_errors(self, verbose=False): reads_near_errors = 0 for read in self.reads: for error in self.errors: read_start = read.read_align_start if abs(read_start - error) >= 250: continue reads_near_errors += 1 read.near_error = True # don't give the user a report if we tell it to shut up. if not verbose: return print(self.name + " has " + str(reads_near_errors) + " reads near errors.") def check_for_really_bad_reads(self, verbose=False): really_bad_reads = 0 for read in self.reads: if read.near_error and not read.correct_alignment: really_bad_reads += 1 # don't give the user a report if we tell it to shut up. if not verbose: return print(self.name + " has " + str(really_bad_reads) + " reads that are near errors and are not aligned correctly.") def check_for_proper_alignment(self, options): start_offset = self.ref_start # this is where the contig aligns to ref global output, counter, total_counter, output_contig potential_output = bytearray() for read in self.reads: # to figure out where read is mapping back to reference, we # add the contig's alignment start to the start of where # the read is aligning to the contig. actual_location = start_offset + read.read_align_start # we also know where the read SHOULD be in the reference by # looking in the read's header. We compare these two values. start_difference = abs(read.read_ref_start - actual_location) if options.at_ends: at_ends = read.read_align_start < 250 \ or abs(self.length - read.read_align_start) < 250 else: at_ends = True if str(read.gi) != str(self.ref_name) and at_ends: # create a range for where contig aligns myname = [read.read_align_start, read.read_align_start + 250] merged = False for r in self.ranges: if (r[0] <= myname[0] <= r[1]) \ or (r[1] >= myname[1] >= r[0]): r[0] = myname[0] if myname[0] < r[0] else r[0] r[1] = myname[1] if myname[1] > r[1] else r[1] merged = True break near_error = True if not options.near_error else read.near_error if not merged and near_error: self.ranges.append(myname) string = ">" + read.name + "___" + self.ref_name + \ "___" + self.name + "\n" string += read.sequence + "\n" potential_output.extend(string) total_counter += 1 self.bad_read_count += 1 if not counter.get(self.ref_name): counter[self.ref_name] = {} if not counter[self.ref_name].get(self.name): counter[self.ref_name][self.name] = {} if not counter[self.ref_name][self.name].get(read.gi): counter[self.ref_name][self.name][read.gi] = 0 counter[self.ref_name][self.name][read.gi] += 1 if self.bad_read_count > options.error_min: output.extend(potential_output) self.is_bad_contig = True if options.show_regions and self.ranges: print self.name, "\n", self.ranges, "\n\n" class Read(object): """Object that represents a read in the assembly. Attributes: name (str): name of the read (contains gi and positional information) contig_ref_start (int): start of where the contig that this read is a part of aligns to the reference. contig_ref_stop (int): stop of where the contig that this read is a part of aligns to the reference. read_ref_start (int): start of where the read was generated from the reference. read_ref_stop (int): stop of where the read was generated from the reference. read_align_start (int): start of where the read aligns to the contig that it is contained within. read_align_stop (int): stop of where the read aligns to the contig that it is contained within. gi (str): the gi of the organism that this read came from correct_alignment(bool): True if, when this read aligns to a contig, that the contig's boundaries are near where the read SHOULD be in the reference. Defaults to: True near_error (bool): True if this read is located near snps (errors) in a contig. This may mean read is the source of the mismatch/indel in the contig. Defaults to: False sequence (str): The nucleotide sequence this read represents. average_quality (float): The phred-score quality of the alignment. """ def __init__(self, name, contig_ref_start, contig_ref_stop, aln_start, sequence): self.name = name self.contig_ref_start = int(contig_ref_start) self.read_ref_start = 0 self.contig_ref_stop = int(contig_ref_stop) self.read_align_start = int(aln_start) self.gi = None self.parse_name() self.correct_alignment = True self.near_error = False self.sequence = sequence def parse_name(self): """Parses the read's name to get positional information.""" elements = re.compile(":-:").split(self.name) self.gi = str(elements[1]) # more duct tape and bubblegum! if len(elements) == 4: self.read_ref_start = int(elements[3]) else: self.read_ref_start = int(elements[5]) def find_errors(options): global contigs for key in contigs: contig = contigs[key] contig.get_reads() contig.check_for_reads_near_errors() contig.check_for_proper_alignment(options) contig.flush_reads() def extract_bad_contigs(): global contigs bad_contig_list = "" for key in contigs: contig = contigs[key] if contig.is_bad_contig: bad_contig_list += contig.name + "\n" myfile = open("bad_contig_list.txt", "w") myfile.write(bad_contig_list) myfile.close() def extract_contigs(options): global contigs if not options.contigs_filename: return filename = options.contigs_filename if options.output_contigs: outname = options.output_contigs else: outname = "bad_contig_list.fasta" print "Writing contigs containing erroneous reads to " + outname contig_out = bytearray() with open(filename, "r") as f: file = f.read() for key in contigs: contig = contigs[key] if not contig.is_bad_contig: continue m = re.search(contig.name + "([^>]*)", file) if m: contig_out.extend(">" + contig.name + m.group(1)) else: print "bad" myfile = open(outname, "w") myfile.write(contig_out) myfile.close() # --------------------------- main -------------------------------------- def main(): global contigs, output, total_counter options, args = create_parser() """:type : OptionParser""" contigs = parse_coords_file(options.coords) print "Parsing SAM file." parse_sam_file(options.sam, contigs) parse_mismatch_file(options.mismatches, contigs) print "Finding read errors." find_errors(options) # calculate total number of reads from wrong species if options.read_count: print "Showing contigs." final_total = 0 for x in counter: for y in counter[x]: total = 0 for z in counter[x][y]: total += counter[x][y][z] if total >= options.error_min: final_total += total if options.read_count: print y, " -> ", counter[x][y], "\n\n" print "Number of erroneous reads before filtering:", total_counter print "Number of erroneous reads after filtering: " + str(final_total) # write outputs extract_contigs(options) out_name = "out.fa" if options.output_reads: out_name = options.output_reads print "Writing erroneous reads to " + out_name f = open(out_name, 'w') f.write(output) f.close() # execute main if this script was run via command-line if __name__ == "__main__": main()
true
63e7a0f36e878f7edf42904a9aedbf3f2f6052c7
Python
jiyun1006/pandas
/Series/ex2.py
UTF-8
175
3.171875
3
[]
no_license
import pandas as pd list_data = ['2019-01-02', 3.14, 'ABC', 100, True] sr = pd.Series(list_data) print(sr) idx = sr.index val = sr.values print(idx) print('\n') print(val)
true
460517891927b04c95ec8707d5bf91a2cd12bf60
Python
Matteo1988/Rosalind
/rosalind_grph.py
UTF-8
378
2.828125
3
[]
no_license
#first save rosalind_grph.txt as prova.fasta from Bio import SeqIO sequenze={} k = 3 # number of nucleotides that overlaps for seq in SeqIO.parse("prova.fasta", "fasta"): sequenze[seq.id] = str(seq.seq) for key1,value1 in sequenze.items(): for key2, value2 in sequenze.items(): if key1 != key2 and value1[0:k] == value2[-k:]: print(key2, key1)
true
588b8775b85b9caaed9b3d1fb19c98df42d0e462
Python
Rundong-Liu/Individual-Data-Science-Elements
/Hackerrank Algo Questions Collection/Search/Ice_Cream_Parlor.py
UTF-8
813
3.21875
3
[]
no_license
## Question: Given an unsorted integer list: cost (intger >= 1), an intger: money ## Return the index of two elements that summed together equal to the integr ## The question has only unique solution ## cost can have differnet positions with the same cost def whatFlavors(cost, money): dic = {} for i in range(len(cost)): if cost[i] < money: ## Handling repeated caost if cost[i] in dic: pass ## else: dic[cost[i]] = i if money - cost[i] in dic and i!= dic[money - cost[i]]: ## Used the constant time operation character of dictionary print (dic[money - cost[i]]+1 , i+1) return ## Medium - 35 ## 100% success ## O(n)
true
3aaa4e284cd7881e4fde3c5ff4de93641470b5f9
Python
dingxinjun/dodola
/dodola/core.py
UTF-8
15,147
2.6875
3
[ "Apache-2.0" ]
permissive
"""Core logic for bias-correction and downscaling Math stuff and business logic goes here. This is the "business logic". """ import numpy as np import logging from skdownscale.spatial_models import SpatialDisaggregator import xarray as xr from xclim import sdba, set_options from xclim.sdba.utils import equally_spaced_nodes from xclim.core.calendar import convert_calendar import xesmf as xe logger = logging.getLogger(__name__) # Break this down into a submodule(s) if needed. # Assume data input here is generally clean and valid. def train_quantiledeltamapping( reference, historical, variable, kind, quantiles_n=100, window_n=31 ): """Train quantile delta mapping Parameters ---------- reference : xr.Dataset Dataset to use as model reference. historical : xr.Dataset Dataset to use as historical simulation. variable : str Name of target variable to extract from `historical` and `reference`. kind : {"+", "*"} Kind of variable. Used for QDM scaling. quantiles_n : int, optional Number of quantiles for QDM. window_n : int, optional Centered window size for day-of-year grouping. Returns ------- xclim.sdba.adjustment.QuantileDeltaMapping """ qdm = sdba.adjustment.QuantileDeltaMapping( kind=str(kind), group=sdba.Grouper("time.dayofyear", window=int(window_n)), nquantiles=equally_spaced_nodes(int(quantiles_n), eps=None), ) qdm.train(ref=reference[variable], hist=historical[variable]) return qdm def adjust_quantiledeltamapping_year( simulation, qdm, year, variable, halfyearwindow_n=10, include_quantiles=False ): """Apply QDM to adjust a year within a simulation. Parameters ---------- simulation : xr.Dataset Daily simulation data to be adjusted. Must have sufficient observations around `year` to adjust. qdm : xr.Dataset or sdba.adjustment.QuantileDeltaMapping Trained ``xclim.sdba.adjustment.QuantileDeltaMapping``, or Dataset representation that will be instantiate ``xclim.sdba.adjustment.QuantileDeltaMapping``. year : int Target year to adjust, with rolling years and day grouping. variable : str Target variable in `simulation` to adjust. Adjusted output will share the same name. halfyearwindow_n : int, optional Half-length of the annual rolling window to extract along either side of `year`. include_quantiles : bool, optional Whether or not to output quantiles (sim_q) as a coordinate on the bias corrected data variable in output. Returns ------- out : xr.Dataset QDM-adjusted values from `simulation`. May be a lazy-evaluated future, not yet computed. """ year = int(year) variable = str(variable) halfyearwindow_n = int(halfyearwindow_n) if isinstance(qdm, xr.Dataset): qdm = sdba.adjustment.QuantileDeltaMapping.from_dataset(qdm) # Slice to get 15 days before and after our target year. This accounts # for the rolling 31 day rolling window. timeslice = slice( f"{year - halfyearwindow_n - 1}-12-17", f"{year + halfyearwindow_n + 1}-01-15" ) simulation = simulation[variable].sel( time=timeslice ) # TODO: Need a check to ensure we have all the data in this slice! if include_quantiles: # include quantile information in output with set_options(sdba_extra_output=True): out = qdm.adjust(simulation, interp="nearest").sel(time=str(year)) # make quantiles a coordinate of bias corrected output variable out = out["scen"].assign_coords(sim_q=out.sim_q) else: out = qdm.adjust(simulation, interp="nearest").sel(time=str(year)) return out.to_dataset(name=variable) def train_analogdownscaling( coarse_reference, fine_reference, variable, kind, quantiles_n=620, window_n=31 ): """Train analog-inspired quantile-preserving downscaling Parameters ---------- coarse_reference : xr.Dataset Dataset to use as resampled (to fine resolution) coarse reference. fine_reference : xr.Dataset Dataset to use as fine-resolution reference. variable : str Name of target variable to extract from `coarse_reference` and `fine_reference`. kind : {"+", "*"} Kind of variable. Used for creating AIQPD adjustment factors. quantiles_n : int, optional Number of quantiles for AIQPD. window_n : int, optional Centered window size for day-of-year grouping. Returns ------- xclim.sdba.adjustment.AnalogQuantilePreservingDownscaling """ # AIQPD method requires that the number of quantiles equals # the number of days in each day group # e.g. 20 years of data and a window of 31 = 620 quantiles # check that lengths of input data are the same, then only check years for one if len(coarse_reference.time) != len(fine_reference.time): raise ValueError("coarse and fine reference data inputs have different lengths") # check number of years in input data (subtract 2 for the +/- 15 days on each end) num_years = len(np.unique(fine_reference.time.dt.year)) - 2 if (num_years * int(window_n)) != quantiles_n: raise ValueError( "number of quantiles {} must equal # of years {} * window length {}, day groups must {} days".format( quantiles_n, num_years, int(window_n), quantiles_n ) ) aiqpd = sdba.adjustment.AnalogQuantilePreservingDownscaling( kind=str(kind), group=sdba.Grouper("time.dayofyear", window=int(window_n)), nquantiles=quantiles_n, ) aiqpd.train(coarse_reference[variable], fine_reference[variable]) return aiqpd def adjust_analogdownscaling(simulation, aiqpd, variable): """Apply AIQPD to downscale bias corrected output. Parameters ---------- simulation : xr.Dataset Daily bias corrected data to be downscaled. aiqpd : xr.Dataset or sdba.adjustment.AnalogQuantilePreservingDownscaling Trained ``xclim.sdba.adjustment.AnalogQuantilePreservingDownscaling``, or Dataset representation that will instantiate ``xclim.sdba.adjustment.AnalogQuantilePreservingDownscaling``. variable : str Target variable in `simulation` to downscale. Downscaled output will share the same name. Returns ------- out : xr.Dataset AIQPD-downscaled values from `simulation`. May be a lazy-evaluated future, not yet computed. """ variable = str(variable) if isinstance(aiqpd, xr.Dataset): aiqpd = sdba.adjustment.AnalogQuantilePreservingDownscaling.from_dataset(aiqpd) out = aiqpd.adjust(simulation[variable]) return out.to_dataset(name=variable) def apply_bias_correction( gcm_training_ds, obs_training_ds, gcm_predict_ds, train_variable, out_variable, method, ): """Bias correct input model data using specified method, using either monthly or +/- 15 day time grouping. Currently the QDM method is supported. Parameters ---------- gcm_training_ds : Dataset training model data for building quantile map obs_training_ds : Dataset observation data for building quantile map gcm_predict_ds : Dataset future model data to be bias corrected train_variable : str variable name used in training data out_variable : str variable name used in downscaled output method : {"QDM"} method to be used in the applied bias correction Returns ------- ds_predicted : xr.Dataset Dataset that has been bias corrected. """ if method == "QDM": # instantiates a grouper class that groups by day of the year # centered window: +/-15 day group group = sdba.Grouper("time.dayofyear", window=31) model = sdba.adjustment.QuantileDeltaMapping(group=group, kind="+") model.train( ref=obs_training_ds[train_variable], hist=gcm_training_ds[train_variable] ) predicted = model.adjust(sim=gcm_predict_ds[train_variable]) else: raise ValueError("this method is not supported") ds_predicted = predicted.to_dataset(name=out_variable) return ds_predicted def apply_downscaling( bc_ds, obs_climo_coarse, obs_climo_fine, train_variable, out_variable, method, domain_fine, weights_path=None, ): """Downscale input bias corrected data using specified method. Currently only the BCSD method for spatial disaggregation is supported. Parameters ---------- bc_ds : Dataset Model data that has already been bias corrected. obs_climo_coarse : Dataset Observation climatologies at coarse resolution. obs_climo_fine : Dataset Observation climatologies at fine resolution. train_variable : str Variable name used in obs data. out_variable : str Variable name used in downscaled output. method : {"BCSD"} Vethod to be used in the applied downscaling. domain_fine : Dataset Domain that specifies the fine resolution grid to downscale to. weights_path : str or None, optional Path to the weights file, used for downscaling to fine resolution. Returns ------- af_fine : xr.Dataset A dataset of adjustment factors at fine resolution used in downscaling. ds_downscaled : xr.Dataset A model dataset that has been downscaled from the bias correction resolution to specified domain file resolution. """ if method == "BCSD": model = SpatialDisaggregator(var=train_variable) af_coarse = model.fit(bc_ds, obs_climo_coarse, var_name=train_variable) # regrid adjustment factors # BCSD uses bilinear interpolation for both temperature and precip to # regrid adjustment factors af_fine = xesmf_regrid(af_coarse, domain_fine, "bilinear", weights_path) # apply adjustment factors predicted = model.predict( af_fine, obs_climo_fine[train_variable], var_name=train_variable ) else: raise ValueError("this method is not supported") ds_downscaled = predicted.to_dataset(name=out_variable) return af_fine, ds_downscaled def build_xesmf_weights_file(x, domain, method, filename=None): """Build ESMF weights file for regridding x to a global grid Parameters ---------- x : xr.Dataset domain : xr.Dataset Domain to regrid to. method : str Method of regridding. Passed to ``xesmf.Regridder``. filename : optional Local path to output netCDF weights file. Returns ------- outfilename : str Path to resulting weights file. """ out = xe.Regridder( x, domain, method=method, filename=filename, ) return str(out.filename) def _add_cyclic(ds, dim): """ Adds wrap-around, appending first value to end of data for named dimension. Basically an xarray version of ``cartopy.util.add_cyclic_point()``. """ return ds.map( lambda x, d: xr.concat([x, x.isel({d: 0})], dim=d), keep_attrs=True, d=str(dim), ) def xesmf_regrid(x, domain, method, weights_path=None, astype=None, add_cyclic=None): """ Regrid a Dataset. Parameters ---------- x : xr.Dataset domain : xr.Dataset Domain to regrid to. method : str Method of regridding. Passed to ``xesmf.Regridder``. weights_path : str, optional Local path to netCDF file of pre-calculated XESMF regridding weights. astype : str, numpy.dtype, or None, optional Typecode or data-type to which the regridded output is cast. add_cyclic : str, or None, optional Add cyclic point (aka wrap-around pixel) to given dimension before regridding. Useful for avoiding dateline artifacts along longitude in global datasets. Returns ------- xr.Dataset """ if add_cyclic: x = _add_cyclic(x, add_cyclic) regridder = xe.Regridder( x, domain, method=method, filename=weights_path, ) if astype: return regridder(x).astype(astype) return regridder(x) def standardize_gcm(ds, leapday_removal=True): """ Parameters ---------- ds : xr.Dataset leapday_removal : bool, optional Returns ------- xr.Dataset """ # Remove cruft coordinates, variables, dims. cruft_vars = ("height", "member_id", "time_bnds") dims_to_squeeze = [] coords_to_drop = [] for v in cruft_vars: if v in ds.dims: dims_to_squeeze.append(v) elif v in ds.coords: coords_to_drop.append(v) ds_cleaned = ds.squeeze(dims_to_squeeze, drop=True).reset_coords( coords_to_drop, drop=True ) # Cleanup time. # if variable is precip, need to update units to mm day-1 if "pr" in ds_cleaned.variables: # units should be kg/m2/s in CMIP6 output if ds_cleaned["pr"].units == "kg m-2 s-1": # convert to mm/day mmday_conversion = 24 * 60 * 60 ds_cleaned["pr"] = ds_cleaned["pr"] * mmday_conversion # update units attribute ds_cleaned["pr"].attrs["units"] = "mm day-1" else: # we want this to fail, as pr units are something we don't expect raise ValueError("check units: pr units attribute is not kg m-2 s-1") if leapday_removal: # if calendar is just integers, xclim cannot understand it if ds.time.dtype == "int64": ds_cleaned["time"] = xr.decode_cf(ds_cleaned).time # remove leap days and update calendar ds_noleap = xclim_remove_leapdays(ds_cleaned) # rechunk, otherwise chunks are different sizes ds_out = ds_noleap.chunk({"time": 730, "lat": len(ds.lat), "lon": len(ds.lon)}) else: ds_out = ds_cleaned return ds_out def xclim_remove_leapdays(ds): """ Parameters ---------- ds : xr.Dataset Returns ------- xr.Dataset """ ds_noleap = convert_calendar(ds, target="noleap") return ds_noleap def apply_wet_day_frequency_correction(ds, process): """ Parameters ---------- ds : xr.Dataset process : {"pre", "post"} Returns ------- xr.Dataset Notes ------- [1] A.J. Cannon, S.R. Sobie, & T.Q. Murdock, "Bias correction of GCM precipitation by quantile mapping: How well do methods preserve changes in quantiles and extremes?", Journal of Climate, vol. 28, Issue 7, pp. 6938-6959. """ threshold = 0.05 # mm/day low = 1e-16 if process == "pre": ds_corrected = ds.where(ds != 0.0, np.random.uniform(low=low, high=threshold)) elif process == "post": ds_corrected = ds.where(ds >= threshold, 0.0) else: raise ValueError("this processing option is not implemented") return ds_corrected
true
5a3d91413fb44c9f0554cbf4a64ec15ac278d722
Python
DerickMathew/adventOfCode2020
/Day14/02/solution.py
UTF-8
1,761
3.25
3
[]
no_license
def getLines(): inputFile = open('../input.txt', 'r') lines = inputFile.readlines() return map(lambda line: line.split('\n')[0], lines) def get36BitBinaryArray(value): binaryArray = [] counter = 0 while counter < 36: binaryArray.append(value % 2) value = value // 2 counter += 1 binaryArray = [n for n in reversed(binaryArray)] return binaryArray def getNumberFromBinaryArray(binaryArray): binaryArray = [n for n in reversed(binaryArray)] power = 0 number = 0 for bit in binaryArray: number += bit * (2 ** power) power += 1 return number def getAddressesFromMask(maskedAddress): if len(filter(lambda x: x == 'X', maskedAddress)) == 0: return [getNumberFromBinaryArray(maskedAddress)] firstXIndex = maskedAddress.index('X') addresses = [] for bit in [0, 1]: newAddress = maskedAddress[:] newAddress[firstXIndex] = bit addresses.extend(getAddressesFromMask(newAddress)) return addresses def getMaskedAddresses(mask, address): binaryAddress = get36BitBinaryArray(address) maskedAddress = [] for pos in xrange(len(binaryAddress)): if mask[pos] == 'X': maskedAddress.append('X') elif mask[pos] == '0': maskedAddress.append(binaryAddress[pos]) else: maskedAddress.append(1) addresses = getAddressesFromMask(maskedAddress) return addresses def processLines(lines): mask = 'X' * 36 memory = {} for line in lines: if line[:4] == 'mask': mask = line[7:] else: [rawAddress, value] = line.split(' = ') rawAddress = int(rawAddress[4:-1]) value = int(value) for address in getMaskedAddresses(mask, rawAddress): memory[address] = value return memory def solution(): lines = getLines() memory = processLines(lines) print sum(map(lambda key: memory[key], memory.keys())) solution()
true
1a92862d678f97beae64f7da132d2647f6ab102c
Python
Boberkraft/Data-Structures-and-Algorithms-in-Python
/chapter2/P-2.35.py
UTF-8
1,633
3.828125
4
[]
no_license
# Write a set of Python classes that can simulate an Internet application in # which one party, Alice, is periodically creating a set of packets that she # wants to send to Bob. An Internet process is continually checking if Alice # has any packets to send, and if so, it delivers them to Bob’s computer, and # Bob is periodically checking if his computer has a packet from Alice, and, # if so, he reads and deletes it. from time import time from collections import defaultdict class Internet: def __init__(self): self.queue = defaultdict(list) def send_msg(self, msg, where): self.queue[where].append(msg) def get_msg(self, who): msg = self.queue[who] if msg: del self.queue[who] return msg class User: def __init__(self, name, internet, delay=1): self.name = name self.internet = internet self._last_action = 0 self.delay = delay def can(self): if time() - self._last_action > self.delay: self._last_action = time() return True return False def send(self, msg, where): self.internet.send_msg(msg, where) def recive(self): msg = self.internet.get_msg(self.name) if msg: print('{} got {}'.format(self.name, msg)) del msg # no need to delete but why not if __name__ == '__main__': internet = Internet() alice = User('Alice', internet, 1) bob = User('Bob', internet, 2) while True: if bob.can(): bob.recive() if alice.can(): alice.send('I LOVE YOU <3', 'Bob')
true
c1cde76ec88941bcdc37fc60e7586279bdf2651c
Python
CodeTheCity/ctc21_nautical_wrecks
/CTC21/HES/main.py
UTF-8
4,464
2.640625
3
[]
no_license
import shapefile as shp import OSGridConverter as OSGC import csv from canmore_classes import Shipwreck wd_name_list = [] canmore_id_list = [] complete_list = [] valid_grid_ref = ['HO','HP','HT','HU','HW','HX','HY','HZ','NA','NB','NC','ND','NE','NF','NG','NH','NJ','NK','NL','NM', 'NN','NO','NP','NR','NS','NT','NU','NW','NX','NY','NZ','OV','SC','SD','SE','SH','SJ','SK','SM','SN', 'SO','SP','SR','SS','ST','SU','SV','SW','SX','SY','SZ','TA','TF','TG','TL','TM','TQ','TR','TV'] def main(): global wd_exists_list, wd_name_list with open('wd_existing.csv', mode='r') as raw_input: reader = csv.reader(raw_input) canmore_id_list = [row[0] for row in reader] with open('WD_labels.csv', mode='r') as raw_input: reader = csv.reader(raw_input) wd_name_list = [row[0] for row in reader] print(wd_name_list) with open('councils.csv', mode='r') as raw_input: reader = csv.reader(raw_input) council_dict = {rows[1]: rows[0] for rows in reader} del council_dict["item"] with open('short_types.csv', mode='r') as raw_input: reader = csv.reader(raw_input) type_dict = {rows[1]: rows[0] for rows in reader} del type_dict["item"] with shp.Reader("Canmore_Points/Canmore_Maritime") as sf: records = sf.shapeRecords() for rec in records: #added check for existing records in the AND clause if rec.record[12][:2] in valid_grid_ref and not rec.record[14].split('/')[-2] in canmore_id_list: rec_class = generate_class(rec, council_dict, type_dict) complete_list.append(rec_class) with open('output.txt', mode="w") as output_text: for rec_class in complete_list: output_text.write(rec_class.create_string()+"\n") """for rec in records: can_id = rec.record[14].split('/')[-2] if can_id == "292341": print_record(rec, council_dict, type_dict)""" def generate_class(rec, council_dict, type_dict): global wd_name_list can_id = rec.record[14].split('/')[-2] if rec.record[2].split(":")[0] not in wd_name_list: name = tidy_string(rec.record[2].split(":")[0]) else: name = tidy_string(rec.record[2].split(":")[0]) + " " + can_id ship_type = get_type_Q(rec.record[5], type_dict) council = council_dict[tidy_string(rec.record[7])] gr = rec.record[12] latlong = convert_coords(gr) loc = f"@{latlong.latitude}/{latlong.longitude}" my_class = Shipwreck(name, ship_type, council, loc, can_id) return my_class def convert_coords(gr): latlong = OSGC.grid2latlong(gr) return latlong def tidy_string(str_val): str_val = str_val.lower() str_val = str_val.capitalize() return str_val def get_type_Q(raw_type, type_dict): ship_type = tidy_string(raw_type.split(",")[0].split("[")[0].split("(")[0].strip()) if ship_type in type_dict: return type_dict[ship_type] else: return "Q11446" def print_record(rec, council_dict, type_dict): name = tidy_string(rec.record[2].split(":")[0]) ship_type = get_type_Q(rec.record[5], type_dict) council = council_dict[tidy_string(rec.record[7])] gr = rec.record[12] latlong = convert_coords(gr) loc = f"@{latlong.latitude}/{latlong.longitude}" can_id = rec.record[14].split('/')[-2] my_class = Shipwreck(name, ship_type, council, loc, can_id) print(my_class.create_string()) if __name__ == '__main__': main() """ Temporary script to find missing ship types type_set = set() for rec in records: ship_type = tidy_string(rec.record[5].split(",")[0].split("[")[0].split("(")[0].strip()) type_set.add(ship_type) with open('ship_types.csv', mode='r', encoding="utf-8") as raw_input: reader = csv.reader(raw_input) types_dict = {rows[1].lower(): rows[0] for rows in reader} del types_dict["itemlabel"] temp_set = set() temp_type_dict = {} for s_type in type_set: if s_type.lower() not in types_dict: temp_set.add(s_type) else: temp_type_dict[s_type] = types_dict[s_type.lower()] with open('types.txt', 'w') as opened_file: for s_type in temp_set: opened_file.write(str(s_type)+"\n") with open('types2.txt', 'w') as opened_file: for s_type in temp_type_dict: opened_file.write(str(s_type)+"\n") """
true
71656772f0a465be7a158d2fb16ebf2c865d37c3
Python
YUNKWANGYOU/Quiz
/ETC/1406.py
UTF-8
591
2.96875
3
[]
no_license
import sys l_stack = list(sys.stdin.readline().rstrip('\n')) r_stack = list() n = int(sys.stdin.readline()) for i in range(n) : command = sys.stdin.readline() if command[0] == 'L' and l_stack : r_stack.append(l_stack.pop()) elif command[0] == 'D' and r_stack : l_stack.append(r_stack.pop()) elif command[0] == 'B' and l_stack : l_stack.pop() if command[0] == 'P' : l_stack.append(command[2]) for i in range(len(l_stack)) : print(l_stack[i],end = '') for i in range(len(r_stack)-1,-1,-1) : print(r_stack[i],end = '') print("")
true
8bff28c498a7f38d480aecab2d6d0c5ba7b3a5a7
Python
fank-cd/python_leetcode
/Problemset/can-make-arithmetic-progression-from-sequence/can-make-arithmetic-progression-from-sequence.py
UTF-8
534
3.359375
3
[]
no_license
# @Title: 判断能否形成等差数列 (Can Make Arithmetic Progression From Sequence) # @Author: 2464512446@qq.com # @Date: 2020-07-05 10:50:17 # @Runtime: 44 ms # @Memory: 13.4 MB class Solution: def canMakeArithmeticProgression(self, arr: List[int]) -> bool: if not arr: return False if len(arr) <2 : return arr arr = sorted(arr) # print(arr) if (arr[0]+arr[len(arr)-1])*len(arr)/2 == sum(arr): return True else: return False
true
b143b6dd692e5500e046efa9ea9646a69cfbd865
Python
rmclean98/CSCI-4150
/Image-Registration/ProcessHarrisCorner.py
UTF-8
979
2.796875
3
[]
no_license
import cv2 import numpy as np from PIL import Image from MessageBox import MessageBox from matplotlib import pyplot as plt class ProcessHarrisCorner: def ProcessTransformation(inputFile,bsizevalue,ksizevalue,harrisvalue): try: # read images img1 = cv2.imread(inputFile) # Change to Grayscale img1_Gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) # Find points using Harris Corner Detection dst=cv2.cornerHarris(img1_Gray,int(bsizevalue),int(ksizevalue),float(harrisvalue)) dst = cv2.dilate(dst, None) #Change the intensity of the points detected to make it visible img1[dst>0.05*dst.max()] =[0,0,255] cv2.imshow("Image",img1) cv2.waitKey(0) except IOError: MessageBox.showMessageBox('info','Please provide a valid Image File Path to Transform')
true
2117cfc23764ac051bc6cdac07c07ee74f2f59a0
Python
prasanth-ashokan/My-Programs
/HR/dragon.py
UTF-8
203
2.8125
3
[]
no_license
n,k=map(int,input().split()) l=[int(i) for i in input().split()] c=0 for i in l: for j in range(n): if l[j]%i==0 or i%l[j]==0: if (i*l[j])%k!=1: c=c+1 print(c//k)
true
3c679755196e7b2cc06f597c8e739216acc9b34d
Python
naughtyneigbour/ctfscript
/crypto/bacon.py
UTF-8
847
2.546875
3
[]
no_license
#!/usr/bin/python2 import sys import re if len(sys.argv) != 2: print "This tool use the bacon encoding to parse a sentence with majuscule and minuscule into baabb.. structure." print "USAGE: {0} TEXT_TO_ENCODE".format(__file__) print "" print "EXAMPLE:" print "$ {0} VoiCIunESUpeRbereCeTtEcONconteepARunGrouPedArtistEsculinaiRedONTleBOnGoutetlESeNsdeLAcLasSenestlimIteEqUeparLEnombreDEcAlOriesqUilsPeUVEntIngurgiter".format(__file__) print "$ BAABB AABBB AABAA AABAB ABABB AAAAA AABBA ABAAA BAABA AAAAB AAAAA AAABA ABBBA ABBAB AAAAA ABBAB AAABB ABAAB AAAAA AAABA ABABA AAABB AAAAA ABBAB ABAAA AABAA ABABB BAABA AAAAA" exit(0) s = re.sub('[^0-9a-zA-Z]+', '*', sys.argv[1]) out = '' for i in range(0, len(s)): if i%5 == 0: out += ' ' c = s[i] cint = ord(s[i]) if cint >= 65 and cint <=90: out += 'B' else: out += 'A' print out
true
e53ef76dd07984579459733962456e9538955287
Python
tomdewildt/covid-19-data-collector
/test/test_collector/test_schema.py
UTF-8
935
2.9375
3
[ "MIT" ]
permissive
import pytest from collector.schema import obj, string, validate, ValidationError class TestValidateSchema: def test_validate_schema_valid_input(self): schema = obj(key=string()) inputs = {"key": "value"} validate(schema, inputs) @pytest.mark.parametrize( "schema,inputs,messages", [ (obj(key=string()), {}, ["'key' is a required property"]), (obj(key=string()), None, ["None is not of type 'object'"]), (obj(key=string()), {"key": 1}, ["1 is not of type 'string'"]), (obj(key=string()), {"key-test": 1}, ["'key' is a required property"]), ], ) def test_validate_schema_invalid_input(self, schema, inputs, messages): with pytest.raises(ValidationError) as error: validate(schema, inputs) for (idx, error) in enumerate(error.value.errors): assert error.message == messages[idx]
true
beb76f3d23c290d6f83cf9d12109e1185b790743
Python
CDinuwan/PortScanner
/PortScanner.py
UTF-8
5,673
2.953125
3
[]
no_license
#!/usr/bin/env python3 import socket import os import sys import subprocess if __name__ == "__main__": try: print("┏━┓┏━┓┏━┓╺┳╸ ┏━┓┏━╸┏━┓┏┓╻┏┓╻┏━╸┏━┓") print("┣━┛┃ ┃┣┳┛ ┃ ┗━┓┃ ┣━┫┃┗┫┃┗┫┣╸ ┣┳┛") print("╹ ┗━┛╹┗╸ ╹ ┗━┛┗━╸╹ ╹╹ ╹╹ ╹┗━╸╹┗╸") print(" created by-CDinuwan") s=socket.socket(socket.AF_INET , socket.SOCK_STREAM) s.settimeout(5) print(" 1.Select port in List : \n 2.Select custom port : \n 3.Upgrade Linux \n 4.Update Linux \n") selection=input("Enter Your Selection : \n") if selection=="1": print(" 1.Port 20-File Transfer Protocol(FTP) /n 2.Port-21-Dile Transfer Protocol(FTP) \n 3.Port-22-Secure Shell(SSH) \n 4.Port-23-Telnet \n 5.Port 25-Simple Mail Transfer Protocol(SMTP) \n 6.Port 53-Domain Name System(DNS) \n 7.Port 67-Dynamic Host Configuration Protocol(DHCP) \n 8.Port 68-Dynamic Host Configuration Protocol(DHCP)") print(" 9.Port 80-Hypertext Transfer Protocol(HTTP) \n 10.Port 110-Post Office Protocol(POP3) \n 11.Port 119-Network News Transfer Protocol(NNTP) \n 12.Port 123-Network Time Protocol(NTP) \n 13.Port 143-Internet Message Access Protocol(IMAP) \n 14.Port 161-Simple Network Management Protocol(SNMP) \n 15.Port 194-Internet Relay Chat(IRC) \n 16.Port 443-HTTP Secure(HTTPS) \n") port_num=input("Select port from list :") host=input("Enter the IP Address: ") if port_num=="1": if s.connect_ex((host,20)): print("The port is closed") else: print("The port is open") elif port_num=="2": if s.connect_ex((host,21)): print("The port is closed") else: print("The port is open") elif port_num=="3": if s.connect_ex((host,22)): print("The port is closed") else: print("The port is open") elif port_num=="4": if s.connect_ex((host,23)): print("The port is closed") else: print("The port is open") elif port_num=="5": if s.connect_ex((host,25)): print("The port is closed") else: print("The port is open") elif port_num=="6": if s.connect_ex((host,53)): print("The port is closed") else: print("The port is open") elif port_num=="7": if s.connect_ex((host,67)): print("The port is closed") else: print("The port is open") elif port_num=="8": if s.connect_ex((host,68)): print("The port is closed") else: print("The port is open") elif port_num=="9": if s.connect_ex((host,80)): print("The port is closed") else: print("The port is open") elif port_num=="10": if s.connect_ex((host,110)): print("The port is closed") else: print("The port is open") elif port_num=="11": if s.connect_ex((host,119)): print("The port is closed") else: print("The port is open") elif port_num=="12": if s.connect_ex((host,123)): print("The port is closed") else: print("The port is open") elif port_num=="13": if s.connect_ex((host,143)): print("The port is closed") else: print("The port is open") elif port_num=="14": if s.connect_ex((host,161)): print("The port is closed") else: print("The port is open") elif port_num=="15": if s.connect_ex((host,194)): print("The port is closed") else: print("The port is open") elif port_num=="16": if s.connect_ex((host,443)): print("The port is closed") else: print("The port is open") elif selection=="2": host=input("Enter the IP Address: ") port_num=int(input("Select port :")) if s.connect_ex((host,port_num)): print("The port is closed") else: print("The port is open") elif selection=="3": process = subprocess.call("sudo apt upgrade") elif selection=="4": process = subprocess.call("sudo apt upgrade") else: print("Invalid Selection") except ValueError as err: print(err) except: print("This program didn't work correctly in you device or check your inputs")
true
5858ccee727784c28ce5550517e063a57e07a6bc
Python
yeqf911/PyOS
/test/buses.py
UTF-8
1,893
3.171875
3
[]
no_license
# coding=utf-8 import xml.sax import cothread # 一个装饰器,工作是为了为有 yield 语句的函数做 f.send(None) 的工作 def coroutine(func): def wrapper(*args, **kwargs): rs = func(*args, **kwargs) rs.send(None) return rs return wrapper class Bushandler(xml.sax.ContentHandler): def __init__(self, target): xml.sax.ContentHandler.__init__(self) self.target = target def startElement(self, name, attrs): self.target.send(('start', (name, attrs))) def characters(self, content): self.target.send(('content', content)) def endElement(self, name): self.target.send(('end', name)) @coroutine def buses_to_dict(target): try: while True: event, value = (yield) if event == 'start' and value[0] == 'bus': buses = {} fragment = [] while True: event, value = (yield) if event == 'start': fragment = [] if event == 'content': fragment.append(value) if event == 'end': if value != 'bus': buses[value] = ' '.join(fragment) else: target.send(buses) break except GeneratorExit: target.close() @coroutine def direction_filter(field, value, target): d = (yield) if d.get(field) == value: target.send(d) @coroutine def printbus(): while True: bus = (yield) print "%(route)s,%(id)s,\"%(direction)s\"," \ "%(latitude)s,%(longitude)s" % bus if __name__ == '__main__': xml.sax.parse('bus.xml', Bushandler(buses_to_dict(cothread.threaded(direction_filter('route', '22', printbus())))))
true
932e994369fccd3748e6901ec7fdb1d79328facc
Python
joakinnoble/Datossimplesenpython
/calculodepreciovalor.py
UTF-8
740
3.953125
4
[]
no_license
#Una juguetería tiene mucho éxito en dos de sus productos: payasos y muñecas. Se venden por correo y la empresa de logística, les cobra por peso de cada paquete, entonces deben calcular el peso de los payasos y muñecas que saldrán en cada paquete. Cada payaso pesa (112g), y cada muñeca (75g.) Escribir un programa que lea el número de payasos y muñecas vendidos en el último pedido y calcule el peso total del paquete que será enviado. peso_payaso = 112 peso_muñeca = 75 payasos = int(input("Introduce el número de payasos a enviar: ")) muñecas = int(input("Introduce el número de muñecas a enviar: ")) peso_total = peso_payaso * payasos + peso_muñeca * muñecas print("El peso total del paquete es " + str(peso_total))
true
a1de294760fca60e164983276a5919ef3f6f258b
Python
tcoatale/cnn_framework
/preprocessing/datasets/pn/sequence_parser.py
UTF-8
1,864
3.015625
3
[]
no_license
import os import pandas as pd from preprocessing.datasets.pn.metadata_parser import MetadataParser from preprocessing.datasets.pn.segment_parser import SegmentParser class SequenceParser: def __init__(self, sequence, app_raw_data_root): self.sequence = sequence self.app_raw_data_root = app_raw_data_root def parse_metadata(self): metadata_parser = MetadataParser(self.sequence, self.app_raw_data_root) metadata_parser.process_segmentation_data() self.segmentation_data = metadata_parser.segmentation_data def parse_segmentation_line(self, segmentation_line): segment_parser = SegmentParser(segmentation_line, self.app_raw_data_root) df = segment_parser.run() return [df] def get_full_dataset(self): frames = self.segmentation_data.apply(self.parse_segmentation_line, axis=1) frames = frames.tolist() frames = list(map(lambda f: f[0], frames)) full_df = pd.concat(frames) return full_df def parse_sequence(self): self.parse_metadata() path = os.path.join(self.app_raw_data_root, self.sequence + '.csv') full_df = self.get_full_dataset() full_df.to_csv(path, index=False) #%% ''' class Infix: def __init__(self, function): self.function = function def __ror__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __or__(self, other): return self.function(other) def __rlshift__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __rshift__(self, other): return self.function(other) def __call__(self, value1, value2): return self.function(value1, value2) pip=Infix(lambda x,f: f(x)) #%% def square(x): return x**2 def minusone(x): return x-1 def my_pip(x): return x |pip| square |pip| minusone my_pip(2) #%% '''
true
75e546e4dc3563564ff4e77b2c1d7798e95ae4a0
Python
manoj24vvr/Vision-AI-TaskPhase
/Task-1/tic-tac-toe.py
UTF-8
4,163
3.46875
3
[]
no_license
# Import required libraries. import numpy as np import pygame import math ROWS = 3 COLUMNS = 3 # write the RGB colour code for required colours before hand, so it won't be necessary to use the colour code every time it is required. WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) BLUE = (0,255,0) WIDTH = 600 HEIGHT = 600 SIZE = (WIDTH,HEIGHT) # Initializing all the modules and functions of the Pygame library. pygame.init() # Initialize a board(Display screen) for the game. board = np.zeros((ROWS,COLUMNS)) window = pygame.display.set_mode(SIZE) pygame.display.set_caption("tic tac toe") window.fill(WHITE) # Importing the circle and cross images to include in the game. CIRCLE = pygame.image.load("circle.png") CROSS = pygame.image.load("cross.png") # Write all the functions seperately for a better understanding while referring in future. def mark(row, col, player): board[row][col] = player def is_valid_mark(row,col): return board[row][col] == 0 def is_board_full(): for c in range(COLUMNS): for r in range(ROWS): if board[r][c] == 0: return False return True def draw_board(): for c in range(COLUMNS): for r in range(ROWS): if board[r][c]==1: window.blit(CIRCLE,((c*200)+50,(r*200)+50)) elif board[r][c]==2: window.blit(CROSS,((c*200)+50,(r*200)+50)) pygame.display.update() def draw_lines(): pygame.draw.line(window,BLACK,(200,0),(200,600),10) pygame.draw.line(window,BLACK,(400,0),(400,600),10) pygame.draw.line(window,BLACK,(0,200),(600,200),10) pygame.draw.line(window,BLACK,(0,400),(600,400),10) def is_winning_move(player): if player == 1: winning_colour =BLUE else: winning_colour = RED for r in range(ROWS): if board[r][0] == player and board[r][1] ==player and board[r][2] == player: pygame.draw.line(window,winning_colour,(10,(r*200)+100),(WIDTH-10, (r*200)+100),10) return True for c in range(COLUMNS): if board[0][c] == player and board[1][c] ==player and board[2][c] == player: pygame.draw.line(window,winning_colour,((c*200)+100,10),(WIDTH-10, (c*200)+100),10) return True if board[0][0] == player and board[1][1] ==player and board[2][2] == player: pygame.draw.line(window,winning_colour,(10,10),(WIDTH-10, HEIGHT-10)) return True if board[2][0] == player and board[1][1] ==player and board[0][2] == player: pygame.draw.line(window,winning_colour,(10,HEIGHT-10),(WIDTH-10,10)) return True game_over = False Turn = 0 draw_lines() pygame.display.update() pygame.time.wait(2000) while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.MOUSEBUTTONDOWN: print(event.pos) if Turn % 2 == 0: #player 1 row = math.floor(event.pos[1]/200) col = math.floor(event.pos[0]/200) if is_valid_mark(row,col): mark(row,col,1) if is_winning_move(1): game_over = True else: Turn -= 1 else: #player 2 row = math.floor(event.pos[1]/200) col = math.floor(event.pos[0]/200) if is_valid_mark(row,col): mark(row,col,2) if is_winning_move(2): game_over = True else: Turn -= 1 Turn += 1 print(board) draw_board() if is_board_full(): game_over = True if game_over==True: print("Game Over") pygame.time.wait(2000) board.fill(0) window.fill(WHITE) draw_lines() draw_board() game_over = False pygame.display.update()
true
0bb3a1f58821933a3295d26420df10e34e70cec4
Python
janFrancoo/Python-Projects
/Image Similarity/image_similarity.py
UTF-8
2,021
3.03125
3
[]
no_license
import cv2 import argparse import numpy as np from skimage.measure import compare_ssim def mean_squared_error(image_a, image_b): if image_a.shape[0] != image_b.shape[0] or image_a.shape[1] != image_b.shape[1]: raise Exception("Image dimensions are not same") return np.sum((image_a.astype("float32") - image_b.astype("float32")) ** 2) / float(image_a.shape[0] * image_b.shape[1]) def show_result(image_a, image_b, title): cv2.imshow(title, np.hstack([image_a, image_b])) cv2.waitKey(0) cv2.imwrite("data/mse_12580_ssim_0_115.jpg", np.hstack([image_a, image_b])) ap = argparse.ArgumentParser() ap.add_argument("-i", "--image_original", required=True, help="Path of the image one") ap.add_argument("-t", "--image_target", required=True, help="Path of the image two") ap.add_argument("-s", "--show", help="A boolean value that allows image to show") ap.add_argument("-m", "--method", help="structural_similarity or mean_squared_error") args = vars(ap.parse_args()) show = True if args["show"] is not None and args["show"] == "True" else False image_original = cv2.imread(args["image_original"], 0) image_target = cv2.imread(args["image_target"], 0) if args["method"] is None: mse = mean_squared_error(image_original, image_target) ssim = compare_ssim(image_original, image_target) print("MSE:", mse, "SSIM:", ssim) if show: show_result(image_original, image_target, "MSE: " + str(mse) + " SSIM: " + str(ssim)) elif args["method"] == "mean_squared_error": mse = mean_squared_error(image_original, image_target) print("MSE:", mse) if show: show_result(image_original, image_target, "MSE: " + str(mse)) elif args["method"] == "structural_similarity": ssim = compare_ssim(image_original, image_target) print("SSIM:", ssim) if show: show_result(image_original, image_target, "SSIM: " + str(ssim)) else: raise Exception("Unknown method")
true
ae8ca30f44ced4aa27a22ee5360071d899ab7f5d
Python
jcusick13/comp135
/hw3/ann_test.py
UTF-8
8,242
3.09375
3
[]
no_license
# ann_test.py import unittest from ann import * class TestAnnFunctions(unittest.TestCase): # # Node.__init__() # def test_node_weight_init(self): """Ensures weights are only initialized for a node when passed in an input value. """ n = Node(value=2.0) self.assertEqual(n.weights, None) def test_node_weight_range_min(self): """Ensures random weight values are initialized within the correct range. """ n = Node(inputs=6) for i in n.weights: self.assertGreaterEqual(i, -0.1) def test_node_weight_range_max(self): """Ensures random weight values are initialized within the correct range. """ n = Node(inputs=3) for i in n.weights: self.assertLess(i, 0.1) # # Node.update_value() # def test_update_value(self): """Ensures node output value is correctly calculated.""" n = Node(inputs=2) # Override weights to static value for reproducibility n.weights = [1, 1] n.update_value([2, 3]) self.assertEqual(round(n.value, 3), 0.993) # # Node._sigmoid() # def test_sigmoid_convert_int(self): """Ensures output is the same regardless if input is given as int or float. """ n = Node() self.assertEqual(n._sigmoid(5), n._sigmoid(5.0)) # # Node._sigmoid_p() # def test_sigmoid_p_output(self): """Ensures correct output of sigmoid derivative.""" n = Node() self.assertEqual(round(n._sigmoid_p(0.993), 3), 0.007) # # Node._delta_n() # def test_delta_n_output(self): """Ensures correct output of delta value for nodes in the network output layer. """ n = Node(value=0.823) self.assertEqual(round(n._delta_n(0), 3), 0.120) # # Node._delta_i() # def test_delta_i_output_multi(self): """Ensures correct output of delta value for nodes within a hidden layer in the network that have multiple nodes in the k-th layer. Node is also first node in its layer. """ # Current node n = Node(value=0.993) # K-layer nodes k1 = Node(value=0.767) k1.delta = 0.021 k1.weights = [0.6, 0.6] k2 = Node(value=0.767) k2.delta = 0.021 k2.weights = [0.6, 0.6] # K-layer k = Layer(0) k.nodes.append(k1) k.nodes.append(k2) self.assertEqual(round(n._delta_i(k, 0), 6), 0.000175) def test_delta_i_output_single(self): """Ensures correct output of the delta value for nodes within a hidden layer in the network that have a single node in the k-th layer. Node is last node in its layer. """ # Current node n = Node(value=0.767) # K-layer node k1 = Node(value=0.823) k1.delta = 0.120 k1.weights = [0.2, 1.0] # K-layer k = Layer(0) k.nodes.append(k1) self.assertEqual(round(n._delta_i(k, 1), 3), 0.021) # # Node.update_weight() # def test_node_update_weight(self): """Ensures correct output during weight update process.""" n = Node(value=0.823) n.weights = [1.0, 1.0] n.delta = 0.120 eta = 0.1 x_j = 0.767 n.update_weight(eta, x_j, 0) weight = n.weights[0] self.assertEqual(round(weight, 4), 0.9908) # # NeuralNet.propagate_forward() # def test_propagate_forward(self): """Ensures correct final network output of forward propagation of x_i values. """ nn = NeuralNet(0, 0, '', '', blank=True) nn.create_net(2, 1, 2, 2) # Override weights to static value for reproducibility for node in nn.layers[2].nodes: node.weights = [0.6, 0.6] for node in nn.layers[3].nodes: node.weights = [1.0, 1.0] nn.propagate_forward([2, 3], test=True) model_output = nn.layers[-1].nodes[0].value self.assertEqual(round(model_output, 3), 0.823) def test_propagate_forward_no_hidden(self): """Ensures correct output when the network consists of a single input and output layer i.e. - no hidden layers. """ nn = NeuralNet(0, 0, '', '', blank=True) nn.create_net(2, 1, 0, 0) for node in nn.layers[-1].nodes: node.weights = [1.0, 1.0] nn.propagate_forward([2, 3], test=True) model_output = nn.layers[-1].nodes[0].value self.assertEqual(round(model_output, 3), 0.993) # # NeuralNet.propagate_backward() # def test_propagate_backward_last_hidden(self): """Ensures correct weight updates are made to the final (closest to output layer) hidden layer. """ nn = NeuralNet(0, 0, '', '', blank=True) nn.create_net(2, 1, 2, 2) nn.eta = 0.1 # Override weights to static value for reproducibility for node in nn.layers[2].nodes: node.weights = [0.6, 0.6] for node in nn.layers[3].nodes: node.weights = [1.0, 1.0] # Walk forward nn.propagate_forward([2, 3], test=True) # Walk backward nn.propagate_backward([0]) test_weight = nn.layers[-1].nodes[0].weights[0] self.assertEqual(round(test_weight, 4), 0.9901) def test_propagate_backward_first_hidden(self): """Ensures correct weight updates are made to the first (closest to input layer) hidden layer. """ nn = NeuralNet(0, 0, '', '', blank=True) nn.create_net(2, 1, 2, 2) nn.eta = 0.1 # Override weights to static value for reproducibility for node in nn.layers[2].nodes: node.weights = [0.6, 0.6] for node in nn.layers[3].nodes: node.weights = [1.0, 1.0] # Walk forward nn.propagate_forward([2, 3], test=True) # Walk backward nn.propagate_backward([0]) test_weight = nn.layers[1].nodes[0].weights[0] self.assertEqual(round(test_weight, 6), 0.999983) # # NeuralNet.update_weights() # def test_net_weight_update(self): """Ensures correct weight to output node after walking through the network forwards and backwards once. """ nn = NeuralNet(0, 0, '', '', blank=True) nn.create_net(2, 1, 2, 2) nn.eta = 0.1 # Override weights to static value for reproducibility for node in nn.layers[2].nodes: node.weights = [0.6, 0.6] for node in nn.layers[3].nodes: node.weights = [1.0, 1.0] nn.update_weights([2, 3], [0], test=True) test_weight = nn.layers[-1].nodes[0].weights[0] self.assertEqual(round(test_weight, 4), 0.9901) # # NeuralNet.assign_output() # def test_find_highest_value_node_last(self): """Ensures that the last output node is correctly selected for prediction. """ nn = NeuralNet(0, 0, '', '', blank=True) nn.create_net(2, 2, 2, 2) nn.eta = 0.1 # Override weights to static value for reproducibility for node in nn.layers[2].nodes: node.weights = [0.6, 0.6] nn.layers[3].nodes[0].weights = [0.0, 0.0] nn.layers[3].nodes[1].weights = [1.0, 1.0] val = nn.assign_output([2, 3], test=True) self.assertEqual(val, '01') def test_find_highest_value_node_first(self): """Ensures that the first output node is correctly selected for prediction. """ nn = NeuralNet(0, 0, '', '', blank=True) nn.create_net(2, 2, 2, 2) nn.eta = 0.1 # Override weights to static value for reproducibility for node in nn.layers[2].nodes: node.weights = [0.6, 0.6] nn.layers[3].nodes[0].weights = [1.0, 1.0] nn.layers[3].nodes[1].weights = [0.0, 0.0] val = nn.assign_output([2, 3], test=True) self.assertEqual(val, '10') if __name__ == '__main__': unittest.main()
true
aab732f5fc9b2a1c7fa9e06c450d4e118fa4f187
Python
irmadong/info303
/INFO303-Week2/Exercise_Expression.py
UTF-8
4,041
4.34375
4
[]
no_license
#problem1 hour = int(input("Enter the hour: " )) rate = int(input("Enter the rate: ")) pay = hour*rate print("Pay:{}".format(pay)) #problem2 number1 = int(input("Enter the first numnber: " )) number2 = int(input("Enter the second number: " )) number3 = number1+number2 print("The total is {}".format(number3)) #problem3 number1 = int(input("Enter the first numnber: " )) number2 = int(input("Enter the second number: " )) number3 = int(input("Enter the third numnber: " )) total = number1+number2+number3 print("The answer is {}".format(total)) #problem4 start = int(input("How many slices of pizze did you start with? " )) eaten = int(input("How many slices of pizza have you had?")) left = start-eaten print("The number of slices of the pizza left {}".format(left)) #problem 5 name = input('Enter your name:') age = int(input('Enter your age (integer):')) next_age = age+1 print("{name} will be {age}".format(name = name, age = next_age)) #problem 6 bill =float(input("Enter the total price:")) num_ppl = int(input("Enter the number of diners")) per_person = bill/num_ppl print("Each person has to pay :${}".format(per_person)) #Problem 7 days = float(input('Enter the total number of days:')) hours = days * 24 minutes = hours * 60 seconds = minutes * 60 print('There are {a} hours, {b} minutes, and {c} seconds in {d} days!'.format(a=hours,b=minutes,c=seconds,d=days)) #Problem 8 kg = float(input("Please enter a weight in kilogram:")) pound = kg*2.204 print("{kg} KG is {pound} Pound".format(kg = kg,pound=pound)) #Problem9 larger=int(input('Enter a number over 100: ')) smaller =int(input('Enter a number under 10: ')) answer = larger//smaller print(smaller,'goes into', larger,answer,'times') #problem 10 full = input("What's your full name?") length = len(full) print("The length of the full name is{}".format(length)) #problem 11 first = input('Enter your first name:') last= input('Enter your last name:') fullname = first + ' ' + last length = len(fullname) print('Your full name is ' + fullname) print("The length is " + str(length)) #problem12 first = input('Enter your first name in lower case letters: ') last = input('Enter your last name in lower case letters: ') name = first.title() + ' ' + last.title() print('Your full name is ' + name +".") #problem13 song = input('What is the first line of the song? ') length = len(song) print("The length of the first line of the song is "+ str(length)) start = int(input('Enter a starting number: ')) end = int(input('Enter an ending number: ')) part = song[start:end] print("The line between {start} and {end} is {part}".format(start=start, end=end,part=part)) #problem14 word = input('Enter an english word: ') word = word.upper() print(word) #problem 15 num = float(input('Enter a number with lots of decimal places: ')) answer = num*2 print( 'two times of {num} is {answer} '.format(num =num,answer=answer)) num=round(num,2) answer=round(answer,2) print( 'two times of {num} is {answer} (in two decimal)'.format(num =num,answer=answer)) print(str(round(num,2)) + ' multiplied by 2 is: ' + str(round(answer,2))) #problem 16 import math num = int(input('Enter an integer number over 500: ')) answer = math.sqrt(num) print('The square root of', round(num,2), 'is', round(answer,2)) #problem 17 import math print(round(math.pi,5)) #problem 18 import math radius = int(input('Enter the radius of a circle:')) area = math.pi*(radius**2) print('The radius is :'+ str(radius)) print("The area of that circle is "+ str(area)) #problem 19 import math radius = int(input('Enter the radius of a cylinder:')) depth = int(input('Enter the depth of the cylinder:')) area = math.pi*(pow(radius,2)) volume = round(depth*area,3) print( 'The volume of a cylinder with a radius of {radius} and a depth of {depth} is{volume}'.format(radius = radius, depth = depth, volume = volume)) #problem20 num1 = int(input('Enter a number:')) num2 = int(input('Enter another number:')) ans1 = num1//num2 ans2=num1%num2 print(num1, 'divided', num2, 'is', ans1) print('The remaining is', ans2)
true
2ebe6ea165914f300e2d3bc1d5576656a435e8fc
Python
KeerthanBhat/NaturalDisaster
/natdis/FinalCode.py
UTF-8
1,057
2.546875
3
[ "MIT" ]
permissive
import tensorflow as tf from keras import optimizers from keras.models import load_model import numpy as np model = load_model('Model.h5') optimizer = tf.train.RMSPropOptimizer(0.002) model.compile(loss='mse', optimizer=optimizer, metrics=['accuracy']) #pridection = np.array([minitemp,maxitemp,windgust,wind9,wind3,humid9,humid3,pressure9,pressure3,temp9,temp3]) pridection = np.array([20.9,23.3,65,37,31,96,96,1006.8,1004.2,21.5,21.3]) #pridection = np.array([2,1,100,100,1,1,1,1,1,1,1]) mean = np.array([12.068963,23.009951,37.19739,13.88135,18.25159,67.70561,49.9628,911.645197,909.72206092,16.76982,21.128429]) std = np.array([6.47953722,7.41225215,16.68598056,9.01179628,9.14530111,20.95509877,22.34781323,310.98021687,309.95752359,6.71328472,7.64915217]) pridection = (pridection - mean) / std if (pridection.ndim == 1): pridection = np.array([pridection]) rainfall = model.predict(pridection) floods = (rainfall - 5) * 5 if (floods > 100): floods = 100 print(rainfall)
true
90bbf9560ec957caf325f79698f18a66f5c9c6ea
Python
gc13141112/predict_crop_yield
/process.py
UTF-8
4,289
2.75
3
[]
no_license
from sklearn.model_selection import train_test_split import os from image_to_input import get_input_data import pandas as pd import numpy as np import random import tensorflow as tf yield_csv = pd.read_csv('data_for_image_download.csv',header=None) output = [] hhid_list = [] for hhid, yld, lat, lon in yield_csv.values: output.append(yld) hhid_list.append(str(hhid)[:-2]) hhid_input = {} hhid_output = {} counter = 0 for file in os.listdir("image_data"): if file.endswith(".tif"): input_array = get_input_data("image_data/" + file) hhid_input[counter] = input_array hhid_output[counter] = output[counter] counter += 1 training_set_X = [] training_set_Y = [] testing_set_X = [] testing_set_Y = [] n_train = int(counter * 0.9) lst = list(range(counter)) for i in range(n_train): r_key = random.choice(lst) training_set_Y.append(hhid_output[r_key]) training_set_X.append(hhid_input[r_key]) lst.remove(r_key) for k in lst: testing_set_Y.append(hhid_output[k]) testing_set_X.append(hhid_input[k]) learning_rate = 0.01 l_train = len(training_set_Y) l_test = len(testing_set_Y) num_input = 350 n_hidden_1 = 64 n_hidden_2 = 64 # tf Graph input X = tf.placeholder("float", [None, num_input]) Y = tf.placeholder("float", [None, 1]) # Store layers weight & bias weights = { 'h1': tf.Variable(tf.random_normal([num_input, n_hidden_1])), 'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 'out': tf.Variable(tf.random_normal([n_hidden_2, 1])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'b2': tf.Variable(tf.random_normal([n_hidden_2])), 'out': tf.Variable(tf.random_normal([1])) } # Create model def neural_net(x): # Hidden fully connected layer with 256 neurons layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) # Hidden fully connected layer with 256 neurons layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2']) # Output fully connected layer with a neuron for each class out_layer = tf.matmul(layer_2, weights['out']) + biases['out'] return out_layer # Construct model prediction = neural_net(X) loss_op = tf.reduce_mean(tf.sqrt(tf.losses.mean_squared_error(Y, prediction))) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) train_op = optimizer.minimize(loss_op) # Evaluate model accuracy = tf.sqrt(tf.losses.mean_squared_error(Y, prediction)) # Initialize the variables (i.e. assign their default value) init = tf.global_variables_initializer() # Start training with tf.Session() as sess: # Run the initializer sess.run(init) display_step = 10 lst = list(range(n_train)) for step in range(0, 10000): sample = random.sample(lst, 20) batch_x = [] batch_y = [] for i in sample: batch_x.append(training_set_X[i]) batch_y.append(training_set_Y[i]) batch_x = np.array(batch_x) batch_y = np.array(batch_y).reshape((20,1)) # Run optimization op (backprop) sess.run(train_op, feed_dict={X: batch_x, Y: batch_y}) if step % display_step == 0 or step == 1: # Calculate batch loss and accuracy loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x, Y: batch_y}) print("Step " + str(step) + ", Minibatch Loss= " + \ "{:.4f}".format(loss) + ", Training Accuracy= " + \ "{:.3f}".format(acc)) for step in range(0, 10): sess.run(train_op, feed_dict={X: np.array(training_set_X), Y: np.array(training_set_Y).reshape((l_train, 1))}) loss, acc = sess.run([loss_op, accuracy], feed_dict={X: np.array(training_set_X), Y: np.array(training_set_Y).reshape((l_train, 1))}) print("Final Step " + str(step) + ", Minibatch Loss= " + \ "{:.4f}".format(loss) + ", Training Accuracy= " + \ "{:.3f}".format(acc)) print "Optimization Finished!" print "Testing Yields: ", testing_set_Y print "Predictions: ", prediction.eval(feed_dict={X: np.array(testing_set_X)}, session=sess) print "Testing Accuracy:", sess.run(accuracy, feed_dict={X: np.array(testing_set_X), Y: np.array(testing_set_Y).reshape((l_test, 1))})
true
1a9d2ce667bf83dfc8e8931276d7494a9bdaced2
Python
Code-Institute-Submissions/FlyHigh
/flyhighblog/errors/handlers.py
UTF-8
606
2.578125
3
[]
no_license
# Importing required flask methods and functions from flask import Blueprint, render_template # Creating Blueprint object errors = Blueprint('errors', __name__) # 404 error page route @errors.app_errorhandler(404) def error_404(error): return render_template('errors/404.html', title='404 error'), 404 # 403 error page route @errors.app_errorhandler(403) def error_403(error): return render_template('errors/403.html', title='403 error'), 403 # 500 error page route @errors.app_errorhandler(500) def error_500(error): return render_template('errors/500.html', title='500 error'), 500
true
0cf9071cacd31b7e780d4c293a158643dd0d5a78
Python
rbanffy/pingo
/experiments/rpi/gertboard/dad.py
UTF-8
4,233
2.859375
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
#!/usr/bin/python2.7 # Python 2.7 version by Alex Eames of http://RasPi.TV # functionally equivalent to the Gertboard dad test by Gert Jan van Loo # & Myra VanInwegen. Use at your own risk - I'm pretty sure the code is # harmless, but check it yourself. # This will not work unless you have installed py-spidev (see README.txt file) # spi must also be enabled on your system import spidev import sys # reload spi drivers to prevent spi failures import subprocess from time import sleep unload_spi = subprocess.Popen('sudo rmmod spi_bcm2708', shell=True, stdout=subprocess.PIPE) start_spi = subprocess.Popen('sudo modprobe spi_bcm2708', shell=True, stdout=subprocess.PIPE) board_type = sys.argv[-1] print board_type def dac_write(DAC_value): # this functions as an SPI driver for the DAC spi.open(0,1) # Gertboard DAC is on SPI channel 1 (CE1 - aka GPIO7) bin_data_bits = int(bin(DAC_value)[2:]) # it converts your number 0-255 into two binary bin_data_bits = "{0:08d}".format(bin_data_bits) # bytes and writes them to the SPI port via spidev whole_list = [dac_channel,0,gain,1,bin_data_bits,'0000'] # assemble whole 16 bit string in a list final_bitstring = ''.join( map( str, whole_list ) ) # join it all in one 16 bit binary string byte1 = int(final_bitstring[0:8],2) # split into two 8 bit bytes byte2 = int(final_bitstring[8:16],2) # and convert to denary for spidev r = spi.xfer2([byte1,byte2]) # send spidev the two denary numbers def get_adc(channel): # read SPI data from MCP3002 chip spi.open(0,0) # Gertboard ADC is on SPI channel 0 (CE0 - aka GPIO8) if ((channel > 1) or (channel < 0)): # Only 2 channels 0 and 1 else return -1 return -1 r = spi.xfer2([1,(2+channel)<<6,0]) # these two lines are an spi driver for the ADC, they send three bytes ret = ((r[1]&31) << 6) + (r[2] >> 2) # and receive back three. This line extracts the 0-1023 ADC reading return ret # set some variables. We can set more than one on a line if values the same dac_channel = gain = 1 # dac_channel is channel B on the dac (not SPI channel) gain is the DAC gain adc_channel = DAC_value = 0 # refers to channel A on the adc, also set intial DAC_value = 0 char='#' # set the bar chart character spi = spidev.SpiDev() # spidev is the python 'wrapper' enabling us to 'speak' to the SPI port print("These are the connections for the digital to analogue to digital test:") if board_type == "m": print("jumper connecting GPIO 8 to CSA") print("jumper connecting GPIO 7 to CSB") print("jumper connecting DA1 to AD0 on the A/D D/A header") else: print("jumper connecting GP11 to SCLK") print("jumper connecting GP10 to MOSI") print("jumper connecting GP9 to MISO") print("jumper connecting GP8 to CSnA") print("jumper connecting GP7 to CSnB") print("jumper connecting DA1 on J29 to AD0 on J28") sleep(3) raw_input("When ready hit enter.\n") print "dig ana" for DAC_value in range(0,257,32): # go from 0-256 in steps of 32 (note the loop stops at 256 not 257) if DAC_value==256: DAC_value=255 # DAC can only accept 0-255, but that's not divisible by 32, so we 'cheat' dac_write(DAC_value) adc_value = get_adc(adc_channel) adc_string = "{0:04d}".format(adc_value) # read ADC and make output a 4 character string print "%s %s %s" % ("{0:03d}".format(DAC_value), adc_string, (adc_value)/16 * char) for DAC_value in range(224,-1,-32): dac_write(DAC_value) adc_value = get_adc(adc_channel) adc_string = "{0:04d}".format(adc_value) # read ADC and make output a 4 character string print "%s %s %s" % ("{0:03d}".format(DAC_value), adc_string, (adc_value)/16 * char) r = spi.xfer2([144,0]) # switch off DAC channel 1 (B) = 10010000 00000000 [144,0]
true
4116facf3a82b4f9455241c97aeb3bd26f1a542c
Python
Simonhong111/SIF
/SIFProject/GridGen.py
UTF-8
9,541
2.953125
3
[]
no_license
""" 配置湖北省所对应的格网信息(CMG) # CMG 0.05 x 0.05 degree # """ import os import numpy as np from osgeo import gdal,ogr,osr from GetPointFromShp import * class GridDefination(object): def __init__(self): # 最大/最小的经纬度,确定CMG格网划分 self.MAX_LONGITUDE = 180 self.MIN_LONGITUDE = -180 self.MAX_LATITUDE = 90 self.MIN_LATITUDE = -90 # 自定义经纬度,确定研究范围在CMG中的格网 self.USER_MAX_LONGITUDE = 180 self.USER_MIN_LONGIUDE = -180 self.USER_MAX_LATITUDE = 90 self.USER_MIN_LATITUDE = -90 # 经纬度间隔 self.LON_INTERVAL =0.05 self.LAT_INTERVAL =0.05 self.CMGGRID = None def setUserExtent(self,extent): """ :param extent:(ulx,lrx,lry,uly) :return: """ self.USER_MAX_LONGITUDE = extent[1] self.USER_MIN_LONGIUDE = extent[0] self.USER_MAX_LATITUDE = extent[3] self.USER_MIN_LATITUDE = extent[2] def user_grid(self): """ 自定义格网范围 计算用户自定义范围,对应于CMG格网的范围 :return: 返回格网配置 """ # 网格ID位置 user_min_Lon_id = int(np.floor((self.USER_MIN_LONGIUDE - self.MIN_LONGITUDE)/self.LON_INTERVAL)) user_max_Lon_id = int(np.ceil((self.USER_MAX_LONGITUDE - self.MIN_LONGITUDE)/self.LON_INTERVAL)) user_min_Lat_id = int(np.floor((self.USER_MIN_LATITUDE - self.MIN_LATITUDE) / self.LAT_INTERVAL)) user_max_Lat_id = int(np.ceil((self.USER_MAX_LATITUDE - self.MIN_LATITUDE) / self.LAT_INTERVAL)) for lat in range(user_min_Lat_id, user_max_Lat_id): for lon in range(user_min_Lon_id, user_max_Lon_id): #(最小经度,最小维度,最大经度,最大纬度,小格网id) ulx = lon * self.LON_INTERVAL + self.MIN_LONGITUDE lrx = ulx + self.LON_INTERVAL lry = lat * self.LAT_INTERVAL + self.MIN_LATITUDE uly = lry + self.LON_INTERVAL # print("ulx,lrx,uly,lry",ulx,lrx,uly,lry) extent = yield (ulx,uly,lrx,lry) # 生成一个方形的里面有好多格网的矩阵 从最后一行开始编号 def GridToalNum(self): """ 定义给定大小的CMG格网 :return:格网配置,包括范围,经纬度,编号等 """ lat_grid_num = (self.MAX_LATITUDE-self.MIN_LATITUDE)/self.LAT_INTERVAL lon_grid_num = (self.MAX_LONGITUDE-self.MIN_LONGITUDE)/self.LON_INTERVAL # 判断格网是否是整数 if not (lat_grid_num.is_integer() and lon_grid_num.is_integer()): raise Exception("please guarantee that the lon/lat_interval can divide 360 or 180") # 返回格网个数沿经度方向lon_grid_num, 沿着纬度方向lat_grid_num return lon_grid_num,lat_grid_num def getGrid(self,shapefile): """ 根据h湖北省行政区划图获取栅格,该grid 会标记有经纬度范围,以及ID,根据从下到上,从左到右顺序 :param shapefile: 湖北省行政区划图矢量,记住,使用之前先做特征融合,只要外部边界 :return: 返回grid 字典集合,字典格式{ID:(ulx,uly,lrx,lry)} """ # 打开湖北省矢量 driver = ogr.GetDriverByName('ESRI Shapefile') dataSource = driver.Open(shapefile, 0) # 记住这里值获取一个layer和第一个feature, # 所以正如上面所说,需要将湖北省矢量都聚合了,只要外部边界,只有一个特征, # 在envi或者arcgis上面做 layer = dataSource.GetLayer() # 获取投影信息 self.EPSG = int(layer.GetSpatialRef().GetAuthorityCode("GEOGCS")) feature = layer.GetNextFeature() # 湖北省矢量边界的轮廓线 poly_geom = feature.geometry() # 湖北省矢量边界的外接矩形 extent = layer.GetExtent() print("湖北省外界矩形",extent) # 根据extent 设定 研究区域范围,减小计算量 self.setUserExtent(extent) # print("extent",extent) # print(poly_geom) gridarr = [] gridId = 0 for subgrid in self.user_grid(): # 用湖北省矢量边界轮廓线生成一个geometry格式的poly ring = ogr.Geometry(ogr.wkbLinearRing) ring.AddPoint(subgrid[0],subgrid[1]) ring.AddPoint(subgrid[2],subgrid[1]) ring.AddPoint(subgrid[2],subgrid[3]) ring.AddPoint(subgrid[0],subgrid[3]) ring.AddPoint(subgrid[0],subgrid[1]) poly = ogr.Geometry(ogr.wkbPolygon) poly.AddGeometry(ring) gridId += 1 if poly.Intersect(poly_geom): #记录下这个在湖北省境内的网格在原来矩形网格中的位置 temp ={"ID":str(gridId),"extent":subgrid} gridarr.append(temp) temp = None ring = None poly = None return gridarr,self.user_grid() def saveGrid(self,shp_path,grid_path): # 获取湖北省境内的网格 mGrid,_ = self.getGrid(shp_path) outDriver = ogr.GetDriverByName('ESRI Shapefile') if os.path.exists(grid_path): os.remove(grid_path) outDataSource = outDriver.CreateDataSource(grid_path) srs = osr.SpatialReference() srs.ImportFromEPSG(self.EPSG) outLayer = outDataSource.CreateLayer(grid_path, srs,geom_type=ogr.wkbPolygon) featureDefn = outLayer.GetLayerDefn() idField = ogr.FieldDefn("Position", ogr.OFTInteger) outLayer.CreateField(idField) for subgrid in mGrid: ring = ogr.Geometry(ogr.wkbLinearRing) ring.AddPoint(subgrid["extent"][0], subgrid["extent"][1]) ring.AddPoint(subgrid["extent"][2], subgrid["extent"][1]) ring.AddPoint(subgrid["extent"][2], subgrid["extent"][3]) ring.AddPoint(subgrid["extent"][0], subgrid["extent"][3]) ring.AddPoint(subgrid["extent"][0], subgrid["extent"][1]) poly = ogr.Geometry(ogr.wkbPolygon) poly.AddGeometry(ring) # 生成字段记录下网格在初始湖北省外结矩的位置 outFeature = ogr.Feature(featureDefn) outFeature.SetGeometry(poly) outFeature.SetField("Position", subgrid["ID"]) outLayer.CreateFeature(outFeature) outFeature = None outDataSource = None def validGrid(self,shp_path,tile_path,output): """ :param shp_path: 湖北省矢量 :param tile_path: 湖北省Sentinel-2 遥感影像id 矢量 :param output: 有效npz :return: 格王对应哪些遥感影像id """ mGrid,_ = self.getGrid(shp_path) driver = ogr.GetDriverByName('ESRI Shapefile') dataSource = driver.Open(tile_path, 0) # 0 means read-only. 1 means writeable. if dataSource is None: print("Can not open the {}".format(tile_path)) layer = dataSource.GetLayer() if os.path.exists(output): os.remove(output) gridTilePairs = [] for subgrid in mGrid: ring = ogr.Geometry(ogr.wkbLinearRing) ring.AddPoint(subgrid["extent"][0], subgrid["extent"][1]) ring.AddPoint(subgrid["extent"][2], subgrid["extent"][1]) ring.AddPoint(subgrid["extent"][2], subgrid["extent"][3]) ring.AddPoint(subgrid["extent"][0], subgrid["extent"][3]) ring.AddPoint(subgrid["extent"][0], subgrid["extent"][1]) poly = ogr.Geometry(ogr.wkbPolygon) poly.AddGeometry(ring) gridTile = {} gridTile["gridId"] = subgrid["ID"] gridTile["etRing"] = [subgrid["extent"][0], subgrid["extent"][1],\ subgrid["extent"][2], subgrid["extent"][1],\ subgrid["extent"][2], subgrid["extent"][3],\ subgrid["extent"][0], subgrid["extent"][3],\ subgrid["extent"][0], subgrid["extent"][1]] iFeature = 0 # print(subgrid["ID"]) tilesintersectwithgrid = [] for feature in layer: geom = feature.geometry() if poly.Intersect(geom): tilesintersectwithgrid.append(feature.GetFieldAsString("Name")) layer.ResetReading() gridTile["valTiles"] = tilesintersectwithgrid # 每个格网对应了几个哨兵-2 的ID # print(subgrid["ID"], gridTile) gridTilePairs.append(gridTile) ID =[gridtile["gridId"] for gridtile in gridTilePairs] ValTile = [gridtile["valTiles"] for gridtile in gridTilePairs] EtRing =[gridtile["etRing"] for gridtile in gridTilePairs] kwargs = {"gridId": ID, "Tile": ValTile,"EtRing":EtRing} # 分别是格网ID 相交的sentinel-2 的ID 以及 格网范围 # print(ValTile) np.savez(output,**kwargs)
true
137cd79bf4fcca229b3412c3c88f72c98b92011e
Python
a-zankov/api_testing_with_python
/apitest/tests/customers/test_create_customers_smoke.py
UTF-8
2,221
2.765625
3
[]
no_license
import pytest import logging as logger from apitest.src.utilities.genericUtilities import generate_random_email_and_password from apitest.src.helpers.customers_helper import CustomerHelper from apitest.src.dao.customers_dao import CustomersDAO from apitest.src.utilities.requestsUtility import RequestsUtility @pytest.mark.customers @pytest.mark.tcid29 def test_create_customer_only_email_password(): logger.info("TEST: Create new customer with email and password only") random_info = generate_random_email_and_password() logger.info(random_info) email = random_info['email'] password = random_info['password'] #create payload # payload = {'email': email, 'password': password} #make the call cust_obj = CustomerHelper() cust_api_info = cust_obj.create_customer(email=email, password=password) assert cust_api_info['email'] == email, f"Create customer api return wrong email. Email: {email}" assert cust_api_info['first_name'] == '', "Create customer api return value for first name" \ "but it should be empty" # verify customer is created in database cust_dao = CustomersDAO() cust_info = cust_dao.get_customer_by_email(email) id_in_api = cust_api_info['id'] id_in_db = cust_info[0]['ID'] ###Verify che za prikol assert id_in_api == id_in_db, 'Create customer response "id" not same as "ID" in database' \ f'Email: {email}' @pytest.mark.customers @pytest.mark.tcid47 def test_create_customer_fail_for_existing_email(): #get existing email from db cust_dao = CustomersDAO() existing_cust = cust_dao.get_random_customer_from_db() existing_email = existing_cust[0]['user_email'] #call the API req_helper = RequestsUtility() payload = {"email": existing_email, "password": "Password1"} cust_api_info = req_helper.post(endpoint='customers', payload=payload, expected_status_code=400) assert cust_api_info['code'] == "registration-error-email-exists",\ f"Create customer with existing email error code is not correct. Expected: registration-error-email-exists," \ "Actual: {cust_api_info['code']}"
true
ce419fc481070e006c6063f6ad361234d604eddf
Python
myevertime/Python-Programs
/LettertoNum.py
UTF-8
1,308
4.25
4
[]
no_license
# Module 2 - Practice / letter to Number Function def let_to_num() : phone_letters = [' ',"","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"] letter = input("Enter a single letter, space, or empty string: ") key = 0 while key < 10 : if letter == "" : return 1 break elif letter.lower() in phone_letters[key].lower() : return key else : key += 1 return("Not found") print(let_to_num()) # Module 2 - Practice / reverse some_numbers = [1,2,3,4,5,6,7,8,9,11,22,33,44,55,66,77] new_string = [] while len(some_numbers) != 0 : pop_num = some_numbers.pop(0) new_string.insert(0,pop_num) print(new_string) # Module 2 - End of Assignment set_list = ["fish", "trees", "books", "movies", "songs"] while len(set_list) != 0 : string = input("Enter a string or \"quit\" if you wanna quit: ") if string.lower() == "quit" : break else : def list_o_matic() : if string == "" : set_list.pop() print("pop msg") elif string in set_list : set_list.remove(string) print("remove msg") else : set_list.append(string) print("append msg") list_o_matic()
true
b10692492cedbe867d93aad6c5a65717b062fe1c
Python
lymanhurd/notakto
/cribbage/deck.py
UTF-8
1,476
3.53125
4
[]
no_license
"""Class representing a deck of cards.""" import logging import random from time import time from typing import List, Optional, Tuple class Deck(object): def __init__(self, seed: Optional[str] = None): self.seed = seed or str(time()) logging.debug('seed = %s', self.seed) random.seed(self.seed) self.deck = list(range(52)) self.shuffle() self.idx = 0 def shuffle(self) -> None: random.shuffle(self.deck) self.idx = 0 def deal(self, n: int) -> List[int]: cards = self.deck[self.idx: self.idx + n] self.idx += n return cards SUITS: List[str] = ['C', 'D', 'H', 'S'] CARD_NAMES: List[str] = ['A'] + [str(i) for i in range(2, 11)] + ['J', 'Q', 'K'] DECK: List[str] = [n + s for n in CARD_NAMES for s in SUITS] JACK: int = 10 def card_number(name: str) -> int: return -1 if not name else DECK.index(name.upper()) def card_points(card: int) -> int: return min(10, 1 + card // 4 % 13) def suit(card: int) -> int: return card % 4 def value(card: int) -> int: return card // 4 % 13 def seq_string(seq: List[int], sep: str = ' ') -> str: return sep.join([DECK[c] for c in seq]) def hand_string(hand: List[int], sep: str = ' ') -> str: return seq_string(sorted(hand), sep) def random_draw() -> Tuple[int, int]: c1, c2 = 0, 0 while value(c1) == value(c2): c1, c2 = random.randint(0, 51), random.randint(0, 51) return c1, c2
true
71605477e34a0668a28fdf1a54fdf8ef4389e2c7
Python
Saptaparna10/Information-Retrieval
/Retrieval/Task2.py
UTF-8
14,284
2.59375
3
[]
no_license
import io import glob import operator import os import traceback from pprint import pprint from math import sqrt from math import log CURRENT_DIRECTORY = os.getcwd() # Path of corpus INPUT_FOLDER = path = os.path.join(CURRENT_DIRECTORY,'corpus') # Path where BM25 scores will be stored OUTPUT_FOLDER_PATH = path = os.path.join(CURRENT_DIRECTORY,'doc_score_BM25') DOC_NAME ={} # mapping doc name and ids QUERY_ID = 0 AVDL = 0 # Average doc length number_of_Token = {} # Inverted index for unigram def inverted_index_for_unigram(): # term -> (docid,tf) inverted_index = {} # docid -> tf doc_id_tf_dict = {} #number_of_Token = {} try: doc_count=1 path = os.path.join(CURRENT_DIRECTORY,'corpus') for filename in glob.glob(os.path.join(path, '*.txt')): with file(filename) as f: document =f.read() file_name = str(filename).split ('corpus\\')[1][:-4] print "Generating index for " + file_name number_of_Token[file_name] = len(document.split()) for word in document.split(): if not inverted_index.has_key(word): doc_id_tf_dict = {file_name : 1} inverted_index[word] = doc_id_tf_dict elif inverted_index[word].has_key(file_name): doc_id_tf_dict = inverted_index[word] value = doc_id_tf_dict[file_name] value = value + 1 doc_id_tf_dict[file_name] = value else: doc_id_tf_dict = {file_name : 1} inverted_index[word].update(doc_id_tf_dict) doc_count = doc_count + 1 f.close() print "toeken count : " print number_of_Token total_num_of_docs = doc_count-1 except: print "Error in try block of inverted_index_for_unigram!" print traceback.format_exc() return inverted_index,total_num_of_docs #--------------------------------------------------------------------# #-------------------------HW3 Indexer functions----------------------# #--------------------------------------------------------------------# # def make_term_freq_table(inverted_index,ngram): # term_frequency = {} # for term in inverted_index: # frequency = 0 # doc_id_tf_dict = inverted_index[term] # for doc_id in doc_id_tf_dict: # frequency = frequency + doc_id_tf_dict[doc_id] # term_frequency[term] = frequency # sorted_term_frequency = sorted(term_frequency.items(), key=operator.itemgetter(1), reverse=True) # write_term_frequency_to_file(sorted_term_frequency,ngram) # return sorted_term_frequency # def write_term_frequency_to_file(term_frequency,ngram): # try: # print "Writing term frequency table..." # file_name= "term_frequency" + "_" + str(ngram) + ".txt" # file_term_frequency= open(file_name, 'w') # table_form = '{:<30}' * 2 # for term in term_frequency: # file_term_frequency.write(table_form.format(str(term[0]),str(term[1]))) # file_term_frequency.write("\n") # file_term_frequency.close() # except: # print "Error in try block of write_term_frequency_to_file!" # print traceback.format_exc() # def make_doc_freq_table(inverted_index,ngram): # document_freq = {} # for term in inverted_index: # document_list = [] # doc_dict = inverted_index[term] # for doc_id in doc_dict: # document_list.append(doc_id) # document_freq[term] = document_list # sorted_document_freq = sorted(document_freq.items(), key=operator.itemgetter(0)) # write_document_freq(sorted_document_freq, ngram) # return sorted_document_freq # # generates file with doc frequency table # def write_document_freq(document_freq, ngram): # try: # print "Writing document frequency table..." # file_name= "doc_freq_table" + "_" + str(ngram) + ".txt" # file_doc_freq_table= open(file_name, 'w') # for list in document_freq: # table_form_doc = '{:<10}' * 3 # list_length = len (list[1]) # file_doc_freq_table.write(table_form_doc.format((str(list[0])),(str(list[1])),(str(list_length)))) # file_doc_freq_table.write("\n") # file_doc_freq_table.close() # except: # print "Error in try block of write_doc_freq!" # print traceback.format_exc() # def inverted_index_for_bigram(): # # term -> (docid,tf) # inverted_index = {} # # docid -> tf # doc_id_tf_dict = {} # number_of_Token = {} # try: # directory_name = os.getcwd() # path = os.path.join(directory_name,'corpus') # for filename in glob.glob(os.path.join(path, '*.txt')): # with file(filename) as f: # document =f.read() # file_name = str(filename).split ('corpus\\')[1][:-4] # print "Generating index for " + file_name # words = document.split() # number_of_Token[file_name] = len(words)-1 # for i in range(len(words) - 1) : # word = words[i] + " " + words[i+1] # if not inverted_index.has_key(word): # doc_id_tf_dict = {file_name : 1} # inverted_index[word] = doc_id_tf_dict # elif inverted_index[word].has_key(file_name): # doc_id_tf_dict = inverted_index[word] # value = doc_id_tf_dict[file_name] # value = value + 1 # doc_id_tf_dict[file_name] = value # else: # doc_id_tf_dict = {file_name : 1} # inverted_index[word].update(doc_id_tf_dict) # f.close() # print "toeken count : " # print number_of_Token # except: # print "Error in try block of inverted_index_for_unigram!" # print traceback.format_exc() # return inverted_index # def inverted_index_for_trigram(): # # term -> (docid,tf) # inverted_index = {} # # docid -> tf # doc_id_tf_dict = {} # try: # directory_name = os.getcwd() # path = os.path.join(directory_name,'corpus') # for filename in glob.glob(os.path.join(path, '*.txt')): # with file(filename) as f: # document =f.read() # file_name = str(filename).split ('corpus\\')[1][:-4] # print "Generating index for " + file_name # words = document.split() # number_of_Token[file_name] = len(words)-2 # for i in range(len(words) - 2) : # word = words[i] + " " + words[i+1] + " " + words[i+2] # if not inverted_index.has_key(word): # doc_id_tf_dict = {file_name : 1} # inverted_index[word] = doc_id_tf_dict # elif inverted_index[word].has_key(file_name): # doc_id_tf_dict = inverted_index[word] # value = doc_id_tf_dict[file_name] # value = value + 1 # doc_id_tf_dict[file_name] = value # else: # doc_id_tf_dict = {file_name : 1} # inverted_index[word].update(doc_id_tf_dict) # f.close() # print "toeken count : " # print number_of_Token # except: # print "Error in try block of inverted_index_for_unigram!" # print traceback.format_exc() # return inverted_index # # generates file with doc frequency table # def write_inverted_index(inverted_index, ngram): # try: # print "Writing inverted index..." # file_name= "inverted_index" + "_" + str(ngram) + ".txt" # with open(file_name, 'wt') as out: # pprint(inverted_index, stream=out) # except: # print "Error in try block of write_doc_freq!" # print traceback.format_exc() #--------------------------------------------------------------------# #--------------------HW4 Retrival Model logic------------------------# #--------------------------------------------------------------------# def calculate_avdl(): try: sum = 0 for doc_id in number_of_Token: sum+=number_of_Token[doc_id] return (float(sum)/float(len(number_of_Token))) except Exception as e: print(traceback.format_exc()) def calculate_doc_bm25_score(query,inverted_index,total_num_of_docs): try: query_term_freq = {} query_term_list = query.split() updated_inverted_index = {} for query_term in query_term_list: if not query_term_freq.has_key(query_term): query_term_freq.update({query_term:1}) else: query_term_freq[query_term]+=1 #reducing the inverted_index with only required terms in query for query_term in query_term_freq: if inverted_index.has_key(query_term): updated_inverted_index.update({query_term:inverted_index[query_term]}) else: updated_inverted_index.update({query_term:{}}) calculate_score(query,query_term_freq,updated_inverted_index,total_num_of_docs) except Exception as e: print(traceback.format_exc()) def calculate_score(query,query_term,inverted_index,N): doc_score={} R = 0 # Assuming no relevance info is available try: for term in inverted_index: # inverted_index.keys() and query_term.keys() are same n = len(inverted_index[term]) dl = 0 qf = query_term[term] r = 0 # Assuming no relevance info is available for doc_id in inverted_index[term]: f = inverted_index[term][doc_id] if number_of_Token.has_key(doc_id): dl = number_of_Token[doc_id] score = calculate_BM25(n, f, qf, r, N, dl,R) if doc_id in doc_score: total_score = doc_score[doc_id] + score doc_score.update({doc_id:total_score}) else: doc_score.update({doc_id:score}) sorted_doc_score = sorted(doc_score.items(), key=operator.itemgetter(1), reverse=True) write_doc_score_to_file(query,sorted_doc_score) except Exception as e: print(traceback.format_exc()) # Writing score to individual files for each query def write_doc_score_to_file(query,sorted_doc_score): try: if not os.path.exists(OUTPUT_FOLDER_PATH): os.mkdir(OUTPUT_FOLDER_PATH) if(len(sorted_doc_score)>0): out_file = open(OUTPUT_FOLDER_PATH +"\\"+query[:-1]+".txt",'a+') for i in range(min(100,len(sorted_doc_score))): doc_id,doc_score = sorted_doc_score[i] out_file.write(str(QUERY_ID) + " Q0 "+ doc_id +" " + str(i+1) + " " + str(doc_score) +" BM25_Model\n") out_file.close() print "\nDocument Scoring for Query id = " +str(QUERY_ID) +" has been generated inside BM25_doc_score.txt" else: print "\nTerm not found in the corpus" except Exception as e: print(traceback.format_exc()) # BM25 score calculation def calculate_BM25(n, f, qf, r, N, dl,R): try: k1 = 1.2 k2 = 100 b = 0.75 K = k1 * ((1 - b) + b * (float(dl) / float(AVDL))) first = log(((r + 0.5) / (R - r + 0.5)) / ((n - r + 0.5) / (N - n - R + r + 0.5))) second = ((k1 + 1) * f) / (K + f) third = ((k2 + 1) * qf) / (k2 + qf) return first * second * third except Exception as e: print(traceback.format_exc()) # main function def main(): global QUERY_ID,AVDL #generating inverted_index for unigrams index_for_unigrams,total_num_of_docs = inverted_index_for_unigram() AVDL = calculate_avdl() print "avdl " print AVDL # Deleting existing files if os.path.exists(OUTPUT_FOLDER_PATH+"\\BM25_doc_score.txt"): os.remove(OUTPUT_FOLDER_PATH+"\\BM25_doc_score.txt") query_file = open("query.txt", 'r') for query in query_file.readlines(): QUERY_ID+=1 calculate_doc_bm25_score(query,index_for_unigrams,total_num_of_docs) # ------------------------INVERTED INDEX for n gram---------------------------------------# # n = raw_input ('Please enter value of n for n-grams...') # if int(n)==1: # # Unigram # index_for_unigrams = inverted_index_for_unigram() # write_inverted_index(index_for_unigrams,"unigram") # term_freq_table_for_unigram = make_term_freq_table(index_for_unigrams, "unigram") # doc_freq_table_for_unigram = make_doc_freq_table(index_for_unigrams, "unigram") # elif int(n)==2: # # Bigram # index_for_bigrams = inverted_index_for_bigram() # write_inverted_index(index_for_bigrams,"bigram") # term_freq_table_for_bigram = make_term_freq_table(index_for_bigrams, "bigram") # doc_freq_table_for_bigram = make_doc_freq_table(index_for_bigrams, "bigram") # elif int(n)==3: # # Trigram # index_for_trigrams = inverted_index_for_trigram() # write_inverted_index(index_for_trigrams,"trigram") # term_freq_table_for_trigram = make_term_freq_table(index_for_trigrams, "trigram") # doc_freq_table_for_trigram = make_doc_freq_table(index_for_trigrams, "trigram") # else: # print "Please enter 1 or 2 or 3" if __name__ == "__main__": main()
true
ea7d4ee1a032c73f981a0de6e3446c614f564a9f
Python
fibasile/PACO
/Software/PacoServer/paco/paco.py
UTF-8
5,022
2.984375
3
[]
no_license
from commands import PacoCommands, PacoBitmaps, PacoEvents import serial from time import sleep START_SYSEX = 0xF0 END_SYSEX = 0xF7 class Paco: def __init__(self, serial_port): self.serial_port = serial_port self.serial = serial.Serial(serial_port,115200) self.serial.write('0xFF') self.distance = 0 self.ready=False def test(self): self.send_command(PacoCommands.TEST,[]) sleep(10) def send_command(self, cmd, args): print 'Command sent' self.serial.write(chr(START_SYSEX)) self.serial.write(chr(cmd)) for a in args: self.send_as_two_bytes(a) while self.bytes_available(): self.iterate() self.serial.write(chr(END_SYSEX)) def from_two_bytes(self,bytes): """ Return an integer from two 7 bit bytes. >>> for i in range(32766, 32768): ... val = to_two_bytes(i) ... ret = from_two_bytes(val) ... assert ret == i ... >>> from_two_bytes(('\\xff', '\\xff')) 32767 >>> from_two_bytes(('\\x7f', '\\xff')) 32767 """ lsb, msb = bytes try: # Usually bytes have been converted to integers with ord already return msb << 7 | lsb except TypeError: # But add this for easy testing # One of them can be a string, or both try: lsb = ord(lsb) except TypeError: pass try: msb = ord(msb) except TypeError: pass return msb << 7 | lsb def send_as_two_bytes(self, val): if type(val) == type(''): val = ord(val) value = chr(val % 128) + chr(val >> 7) self.serial.write(value) def iterate(self): """ Reads and handles data from the microcontroller over the serial port. This method should be called in a main loop or in an :class:`Iterator` instance to keep this boards pin values up to date. """ byte = self.serial.read() if not byte: return data = ord(byte) received_data = [] handler = None if data == START_SYSEX: cmd = ord(self.serial.read()) data = ord(self.serial.read()) while data != END_SYSEX: received_data.append(data) data = ord(self.serial.read()) self.handle_sysex(cmd,received_data) def handle_sysex(self,cmd,data): if cmd==121: self.ready=True if cmd==PacoEvents.EVT_DISTANCE: if len(data) >= 2: self.distance = self.from_two_bytes(data[0:2]) print 'Distance %d' % self.distance print 'Received %s' % cmd def bytes_available(self): return self.serial.inWaiting() def pan(self, degrees): self.send_command(PacoCommands.PAN, [degrees] ) sleep(.3) def tilt(self, degrees): self.send_command(PacoCommands.TILT, [degrees] ) sleep(.3) def panTiltTest(self): self.pan(40) self.tilt(30) self.pan(130) self.tilt(70) self.pan(40) self.tilt(50) self.pan(90) def showBitmap(self, bitmap): if PacoBitmaps.has_key(bitmap): self.send_command(PacoCommands.SHOW_BMP, [PacoBitmaps[bitmap]]) def showText(self, text): if len(text)>0: self.serial.write(chr(START_SYSEX)) self.serial.write(chr(PacoCommands.SHOW_TXT)) for ch in text: self.serial.write(ch) self.serial.write(chr(END_SYSEX)) def clearScreen(self): l=[] for i in range(0,50): l.append(' ') self.send_command(PacoCommands.SHOW_TXT,l) def setLed(self, ledNo, r,g,b): cmdArgs = [ledNo,r,g,b] self.send_command(PacoCommands.SET_LED, cmdArgs) def setLeds(self, r,g,b): cmdArgs = [9,r,g,b] self.send_command(PacoCommands.SET_LED, cmdArgs) def setBrightness(self, val): self.send_command(PacoCommands.SET_BRIGHT, [val]) def readDistance(self): self.send_command(PacoCommands.READ_DISTANCE, []) # for i in range(0,10): # self.iterate() return self.distance def logo(self): self.showBitmap("logo") def smile(self): self.showBitmap("smile") def beachlab(self): self.showBitmap("beachlab") def sad(self): self.showBitmap("sad") def grin(self): self.showBitmap("grin") def version(self): return 1.0 def exit(self): self.serial.close()
true
ce9ee5edec318e200c685673a7ba43caea997fae
Python
sundhareswaran/core-python-program
/arrayprogram.py
UTF-8
741
3.6875
4
[]
no_license
arr=[10,20,30,40,50] print(arr[0]) print(arr[-1]) print(arr[-2]) brands = ["Coke", "Apple", "Google", "Microsoft", "Toyota"] num_brands = len(brands) print(num_brands) add=['a','b','c'] add.append('d') print(add) colors=["violet","indigo","blue","green","yellow","orange","red"] del colors[4] colors.remove("blue") colors.pop(3) print (colors) fruits=["apple","banana","mango","grapes","orange"] fruits[1]="pineapple" fruits[-1]="guava" print (fruits) concat = [1, 2, 3] a=concat + [4,5,6] print(a) repeat=["a"] repeat=repeat*5 print(repeat) fruits=["apple","banana","mango","grapes","orange"] print(fruits[1:4]) print(fruits[ :3]) print(fruits[-4: ]) print(fruits[-3:-1])
true
f8c84e6fe822501ef6c4c0e2b80f5eb7ba253443
Python
KLDistance/py3_simple_tutorials
/Fundamentals/OOM/member_privilege.py
UTF-8
761
4.6875
5
[]
no_license
# To define a private member variable inside a class, use two underscores "__" in front of a variable name. class MyClass1 : pub_mem = 'I am public in MyClass1' __priv_mem = 'I am private in MyClass1' def func(self) : print(self.pub_mem) print(self.__priv_mem) mc1 = MyClass1() # you can only directly use pub_mem! print(mc1.pub_mem) mc1.func() print() # To define a private member function inside a class, use two underscores "__" in front of a function name class MyClass2 : def pub_func(self) : print("This public member function is called.") def __priv_function(self) : print("You cannot reach here!") mc2 = MyClass2() # you can only directly call pub_func! mc2.pub_func()
true
4fc846e881099571ec8526621068e75eef785c18
Python
maznabili/kyros
/kyros/exceptions.py
UTF-8
289
2.859375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
class HMACValidationError(Exception): message = "validation failed" class LoginError(Exception): pass class StatusCodeError(Exception): def __init__(self, code): self.code = code message = f'Unexpected status code: {code}' super().__init__(message)
true
959a77234718130ff88f76d589af3bea64118167
Python
leejongcheal/algorithm_python
/알고리즘 문제풀이전략_python/ch14 동적계획법/목장 울타리.py
UTF-8
488
2.96875
3
[]
no_license
T = int(input()) for _ in range(T): n = int(input()) L = [] for i in range(n): L.append(list(map(float, input().split()))) i = 0 print(i+1, end=" ") while True: max = -100000 for j in range(i + 1, n): ratio = (L[j][1] - L[i][1]) / (L[j][0] - L[i][0]) if ratio > max: max = ratio sol = j print(sol+1, end=" ") i = sol if i == n-1: break print()
true
162644a9d0465d8ce0159e420c83f63e0ea570fe
Python
vieirinhaabr/data_estructure_tree_python
/MathNode.py
UTF-8
1,270
3.09375
3
[]
no_license
class ExpMath(object): numberOne = None numberTwo = None operator = None nextFunc = None id = 0 def newFunc(self, numberOne, numberTwo, operator, id): self.numberOne = numberOne self.numberTwo = numberTwo self.operator = operator self.id = id def insertFunc(self, numberOne, numberTwo, operator, id=0): if self.numberOne is None: self.newFunc(numberOne, numberTwo, operator, id) else: id += 1 self.nextFunc = ExpMath() self.nextFunc.insertFunc(numberOne, numberTwo, operator, id) def countFunc_initializate(self): if self.numberOne is not None: return 1 + self.countFunc_continue() else: return 0 def countFunc_continue(self): if self.nextFunc is not None: return 1 + self.nextFunc.countFunc_continue() else: return 0 def returnExp(self, id): if self.id == id: return self.operator, self.numberOne, self.numberTwo else: if self.nextFunc is not None: return self.nextFunc.returnExp(id) else: print("error when trying to find function") return 'empty'
true
c00f8bab31e4a5a793ce14b28acc03144c00b1ea
Python
victory-oki/Algorithms-DS
/gcd.py
UTF-8
132
3.28125
3
[]
no_license
# Uses python3 def gcd(a,b): if(b==0): return(a) return gcd(b,a%b) a, b = map(int, input().split()) print(gcd(a,b))
true
987419fd0425cf5cca39599eb800798667499729
Python
selwynsimsek/trilobite
/src/python/trilobite.py
UTF-8
12,971
3.734375
4
[]
no_license
""" Trilobite (The abstRact manIpuLation Of BInary TreEs) is a library written in Python and Java which contains high-level routines for binary tree search, insertion, removal and replacement. """ import math import random def print_tree(tree_str,display_slashes=True,output_file=None): """ This method prints a binary heap in tree form. E.g: Abc \n is rendered as \n A\n / \\\n b c\n ABCde f is rendered as A\n / \\\n / \\\n B C\n / \ \\\n d e f\n RATBCY de fgh is rendered as R\n / \\\n / \\\n / \\\n / \\\n / \\\n A T\n / \ /\n / \ /\n B C Y\n / \ \ / \\\n d e f g h\n """ #Trim any empty children (blank spaces) that may be at the end of the tree. tree_str=tree_str.rstrip(); #Terminate upon being given a blank tree if len(tree_str) ==0: return; # Compute the depth of the tree: a tree with l levels has binary heap size 2^l -1. l = int(math.ceil(math.log(len(tree_str)+1,2))); #Fill in the tree string with blank spaces: tree_length= 2**l - 1; tree_str += ' '*(tree_length-len(tree_str)); #pos_array holds the column number that each character is meant to be printed in pos_array=[-1]*tree_length; #Initialise the positions of the leftmost diagonal; from these positions #the positions of all the other characters may be calculated. for index in range(0,l): pos_array[2**index -1] = int(math.floor((3* 2**(l-index-2) -1))) #Now fill in the rest of the positions: for index in range(0,tree_length): if pos_array[index] == -1: curr_level=int(math.ceil(math.log(index+2,2)))-1 parent_pos=pos_array[(index+1)/2 -1]; #pos_array[index] = 2*pos_array[index/2 -1] - pos_array[index-1] if index % 2: #If the index is odd; we must move to the left of the parent index pos_array[index]=parent_pos - int(math.ceil(3* 2 **(l-2-curr_level))) else: #The index is even so we must move to the right of the parent index pos_array[index]=parent_pos + int(math.ceil(3* 2 **(l-2-curr_level))) #Store the output lines in a text array: output_lines=[t[:] for t in [[' ']*(pos_array[-1]+1)]*l]; #Keep track over which nodes are left-pointing and which are right-pointing: output_lines_flags=[t[:] for t in [[-1]*(pos_array[-1]+1)]*l]; for index in range(tree_length): #Calculate the index of the line that the current character should be printed to: curr_line_index= int(math.ceil(math.log(index+2,2)))-1; #print(curr_line_index) output_lines[curr_line_index][pos_array[index]]=tree_str[index]; output_lines_flags[curr_line_index][pos_array[index]]=index%2; #print(output_lines); #print(output_lines_flags) if display_slashes: #We need to add some slashes first output_lines_with_slashes=[t[:] for t in [[' ']*(pos_array[-1]+1)]*int(math.floor((3 * 2**(l-2))))]; #Easier to start from the bottom of the list and link up: output_lines.reverse(); output_lines_flags.reverse(); output_lines_with_slashes[0]=output_lines[0]; curr_line_index=1; for index in range(1,int(math.floor((3 * 2**(l-2))))): #The algorithm builds up a line of slashes. #If two slashes cross, then it must be necessary to print a new level of the tree. previous_line=output_lines_with_slashes[index-1]; add_new_level_flag=False prev_level_left_slashes= [i for i in range(len(previous_line)) if previous_line[i] == '\\'] #Source: #<http://stackoverflow.com/questions/11122291/python-find-char-in-string-can-i-get-all-indexes> prev_level_right_slashes= [i for i in range(len(previous_line)) if previous_line[i] == '/'] prev_level_letters=[i for i in range(len(previous_line)) if not (previous_line[i] == '/' or previous_line[i] == '\\' or previous_line[i]==' ' )] for i in prev_level_left_slashes: output_lines_with_slashes[index][i-1]='\\'; #Add another left slash for i in prev_level_right_slashes: if output_lines_with_slashes[index][i+1] == ' ': output_lines_with_slashes[index][i+1]='/'; else: add_new_level_flag=True for i in prev_level_letters: #letter_sign = tree_str.find(previous_line[i]) %2;# Too hacky; doesn't allow for duplicate letters! letter_sign=output_lines_flags[curr_line_index-1][i] #if letter_sign == -1: # print('warning') # print('curr_line_index=%s'%curr_line_index) # print('i=%s'%i) if letter_sign: #We need to add a right slash if output_lines_with_slashes[index][i+1] == ' ': output_lines_with_slashes[index][i+1]='/' else: add_new_level_flag=True else: if output_lines_with_slashes[index][i-1] == ' ': output_lines_with_slashes[index][i-1]='\\' else: add_new_level_flag=True if curr_line_index <len(output_lines): next_line=output_lines[curr_line_index]; next_line_char_indices=[i for i in range(len(next_line)) if not (next_line[i]==' ' )] curr_output_line_indices=[i for i in range(len(output_lines_with_slashes[index])) if not (output_lines_with_slashes[index][i]==' ' )] if not set(curr_output_line_indices).isdisjoint(set(next_line_char_indices)): add_new_level_flag=True if add_new_level_flag: output_lines_with_slashes[index]=output_lines[curr_line_index]; curr_line_index=1+curr_line_index; # Now reverse the lines: output_lines_with_slashes.reverse() #Update output_lines: output_lines=output_lines_with_slashes; if output_file==None: #Just print the lines to the output: for line in output_lines: print("".join(line)); else: #Write to file for line in output_lines: output_file.write("".join(line)+'\n'); output_file.close() def subtree(tree_str,n): """ Returns the subtree of a binary heap starting at position n. E.g. subtree(RATBCY de fgh,1) will return ABCde f """ tree_str=tree_str.rstrip(); tree_size=len(tree_str) subtree_size= int(math.floor((2*tree_size - n)/float(2+n))) +1; #+1 due to counting 0 as an index. # This formula gives a value which is slightly too high; try to work out an # analytic formula for the size of the subtree but it probably isn't possible. #Have a lower bound too #subtree_lower_bound=int(math.floor((tree_size - n)/float(1+n))) ; #print("Upper bound for subtree size: %s"%subtree_size) #print("Lower bound for subtree size: %s"%subtree_lower_bound) # Initialise the subtree: subtree=[' ' for i in range(subtree_size)] for i in range(subtree_size): a_i = int((n * 2**math.floor(math.log(i+1,2)) )+i); if a_i>=tree_size: # We have already calculated all the coefficients; #print("Actual subtree size: %s"%i) return "".join(subtree[:i])# trim the subtree to size and return it. else: subtree[i]=tree_str[a_i]; #Return the subtree #print("Actual subtree size: %s "%subtree_size) return "".join(subtree); def randtree(p_blank=0.05,alphabet=[chr(i) for i in range(ord('a'), ord('z') + 1)],unique_nodes=True,max_levels=6): """ Generates a random tree. """ alphabet=alphabet[:]; if unique_nodes: #If we need unique nodes, we should shuffle the alphabet and draw the letters one by one. random.shuffle(alphabet) #print(alphabet) tree = []; #Use a character array to build the tree; more efficient than string concatenation. # Keep track of where we are in the tree. curr_index=0; # Need to keep track of the last filled position in the tree in order to figure out if we have # finished or not. last_occupied_index=0; if p_blank==0 and not unique_nodes: print('warning - p_blank=0 and unique_nodes=False - returning a blank tree') return ''; #if not unique_nodes: # print('unique_nodes=False not yet implemented') # return; #We want to loop until either all nodes # in the current level of the tree have no children or if the number of levels in the tree # has reached max_levels. while curr_index <=2*last_occupied_index+2 and (max_levels <0 or curr_index <= 2**(max_levels) -2): # First, check whether we need to add a new leaf. # If we are at the root (position 0) or if the parent node is blank we can skip over it. if curr_index==0 or not tree[(curr_index+1)/2 -1] == ' ': #Add a new node node_is_blank=random.random()<p_blank if node_is_blank: tree.append(' ') else: if unique_nodes: #Unique nodes, so we need to remove a character from the alphabet without replacement. if len(alphabet) >0: tree.append(alphabet.pop(0)); last_occupied_index=curr_index else: #If no other letters are left, return the tree. return "".join(tree); else: tree.append(random.choice(alphabet)); last_occupied_index=curr_index else: tree.append(' ') curr_index=curr_index+1; return "".join(tree) def tree_depth(tree_str): """ Returns the depth of a tree represented in binary heap form. """ tree_str=tree_str.rstrip(); if len(tree_str) ==0: return 0; else: return int(1+math.floor(math.log(len(tree_str),2))) def tree_size(tree_str): """ Returns the size of the tree (number of elements). """ return len(tree_str.replace(" ","")) def traverse(tree_str,mode): """ Traverses a binary tree in a particular order. Current options are: 'pre' - Preorder traversal 'in' - Inorder traversal 'post' - Postorder traversal """ if mode == 'bh': # Binary heap return tree_str.rstrip(); elif mode == 'pre' or mode== 'post' or mode =='in': #Preorder traversal tree_str=list(tree_str); tree_str_len = len(tree_str); ret_seq=[]; curr_index=0 while True: if mode == 'pre': if tree_str[curr_index] !=' ': #tree[curr_index] is not blank ret_seq.append(tree_str[curr_index]); #print(tree_str[curr_index]) tree_str[curr_index]=' '; if 2*curr_index + 1 < tree_str_len and tree_str[2*curr_index+1]!= ' ': curr_index= 2*curr_index +1; continue if 2*curr_index + 2 < tree_str_len and tree_str[2*curr_index+2]!= ' ': curr_index= 2*curr_index +2; continue elif mode == 'post': if tree_str[curr_index] !=' ': #tree[curr_index] is not blank if 2*curr_index + 1 < tree_str_len and tree_str[2*curr_index+1]!= ' ': curr_index= 2*curr_index +1; continue if 2*curr_index + 2 < tree_str_len and tree_str[2*curr_index+2]!= ' ': curr_index= 2*curr_index +2; continue ret_seq.append(tree_str[curr_index]); #print(tree_str[curr_index]) tree_str[curr_index]=' '; elif mode == 'in': if tree_str[curr_index] !=' ': #tree[curr_index] is not blank if 2*curr_index + 1 < tree_str_len and tree_str[2*curr_index+1]!= ' ': curr_index= 2*curr_index +1; continue ret_seq.append(tree_str[curr_index]); #print(tree_str[curr_index]) tree_str[curr_index]=' '; if 2*curr_index + 2 < tree_str_len and tree_str[2*curr_index+2]!= ' ': curr_index= 2*curr_index +2; continue if curr_index ==0: return "".join(ret_seq); else: curr_index = (curr_index+1)/2 -1
true
a540d30e541221631a561dec7af9a599f7d437bf
Python
fincai/pythonDSA
/Recursion/recursive_spiral_turtle.py
UTF-8
301
3.640625
4
[]
no_license
import turtle myTurtle = turtle.Turtle() myWindow = turtle.Screen() def drawSpiral(myTurtle, lineLen): if lineLen > 0: myTurtle.forward(lineLen) myTurtle.right(90) # turn right 90 degree drawSpiral(myTurtle, lineLen-5) drawSpiral(myTurtle, 100) myWindow.exitonclick()
true
1e4d29dba3c690d6210bff3ad5978a179b410bc9
Python
Thunderbird2086/dumbir
/dumbir_codes/climate/get_conf.py
UTF-8
946
2.71875
3
[]
no_license
#!/usr/bin/env python3 import argparse import logging import yaml FORMAT = '%(asctime)-15s %(message)s' logging.basicConfig(format=FORMAT, level=logging.DEBUG) _LOGGER = logging.getLogger(__name__) def main(yaml_file): with open(yaml_file, 'r') as stream: conf = yaml.safe_load(stream) for k, v in conf.items(): print(k) if type(v) is dict: for k1, v1 in v.items(): print(" {}".format(k1)) if type(v1) is dict: for k2, v2 in v1.items(): print(" {}".format(k2)) if type(v2) is dict: for k3, v3 in v2.items(): print(" {}".format(k3)) if __name__ == '__main__': parser = argparse.ArgumentParser(fromfile_prefix_chars='@') parser.add_argument('yaml', help="yaml file") args = parser.parse_args() main(args.yaml)
true
88fefaf198e8122283f04ab357be5aaf3cefbb42
Python
ltfafei/myPython_penetraScript
/Py_rot_arithme_encrypt-and-decrypt/ascii_Rot-any-encode_and_decode.py
UTF-8
1,244
3.484375
3
[]
no_license
#!/usr/bin/python # Env: python3 # Author: afei_0and1 # -*- coding: utf8 -*- import string def rot_any_encode(cipher, OffSet): x = [] for i in range(len(cipher)): string = ord(cipher[i]) if string >= 33 and string <= 126: #除94取余?127-33=94 x.append(chr(33+(string + OffSet) % 94)) else: x.append(cipher[i]) res = ''.join(x) print("\nrot密码加密成功,加密结果:"+res) def rot_any_decode(strings, OffSet): x = [] for i in range(len(strings)): string = ord(strings[i]) if string >= 33 and string <= 126: #除94取余?127-33=94 x.append(chr(string - (33 + OffSet))) else: x.append(strings[i]) res = ''.join(x) print("\nrot密码解密成功,解密结果:"+res) x = input("\n功能选择:\n 加密:1\n 解密:2\n") if x == '1': en = input("请输入需要加密的字符串:") step = int(input("请输入步长(step-33):")) rot_any_encode(en, step) elif x == '2': de = input("请输入解密密文:") step = int(input("请输入步长(step-33):")) rot_any_decode(de, step) else: print("您的输入有误!") exit()
true
4a8a2c14cec102cc9120489b31dfa7935488fc99
Python
rajalur/lambda_projects
/flubs.py
UTF-8
2,600
2.75
3
[]
no_license
import urllib2 import json def lambda_handler(event, context): # TODO implement if event['request']['type'] == "IntentRequest": intent_name = extract_alexa_skill_name(event) print("Intent name = {}".format(intent_name)) intent_slot = extract_alexa_slot_type(event) print("Intent Slot = {}".format(intent_slot)) intent_slot_value = extract_alexa_skill_value(event, intent_slot) print("intent slot Value = {}".format(intent_slot_value)) rhymes = find_rhymes(intent_slot_value) my_string = construct_string_from_list(rhymes) response = build_speechlet_response(title="", #output=','.join(rhymes), output=my_string, reprompt_text=None, should_end_session=True) return build_response({}, response) def construct_string_from_list(my_list): my_string = '' for l in my_list: my_string += l my_string += ',' return my_string[:-1] def extract_alexa_skill_name(json_input_to_lambda): return json_input_to_lambda['request']['intent']['name'] def extract_alexa_slot_type(json_input_to_lambda): for key in json_input_to_lambda['request']['intent']['slots'].keys(): if 'name' in json_input_to_lambda['request']['intent']['slots'][key].keys(): return key return '' def extract_alexa_skill_value(json_input_to_lambda, slot_type): return json_input_to_lambda['request']['intent']['slots'][slot_type]['value'] def find_rhymes(word): url = 'https://api.datamuse.com/words?rel_rhy=' datamuse_retval = urllib2.urlopen('{}{}'.format(url, word)).read() json_rhymes = json.loads(datamuse_retval) rhymes = [] for val in json_rhymes: rhymes.append(val['word']) return rhymes def build_speechlet_response(title, output, reprompt_text, should_end_session): return { "outputSpeech": { "type": "PlainText", "text": output }, "card": { "type": "Simple", "title": title, "content": output }, "reprompt": { "outputSpeech": { "type": "PlainText", "text": reprompt_text } }, "shouldEndSession": should_end_session } def build_response(session_attributes, speechlet_response): return { "version": "1.0", "sessionAttributes": session_attributes, "response": speechlet_response }
true
d820244ad2baa4e40622962476bac790ee25b8df
Python
giusedyn/dd2424-deep-learning
/assignment-2/assignment2-bonus.py
UTF-8
27,980
2.890625
3
[]
no_license
__author__ = "Hamid Dimyati" import numpy as np import pickle import matplotlib.pyplot as plt import time np.random.seed(40) def load_meta(file): """ Parameters: file: filename to be loaded Returns: dict: dictionary of meta/data """ with open(file, 'rb') as fo: dict = pickle.load(fo, encoding='bytes') return dict def load_batch(file): """ Parameters: file: filename to be loaded Returns: X (d, n): image pixel data Y (K, n): one-hot representation of the label for each image y (n): label for each image """ with open(file, 'rb') as fo: dict = pickle.load(fo, encoding='bytes') X = dict[b'data'].T y = dict[b'labels'] Y = np.eye(10)[y].T return X, Y, y def softmax(X): """ Parameters: X: matrix to be transformed Returns: softmax transformation """ a = np.exp(X - np.max(X, axis=0)) return a / a.sum(axis=0) def relu(X): """ """ return np.maximum(0, X) def normalization(X, X_train, type_norm): """ Parameters: X (d, n): image pixel data to be normalized X_train (d, n): training image pixel data as reference for normalization type_norm: the type of normalization, either z-score or min-max Returns: X (d, n): normalized image pixel data """ if type_norm == 'z-score': mean_X = np.mean(X_train, axis=1).reshape(-1,1) std_X = np.std(X_train, axis=1).reshape(-1,1) X = (X-mean_X)/std_X if type_norm == 'min-max': min_X = np.min(X_train, axis=1).reshape(-1,1) max_X = np.max(X_train, axis=1).reshape(-1,1) X = (X-min_X)/(max_X-min_X) return X class NeuralNetwork(): def __init__(self, n_hidden, file='datasets/cifar-10-batches-py/batches.meta'): """ Parameters: W1 (m, d): weight matrix from input layer to hidden layer W2 (K, m): weight matrix hidden layer to output layer b1 (m, 1): bias vector to hidden layer b2 (K, 1): bias vector to output layer cost_train: cost value during learning the training dataset loss_train: loss value during learning the training dataset acc_train: accuracy of the training dataset cost_val: cost value during learning the validation dataset loss_val: loss value during learning the validation dataset acc_val: accuracy of the validation dataset labels: label of each sample """ self.W = {} self.b = {} self.cost_train = [] self.loss_train = [] self.acc_train = [] self.cost_val = [] self.loss_val = [] self.acc_val = [] self.t = [] self.labels = load_meta(file)[b'label_names'] self.n_hidden = n_hidden self.mask = None def test_method(self, X, Y, lambda_, n_batch, ht, type_norm): """ Parameters: X (d, n): image pixel data Y (K, n): one-hot representation of the label for each image lambda_: value of regularization parameter n_batch: total samples per one batch Returns: print the result of method validation between analytical and numerical approaches """ X = normalization(X, X, type_norm) X_batch = X[:20, :n_batch] Y_batch = Y[:20, :n_batch] h=1e-5 self.init_parameters(X_batch) gw10, gb10, gw20, gb20 = self.compute_gradients(X_batch, Y_batch, lambda_=0) e = np.finfo(np.float32).eps # ComputeGradsNum gw11, gb11, gw21, gb21 = self.compute_grads_num(X_batch, Y_batch, lambda_=0, h=h) gap_w11 = np.divide(np.abs(gw10-gw11), np.maximum(e, (np.abs(gw10)) + (np.abs(gw11)))) gap_b11 = np.divide(np.abs(gb10-gb11), np.maximum(e, (np.abs(gb10)) + (np.abs(gb11)))) threshold_w11 = np.array([ht] * (gap_w11.shape[0] * gap_w11.shape[1])).reshape((gap_w11.shape[0], gap_w11.shape[1])) threshold_b11 = np.array([ht] * (gap_b11.shape[0] * gap_b11.shape[1])).reshape((gap_b11.shape[0], gap_b11.shape[1])) gap_w21 = np.divide(np.abs(gw20-gw21), np.maximum(e, (np.abs(gw20)) + (np.abs(gw21)))) gap_b21 = np.divide(np.abs(gb20-gb21), np.maximum(e, (np.abs(gb20)) + (np.abs(gb21)))) threshold_w21 = np.array([ht] * (gap_w21.shape[0] * gap_w21.shape[1])).reshape((gap_w21.shape[0], gap_w21.shape[1])) threshold_b21 = np.array([ht] * (gap_b21.shape[0] * gap_b21.shape[1])).reshape((gap_b21.shape[0], gap_b21.shape[1])) print('ComputeGradsNum') print("W1's are equal: " + str(np.allclose(gap_w11, threshold_w11, rtol=0.0, atol=ht))) print("b1's are equal: " + str(np.allclose(gap_b11, threshold_b11, rtol=0.0, atol=ht))) print("W2's are equal: " + str(np.allclose(gap_w21, threshold_w21, rtol=0.0, atol=ht))) print("b2's are equal: " + str(np.allclose(gap_b21, threshold_b21, rtol=0.0, atol=ht))) # ComputeGradsNumSlow gw12, gb12, gw22, gb22 = self.compute_grads_num_slow(X_batch, Y_batch, lambda_=0, h=h) gap_w12 = np.divide(np.abs(gw10-gw12), np.maximum(e, (np.abs(gw10)) + (np.abs(gw12)))) gap_b12 = np.divide(np.abs(gb10-gb12), np.maximum(e, (np.abs(gb10)) + (np.abs(gb12)))) threshold_w12 = np.array([ht] * (gap_w12.shape[0] * gap_w12.shape[1])).reshape((gap_w12.shape[0], gap_w12.shape[1])) threshold_b12 = np.array([ht] * (gap_b12.shape[0] * gap_b12.shape[1])).reshape((gap_b12.shape[0], gap_b12.shape[1])) gap_w22 = np.divide(np.abs(gw20-gw22), np.maximum(e, (np.abs(gw20)) + (np.abs(gw22)))) gap_b22 = np.divide(np.abs(gb20-gb22), np.maximum(e, (np.abs(gb20)) + (np.abs(gb22)))) threshold_w22 = np.array([ht] * (gap_w22.shape[0] * gap_w22.shape[1])).reshape((gap_w22.shape[0], gap_w22.shape[1])) threshold_b22 = np.array([ht] * (gap_b22.shape[0] * gap_b22.shape[1])).reshape((gap_b22.shape[0], gap_b22.shape[1])) print('ComputeGradsNumSlow') print("W1's are equal: " + str(np.allclose(gap_w12, threshold_w12, rtol=0.0, atol=ht))) print("b1's are equal: " + str(np.allclose(gap_b12, threshold_b12, rtol=0.0, atol=ht))) print("W2's are equal: " + str(np.allclose(gap_w22, threshold_w22, rtol=0.0, atol=ht))) print("b2's are equal: " + str(np.allclose(gap_b22, threshold_b22, rtol=0.0, atol=ht))) def fit(self, X_train, Y_train, y_train, X_val, Y_val, y_val, lambda_, keep_prob, n_batch, n_epoch, n_step, eta_min, eta_max, shuffle, cost, cyclical, type_norm): """ Parameters: X_train (d, n_1): image pixel training data Y_train (K, n_1): one-hot representation of the label for each training image y_train (n_1): label for each training image X_val (d, n_2): image pixel validation data Y_val (K, n_2): one-hot representation of the label for each validation image y_val (n_2): label for each validation image lambda_: value of regularization parameter n_batch: total samples per one batch eta: learning rate value n_epoch: total epoch shuffle (boolean): whether to apply random shuffling to the data """ X_train_norm = normalization(X_train, X_train, type_norm) X_val_norm = normalization(X_val, X_train, type_norm) self.init_parameters(X_train_norm) self.mini_batch_GD(X_train_norm, Y_train, y_train, X_val_norm, Y_val, y_val, lambda_, keep_prob, n_batch, n_epoch, n_step, eta_min, eta_max, shuffle, cost, cyclical) def predict(self, X, y): """ Parameters: X (d, n): image pixel data y (n): label for each image Returns: final_acc: accuracy of the model """ final_acc = self.compute_accuracy(X, y) return final_acc def montage(self, filename): """ Display the image for each label in W Parameters: filename: filename Returns: save the figure in png format """ fig, ax = plt.subplots(2,5) for i in range(2): for j in range(5): im = self.W[5*i+j,:].reshape(32,32,3, order='F') sim = (im-np.min(im[:]))/(np.max(im[:])-np.min(im[:])) sim = sim.transpose(1,0,2) ax[i][j].imshow(sim, interpolation='nearest') ax[i][j].set_title("y="+str(5*i+j)) ax[i][j].axis('off') fig.savefig('figure_{}.png'.format(filename)) plt.close(fig) def plotting(self, filename): """ Parameters: n_epoch: range of total epoch filename: filename Returns: save the figure in png format """ fig, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(20,5)) ax1.plot(self.t, self.loss_train, label='training loss') ax1.plot(self.t, self.loss_val, label='validation loss') ax1.legend(loc='best', fontsize='small') ax1.set_title('cross-entropy loss value in each step size') ax1.set_xlabel('step size', fontsize='small') ax1.set_ylabel('cross-entropy loss', fontsize='small') ax2.plot(self.t, self.cost_train, label='training cost') ax2.plot(self.t, self.cost_val, label='validation cost') ax2.legend(loc='best', fontsize='small') ax2.set_title('cost value in each step size') ax2.set_xlabel('step size', fontsize='small') ax2.set_ylabel('cost value', fontsize='small') ax3.plot(self.t, self.acc_train, label='training accuracy') ax3.plot(self.t, self.acc_val, label='validation accuracy') ax3.legend(loc='best', fontsize='small') ax3.set_title('accuracy in each step size') ax3.set_xlabel('step size', fontsize='small') ax3.set_ylabel('accuracy', fontsize='small') fig.savefig('plot_{}.png'.format(filename)) plt.close(fig) def init_parameters(self, X): """ Parameters: X (d, n): image pixel data Returns: save the parameter initialization of W and b """ d = X.shape[0] m = self.n_hidden K = len(self.labels) self.W['1'] = np.random.normal(0, 1/np.sqrt(d, dtype=np.float32), (m, d)).astype(np.float32) self.W['2'] = np.random.normal(0, 1/np.sqrt(m, dtype=np.float32), (K, m)).astype(np.float32) self.b['1'] = np.zeros((m, 1), dtype=np.float32) self.b['2'] = np.zeros((K, 1), dtype=np.float32) def dropout(self, X, keep_prob): """ Parameters: X: matrix of nodes to be dropped out keep_prob: probability of each node to be dropped out Returns: X_drop: matrix of nodes after some nodes been dropped out """ self.mask = (np.random.rand(X.shape[0], X.shape[1]) < keep_prob) X_drop = np.multiply(X, self.mask) X_drop = X_drop / keep_prob return X_drop def evaluate_classifier(self, X, keep_prob, dropout_=True): """ Parameters: X (d, n): image pixel data Returns: P (K, n): probability of dot product of input data and parameters """ s1 = np.matmul(self.W['1'], X) + self.b['1'] H = relu(s1) if dropout_: H = self.dropout(H, keep_prob) s = np.matmul(self.W['2'], H) + self.b['2'] P = softmax(s) return H, P def compute_gradients(self, X, Y, lambda_, keep_prob): """ Parameters: X (d, n): image pixel data Y (K, n): one-hot representation of the label for each image lambda_: value of regularization parameter Returns: grad_W (K, d): gradient of weight matrix grad_b (K, 1): gradient of bias vector """ n = X.shape[1] I = np.ones(n, dtype=np.float32).reshape(n, 1) H, P = self.evaluate_classifier(X, keep_prob) G = -(Y-P) grad_W2 = 1/n * np.matmul(G, H.T) + 2 * lambda_ * self.W['2'] grad_b2 = 1/n * np.matmul(G, I) G = np.matmul(self.W['2'].T, G) G = np.multiply(G, self.mask) G = G / keep_prob #H[H <= 0.0] = 0.0 G = np.multiply(G, H > 0.0) grad_W1 = 1/n * np.matmul(G, X.T) + 2 * lambda_ * self.W['1'] grad_b1 = 1/n * np.matmul(G, I) return grad_W1, grad_b1, grad_W2, grad_b2 def compute_grads_num(self, X, Y, lambda_, h): """ Converted from matlab code Parameters: X (d, n): image pixel data Y (K, n): one-hot representation of the label for each image P (K, n): probability of dot product of input data and parameters lambda_: value of regularization parameter h: small value as tolerable threshold Returns: grad_W (K, d): gradient of weight matrix grad_b (K, 1): gradient of bias vector """ grad_W = [np.zeros(self.W['1'].shape, dtype=np.float32), np.zeros(self.W['2'].shape, dtype=np.float32)]; grad_b = [np.zeros(self.b['1'].shape, dtype=np.float32), np.zeros(self.b['2'].shape, dtype=np.float32)]; c, _ = self.compute_cost(X, Y, lambda_); for j in range(1,3): b_try = np.copy(self.b[str(j)]) for i in range(len(self.b[str(j)])): self.b[str(j)] = np.array(b_try) self.b[str(j)][i] += h c2, _ = self.compute_cost(X, Y, lambda_) grad_b[j-1][i] = (c2-c) / h self.b[str(j)] = b_try W_try = np.copy(self.W[str(j)]) for i in np.ndindex(self.W[str(j)].shape): self.W[str(j)] = np.array(W_try) self.W[str(j)][i] += h c2, _ = self.compute_cost(X, Y, lambda_) grad_W[j-1][i] = (c2-c) / h self.W[str(j)] = W_try return grad_W[0], grad_b[0], grad_W[1], grad_b[1] def compute_grads_num_slow(self, X, Y, lambda_, h): """ Converted from matlab code Parameters: X (d, n): image pixel data Y (K, n): one-hot representation of the label for each image P (K, n): probability of dot product of input data and parameters lambda_: value of regularization parameter h: small value as tolerable threshold Returns: grad_W (K, d): gradient of weight matrix grad_b (K, 1): gradient of bias vector """ grad_W = [np.zeros(self.W['1'].shape, dtype=np.float32), np.zeros(self.W['2'].shape, dtype=np.float32)]; grad_b = [np.zeros(self.b['1'].shape, dtype=np.float32), np.zeros(self.b['2'].shape, dtype=np.float32)]; for j in range(1,3): b_try = np.copy(self.b[str(j)]) for i in range(len(self.b[str(j)])): self.b[str(j)] = np.array(b_try) self.b[str(j)][i] -= h c1, _ = self.compute_cost(X, Y, lambda_) self.b[str(j)] = np.array(b_try) self.b[str(j)][i] += h c2, _ = self.compute_cost(X, Y, lambda_) grad_b[j-1][i] = (c2-c1) / (2*h) self.b[str(j)] = b_try W_try = np.copy(self.W[str(j)]) for i in np.ndindex(self.W[str(j)].shape): self.W[str(j)] = np.array(W_try) self.W[str(j)][i] -= h c1, _ = self.compute_cost(X, Y, lambda_) self.W[str(j)] = np.array(W_try) self.W[str(j)][i] += h c2, _ = self.compute_cost(X, Y, lambda_) grad_W[j-1][i] = (c2-c1) / (2*h) self.W[str(j)] = W_try return grad_W[0], grad_b[0], grad_W[1], grad_b[1] def compute_cost(self, X, Y, lambda_): """ Parameters: X (d, n): image pixel data Y (K, n): one-hot representation of the label for each image lambda_: value of regularization parameter Returns: J: the sum of the loss of the network’s predictions with regularization term l: the sum of the loss function """ n = X.shape[1] _, P = self.evaluate_classifier(X, keep_prob=1.0, dropout_=False) pre_l = np.matmul(Y.T, P) pre_l[pre_l == 0] = np.finfo(np.float32).eps l = -1/n * np.log(pre_l).trace() J = l + lambda_ * (np.sum(self.W['1']**2) + np.sum(self.W['2']**2)) return J, l def mini_batch_GD(self, X_train, Y_train, y_train, X_val, Y_val, y_val, lambda_, keep_prob, n_batch, n_epoch, n_step, eta_min, eta_max, shuffle, cost, cyclical): """ Parameters: X_train (d, n_1): image pixel training data Y_train (K, n_1): one-hot representation of the label for each training image y_train (n_1): label for each training image X_val (d, n_2): image pixel validation data Y_val (K, n_2): one-hot representation of the label for each validation image y_val (n_2): label for each validation image lambda_: value of regularization parameter n_batch: total samples per one batch eta: learning rate value n_epoch: total epoch shuffle (boolean): whether to apply random shuffling to the data """ n = X_train.shape[1] eta = eta_min t = 0 l = 0 rec = 2 * n_step / 3 for i in range(n_epoch): rand_id = np.random.permutation(n) for id in range(n // n_batch): if shuffle: rand_batch_range = range(id * n_batch, ((id + 1) * n_batch)) batch_range = rand_id[rand_batch_range] else: batch_range = range(id * n_batch, (id + 1) * n_batch) X_batch = X_train[:, batch_range] Y_batch = Y_train[:, batch_range] grad_W1, grad_b1, grad_W2, grad_b2 = self.compute_gradients(X_batch, Y_batch, lambda_, keep_prob) self.W['1'] -= eta * grad_W1 self.b['1'] -= eta * grad_b1 self.W['2'] -= eta * grad_W2 self.b['2'] -= eta * grad_b2 if cost & (t % rec == 0): #(i == n_epoch - 1) & (id == (n // n_batch) - 1): print(t) cost_train, loss_train = self.compute_cost(X_train, Y_train, lambda_) self.cost_train.append(cost_train) self.loss_train.append(loss_train) cost_val, loss_val = self.compute_cost(X_val, Y_val, lambda_) self.cost_val.append(cost_val) self.loss_val.append(loss_val) acc_train = self.compute_accuracy(X_train, y_train) acc_val = self.compute_accuracy(X_val, y_val) self.acc_train.append(acc_train) self.acc_val.append(acc_val) self.t.append(t) t += 1 if cyclical: if (t + 1) % (2 * n_step) == 0: l += 1 if (t >= 2 * l * n_step) & (t <= (2 * l + 1) * n_step): eta = eta_min + ((t - (2 * l * n_step)) / n_step) * (eta_max - eta_min) elif (t >= (2 * l + 1) * n_step) & (t <= 2 * (l + 1) * n_step): eta = eta_max - ((t - ((2 * l + 1) * n_step)) / n_step) * (eta_max - eta_min) def compute_accuracy(self, X, y): """ Parameters: X (d, n): image pixel data y (n): label for each image Returns: acc: accuracy of the model """ n = X.shape[1] _, P = self.evaluate_classifier(X, keep_prob=1.0, dropout_=False) k = np.argmax(P, axis=0).T count = k[k == np.asarray(y)].shape[0] acc = count/n return acc if __name__ == "__main__": start = time.time() norm = 'z-score' X_train, Y_train, y_train = load_batch('datasets/cifar-10-batches-py/data_batch_1') # load full datasets for i in range(2,6): Xi, Yi, yi = load_batch('datasets/cifar-10-batches-py/data_batch_{}'.format(i)) if i != 5: X_train = np.concatenate((X_train, Xi), axis=1) Y_train = np.concatenate((Y_train, Yi), axis=1) y_train = y_train + yi else: X_train = np.concatenate((X_train, Xi[:,:5000]), axis=1) Y_train = np.concatenate((Y_train, Yi[:,:5000]), axis=1) y_train = y_train + yi[:5000] X_val = Xi[:,5000:] Y_val = Yi[:,5000:] y_val = yi[5000:] #X_val, Y_val, y_val = load_batch('datasets/cifar-10-batches-py/data_batch_2') X_test, Y_test, y_test = load_batch('datasets/cifar-10-batches-py/test_batch') X_train_norm = normalization(X_train, X_train, norm) X_val_norm = normalization(X_val, X_train, norm) X_test_norm = normalization(X_test, X_train, norm) n_batch = 100 eta_min=1e-5 eta_max=1e-1 lambda_ = 0.00197229 # random search for step size and number of cycles n = X_train.shape[1] ns_min = 0.5 ns_max = 15 nstep_dict = {} cycle_min = 1 cycle_max = 10 cycle_dict = {} acc_dict = {} for i in range(5): acc_val_list = [] ns_list = [] cycle_list = [] for _ in range(15): ns = ns_min + (ns_max - ns_min) * np.random.rand(1,1)[0][0] n_step = 100 * np.int(ns) ns_list.append(n_step) cyc = cycle_min + (cycle_max - cycle_min) * np.random.rand(1,1)[0][0] cycle = np.int(cyc) cycle_list.append(cycle) n_epoch = np.int(2 * cycle * n_step / (n // n_batch)) model_NN = NeuralNetwork(n_hidden=50) model_NN.fit(X_train, Y_train, y_train, X_val, Y_val, y_val, lambda_=lambda_, n_batch=n_batch, n_epoch=n_epoch, n_step=n_step, eta_min=eta_min, eta_max=eta_max, shuffle=True, cost=False, cyclical=True, type_norm=norm) acc = model_NN.predict(X_val_norm, y_val) acc_val_list.append(acc) print(acc_val_list) top_acc = np.argsort(acc_val_list)[-3:][::-1] acc_dict[str(i)] = np.asarray(acc_val_list)[top_acc] nstep_dict[str(i)] = np.asarray(ns_list)[top_acc] ns_min = np.int(np.min(nstep_dict[str(i)])/100) ns_max = np.int(np.max(nstep_dict[str(i)])/100) cycle_dict[str(i)] = np.asarray(cycle_list)[top_acc] cycle_min = np.min(cycle_dict[str(i)]) cycle_max = np.max(cycle_dict[str(i)]) print(nstep_dict) print(cycle_dict) print(acc_dict) with open('nstep_dict.p', 'wb') as fp: pickle.dump(nstep_dict, fp, protocol=pickle.HIGHEST_PROTOCOL) with open('cycle_dict.p', 'wb') as fp: pickle.dump(cycle_dict, fp, protocol=pickle.HIGHEST_PROTOCOL) # improve number of hidden nodes n_epoch=31 n_step=1000 node_list = range(1,11) hidden_node_list = [] acc_train_list = [] acc_val_list = [] acc_test_list = [] for node in node_list: n_node=np.int(10*node) hidden_node_list.append(n_node) model_NN = NeuralNetwork(n_hidden=n_node) model_NN.fit(X_train, Y_train, y_train, X_val, Y_val, y_val, lambda_=lambda_, n_batch=n_batch, n_epoch=n_epoch, n_step=n_step, eta_min=eta_min, eta_max=eta_max, shuffle=True, cost=False, cyclical=True, type_norm=norm) acc_train_list.append(model_NN.predict(X_train_norm, y_train)) acc_val_list.append(model_NN.predict(X_val_norm, y_val)) acc_test_list.append(model_NN.predict(X_test_norm, y_test)) print('all accuracy in coarse:') print(acc_train_list) print(acc_val_list) print(acc_test_list) plt.plot(hidden_node_list, acc_train_list, label='training') plt.plot(hidden_node_list, acc_val_list, label='validation') plt.plot(hidden_node_list, acc_test_list, label='testing') plt.xlabel('number of hidden nodes', fontsize='small') plt.ylabel('accuracy', fontsize='small') plt.title('accuracy by number of hidden nodes') plt.legend(loc='best', fontsize='small') plt.savefig('accuracy vs no hidden node.png') plt.close() # employing dropout (6 cycles) n_epoch=30 n_step=1125 n_node = 100 model_NN = NeuralNetwork(n_hidden=n_node) model_NN.fit(X_train, Y_train, y_train, X_val, Y_val, y_val, lambda_=lambda_, keep_prob=0.75, n_batch=n_batch, n_epoch=n_epoch, n_step=n_step, eta_min=eta_min, eta_max=eta_max, shuffle=True, cost=True, cyclical=True, type_norm=norm) print('training accuracy: {}'.format(model_NN.predict(X_train_norm, y_train))) print('validation accuracy: {}'.format(model_NN.predict(X_val_norm, y_val))) print('testing accuracy: {}'.format(model_NN.predict(X_test_norm, y_test))) fname = "dropout1 lambda:{}, n_batch:{}, n_epoch:{}, eta:{}, n_step:{}".format(lambda_, n_batch, n_epoch, 'cyclic', n_step) model_NN.plotting(filename=fname) # search for the best range of learning rate n_epoch=20 n_step=500 pre_eta_list=np.linspace(-3,-1,10) #eta_list = 10 ** pre_eta_list eta_list = np.around(np.asarray(10 ** pre_eta_list), 5) n_node = 100 acc_train_list = [] cost_train_list = [] for eta in eta_list: model_NN = NeuralNetwork(n_hidden=n_node) model_NN.fit(X_train, Y_train, y_train, X_val, Y_val, y_val, lambda_=lambda_, keep_prob=0.5, n_batch=n_batch, n_epoch=n_epoch, n_step=n_step, eta_min=eta, eta_max=eta, shuffle=True, cost=True, cyclical=False, type_norm=norm) acc_train_list.append(model_NN.predict(X_train_norm, y_train)) cost_train_list.append(model_NN.cost_train) #plot cost plt.plot(range(len(eta_list)), cost_train_list, label='training') plt.xticks(range(len(eta_list)), eta_list, fontsize='xx-small') plt.xlabel('learning rate', fontsize='small') plt.ylabel('cost value', fontsize='small') plt.title('cost value by learning rate') plt.legend(loc='best', fontsize='small') plt.savefig('1 cost vs learning rate.png') plt.close() #plot accuracy plt.plot(range(len(eta_list)), acc_train_list, label='training') plt.xticks(range(len(eta_list)), eta_list, fontsize='xx-small') plt.xlabel('learning rate', fontsize='small') plt.ylabel('accuracy', fontsize='small') plt.title('accuracy by learning rate') plt.legend(loc='best', fontsize='small') plt.savefig('1 accuracy vs learning rate.png') plt.close() # running with new minimum and maximum value of learning rates n_epoch=30 n_step=1125 eta_min=1e-3 eta_max=1e-1 n_node = 100 model_NN = NeuralNetwork(n_hidden=n_node) model_NN.fit(X_train, Y_train, y_train, X_val, Y_val, y_val, lambda_=lambda_, keep_prob=0.75, n_batch=n_batch, n_epoch=n_epoch, n_step=n_step, eta_min=eta_min, eta_max=eta_max, shuffle=True, cost=True, cyclical=True, type_norm=norm) print('training accuracy: {}'.format(model_NN.predict(X_train_norm, y_train))) print('validation accuracy: {}'.format(model_NN.predict(X_val_norm, y_val))) print('testing accuracy: {}'.format(model_NN.predict(X_test_norm, y_test))) fname = "1 lambda:{}, n_batch:{}, n_epoch:{}, eta:{}, n_step:{}".format(lambda_, n_batch, n_epoch, 'cyclic', n_step) model_NN.plotting(filename=fname) end = time.time() print(end - start)
true
8c76941030abcf61dbac229ce5c21a0c48e11745
Python
lenaromanenko/twitter_sentiment_analysis
/docker_compose/tweet_collector/tweet_collector.py
UTF-8
1,556
2.546875
3
[ "MIT" ]
permissive
#import time #import os #from datetime import datetime import logging #import random import config from tweepy import OAuthHandler, Cursor, API from tweepy.streaming import StreamListener import logging import pymongo # Redirect logs to a file logging.basicConfig(filename='debug.log', level=logging.WARNING) # Create a connection to the MongoDB database server client = pymongo.MongoClient(host='mongodb') # hostname = servicename for docker-compose pipeline # Create/use a database db = client.tweets #equivalent of CREATE DATABASE tweets; # Define the collection collection = db.tweet_data #equivalent of CREATE TABLE tweet_data; def authenticate(): """Function for handling Twitter Authentication. Please note that this script assumes you have a file called config.py which stores the 2 required authentication tokens: 1. API_KEY 2. API_SECRET See course material for instructions on getting your own Twitter credentials. """ auth = OAuthHandler(config.API_KEY, config.API_SECRET) return auth if __name__ == '__main__': auth = authenticate() api = API(auth) cursor = Cursor( api.user_timeline, id = 'BioNTech_Group', tweet_mode = 'extended' ) for status in cursor.items(10000): tweet = { 'text': status.full_text, 'username': status.user.screen_name, 'followers_count': status.user.followers_count } collection.insert_one(tweet) print(tweet)
true
a1b6d3bbfbdb0b443f797dedceeedb3cbc28020e
Python
alekrutkowski/rfmt
/inst/python/rfmt_vim.py
UTF-8
885
2.53125
3
[ "Apache-2.0" ]
permissive
"""Rudimentary integration of rfmt into vim. - Add to your .vimrc: let rfmt_executable = "<path-to-rfmt-executable>" map <C-I> :pyf <path-to-this-file>/rfmt_vim.py<cr> imap <C-I> <c-o>:pyf <path-to-this-file>/rfmt_vim.py<cr> """ import difflib import subprocess import vim rfmt_cmd = vim.eval('rfmt_executable') text = '\n'.join(vim.current.buffer) try: p = subprocess.Popen(rfmt_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) stdout, stderr = p.communicate(input=text) if stderr: print stderr if stdout: lines = stdout.split('\n') sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines) for op in reversed(sequence.get_opcodes()): if op[0] is not 'equal': vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]] except RuntimeError as e: print e
true
3b70fefa8f8f2859f9bcb992467545289c564f73
Python
vineetjc/Monopoly-Custom
/tokenselect.py
UTF-8
5,276
2.625
3
[]
no_license
import pygame, sys, random,time, eztext from pygame.locals import * pygame.init() #setup the window display windowSurface = pygame.display.set_mode((960,640), 0, 32) pygame.display.set_caption('Super Mumbo Epicness') #the title of window #setup font basicFont = pygame.font.SysFont(None, 48) #set colors R,G,B code BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) VIOLET = (148,0,221) YELLOW=(255,215,0) #Token images Car=pygame.image.load('Images//Tokens/Car.jpeg') Dog=pygame.image.load('Images//Tokens/Dog.jpeg') Thimble=pygame.image.load('Images//Tokens/Thimble.jpeg') Trolley=pygame.image.load('Images//Tokens/Trolley.jpeg') Ship=pygame.image.load('Images//Tokens/Ship.jpeg') Iron=pygame.image.load('Images//Tokens/Iron.jpeg') Hat=pygame.image.load('Images//Tokens/Hat.jpeg') Shoe=pygame.image.load('Images//Tokens/Shoe.jpeg') #Other image assets back=pygame.image.load('Images/back.png') backbox=back.get_rect(center=(40,18.5)) ok=pygame.image.load('Images/ok.jpg') okbox=ok.get_rect(center=(920,640-18.5)) BG=pygame.image.load('Images/tokenselectbg.jpg') tokenlist=[Car, Dog, Thimble, Trolley, Ship, Iron, Hat, Shoe] def tokenselect(playerno,Playernames): PLAYERTOKENS=[] names_and_icons=[0 for i in range(4)] #names_and_icons which contains tuples of name and image #list to store rects for all 8 token images / integer corresponding to player number in place if player selected token rectangles=['null' for i in range(8)] idx=1 q=0 while 0<idx<=playerno+1: for event in pygame.event.get(): if event.type==QUIT: pygame.quit() sys.exit() if event.type==pygame.MOUSEBUTTONDOWN and event.button==1: pos=event.pos if backbox.collidepoint(pos): if idx>0: idx-=1 if idx==0: #goes back to playersinput return 0, [], [] break q-=1 for l in rectangles: if l==idx: rectangles[rectangles.index(l)]='changed' #temporarily replace the integer till rect is assigned for drawing black/white rectangles later break if idx>playerno: if okbox.collidepoint(pos): v=1 while v<=playerno: for i in range(8): if type(rectangles[i])==int: #i.e. token is chosen by that player if rectangles[i]==v: #v-th player has chosen that token PLAYERTOKENS.append(tokenlist[i]) v+=1 idx = playerno + 2 if idx<=playerno: for rec in rectangles: if type(rec)!=int: #i.e. 'clickable rect' if rec.collidepoint(pos): names_and_icons[q]=(Playernames[idx-1], rec) idx+=1 q+=1 rectangles[rectangles.index(rec)]=idx-1 #change rectangle type to current player number break j=130 k=0 windowSurface.blit(pygame.transform.scale(BG, (960,640)), (0,0)) for e in range(8): if e<4: k=240 if e==4: j=130 if e>=4: k=400 buttonclick=tokenlist[e].get_rect(center=(j,k)) if type(rectangles[e])==int: #is an already selected rect, colour it black pygame.draw.rect(windowSurface, BLACK, (buttonclick.left, buttonclick.top, buttonclick.width, buttonclick.height)) else: #is not selected yet, make rect rectangles[e]=buttonclick pygame.draw.rect(windowSurface, WHITE, (buttonclick.left, buttonclick.top, buttonclick.width, buttonclick.height)) windowSurface.blit(tokenlist[e],buttonclick) j+=240 if idx>playerno: finish=basicFont.render('Click OK to proceed to game!', True, VIOLET) finishbox=finish.get_rect(center=(500,600)) windowSurface.blit(finish,finishbox) windowSurface.blit(ok,okbox) else: prompts = basicFont.render('Player '+str(idx)+" "+Playernames[q]+' choose your token', True, VIOLET) box=prompts.get_rect(center=(500,600)) windowSurface.blit(prompts,box) windowSurface.blit(back,backbox) pygame.display.flip() pygame.display.flip() if len(Playernames)>playerno: #Assigning random CPU tokens diff=len(Playernames)-playerno for i in range(diff): R=random.randint(0,7) while tokenlist[R] in PLAYERTOKENS: R=random.randint(0,7) PLAYERTOKENS.append(tokenlist[R]) return 1, PLAYERTOKENS, names_and_icons
true
d037903e16015bb3841adc8a79f979b11deaeb77
Python
DigitalVeer/Discord-Option-Observer
/tda_handler.py
UTF-8
5,098
2.640625
3
[ "MIT" ]
permissive
from logging import error import re, requests from datetime import datetime class TDAHandler: APITEMPLATE = "https://api.tdameritrade.com/v1/marketdata/chains?apikey=A0&symbol=A1&contractType=A2&includeQuotes=TRUE&strategy=SINGLE&strike=A3&fromDate=A4&toDate=A4" TRACK_PREFIX="!track" COST_DELIMITER="@" def __init__(self, input=None, apikey=None): self.TOS = None self.TICKER = None self.DAY = None self.MONTH = None self.YEAR = None self.CALLPUT = None self.STRIKE = None self.FULLDATE = None self.OPTION = None self.REQUEST = None self.JSON = None self.APIKey = apikey if input is not None: self.set_new_option(input) def set_new_option(self, input): if self.determineType(input) == "TOS": self.tos_to_components(input) else: self.tos_to_components(self.option_to_tos(input)) #will add regex validation another time def determineType(self, str): if (str[0]=='.' and str.count(' ')==0): return 'TOS' else: return 'OPTION' def option_to_tos(self, option): clean_str = list( filter(None, option .replace(self.COST_DELIMITER, " ") .replace(self.TRACK_PREFIX, "") .split(" ")) ) ticker, date, strike, call_put, *_ = clean_str date_fields = date.split("-") #2021-05-21 is acceptable as well as 05-21 (defaults to current year) if (len(date_fields) == 2): month, day, = date_fields year = datetime.today().year else: year, month, day, = date_fields year = str(year).replace("20", ""); tos_str = (f'.{ticker}{year}{month}{day}{call_put[0]}{strike}').upper(); self.TOS = tos_str return tos_str def tos_to_components(self, tos_str): components = re.match(r'\.([A-Z]+)(\d\d)(\d\d)(\d\d)([CP])([\d\.]+)',tos_str).groups() TICKER, YEAR, MONTH, DAY, CALLPUT, STRIKE = components YEAR = "20" + YEAR CALLPUT = 'CALL' if CALLPUT == 'C' else 'PUT' FULL_DATE=f"{YEAR}-{MONTH}-{DAY}" self.TOS = tos_str self.OPTION = f"{TICKER} {FULL_DATE} {STRIKE} {CALLPUT}" self.TICKER = TICKER self.YEAR = YEAR self.MONTH = MONTH self.DAY = DAY self.FULLDATE = FULL_DATE self.CALLPUT = CALLPUT self.STRIKE = STRIKE def input_components_into_api(self, apikey=None): API_HANDLE = ( self.APITEMPLATE .replace("A0", self.APIKey or apikey) .replace("A1", self.TICKER) .replace("A2", self.CALLPUT) .replace("A3", self.STRIKE) .replace("A4", self.FULLDATE) ) self.REQUEST = API_HANDLE #Credit: https://hackersandslackers.com/extract-data-from-complex-json-python/ def json_extract(self, key): arr = [] def extract(obj, arr, key): if isinstance(obj, dict): for k, v in obj.items(): if isinstance(v, (dict, list)): extract(v, arr, key) elif k == key: arr.append(v) elif isinstance(obj, list): for item in obj: extract(item, arr, key) return arr values = extract(self.JSON, arr, key) return values def get_fields_from_tos(self, field, tos_str=None, apikey=None): self.tos_to_components(tos_str or self.TOS) self.input_components_into_api(apikey or self.APIKey) response = requests.get(self.REQUEST) self.JSON = response.json() field = self.json_extract(field) return field def get_cost_from_tos(self, tos_str=None, apikey=None): print(self.OPTION) fields = self.get_fields_from_tos("mark", tos_str, apikey) cost = fields[-1] return cost def get_volume_from_tos(self, tos_str=None, apikey=None): print(self.OPTION) fields = self.get_fields_from_tos("totalVolume", tos_str, apikey) cost = fields[-1] return cost def get_open_interest_from_tos(self, tos_str=None, apikey=None): attempts = 0 while True: attempts = attempts + 1 fields = self.get_fields_from_tos("openInterest", tos_str, apikey) if fields: openInterest = fields[0] return openInterest if attempts > 5: error("Could not get OI!") def validate_is_option(self, tos_str=None, apikey=None): fields = self.get_fields_from_tos("status", tos_str, apikey) print(fields[0])
true
3208369ee946c3ce3e8ecfd5a605ba11ed810249
Python
travismturner/Robot_Hello
/HelloLibrary.py
UTF-8
612
2.78125
3
[]
no_license
import os.path import subprocess import sys class HelloLibrary(object): def __init__(self): self.path = os.path.join(os.path.dirname(__file__),'Hello.py') self.status = '' def status_should_be(self, expected_status): if expected_status != self.status: raise AssertionError("Expected status to be '%s' but was '%s'." % (expected_status, self.status)) def get_response(self, num): command = [sys.executable, self.path, num] process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self.status = process.communicate()[0].strip()
true
7c20e91b9dc0de68145bcb28a15e2f88c1bbc761
Python
ssruiz/IS2_R09
/IS2_R09/apps/home/views.py
UTF-8
5,429
2.53125
3
[]
no_license
# -*- encoding: utf-8 -*- """ Vistas (Views) ============== Módulo que contiene las vistas del módulo L{Home<IS2_R09.apps.home>}, encargadas de controlar las distintas operaciones aplicables al mismo. """ from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth import login,logout,authenticate from django.http import HttpResponseRedirect from IS2_R09.apps.home.forms import login_form, recuperar_contra from django.contrib.auth.decorators import login_required from IS2_R09.settings import URL_LOGIN from django.contrib.auth.models import User from django.core.mail import send_mail # Create your views here. # vista inicial del sistema @login_required(login_url= URL_LOGIN) def index_view(request): """ index_view(request) Index ===== Vista inicial del sistema que administra la página que ve el usuario al logearse. @note: es utilizada solamente una vez, al logearse. @param request: Contiene información sobre la consulta realizada a la vista como el usuario que la hizo, desde dónde se hizo, datos que incluye la consulta(si existieran) etc. """ return render_to_response('home/index.html',{'usuario':request.user},context_instance= RequestContext(request)) def menu_view(request): """ menu_view(request) Menú ==== Vista del sistema que administra la página que ve el usuario al acceder al menú. @param request: Contiene información sobre la consulta realizada a la vista como el usuario que la hizo, desde dónde se hizo, datos que incluye la consulta(si existieran) etc. """ return render_to_response('home/menu.html',{'usuario':request.user},context_instance= RequestContext(request)) # vista del login def login_view(request): """ login_view(request) Login ===== Vista inicial del sistema que administra la página que ve el usuario tratar de acceder al sistema. Se encarga de controlar si el usuario esta registrado en el sistema y en dicho caso permitirle el acceso. @param request: Contiene información sobre la consulta realizada a la vista como el usuario que la hizo, desde dónde se hizo, datos que incluye la consulta(si existieran) etc. """ mensaje = "" if request.user.is_authenticated(): return HttpResponseRedirect('/') else: if request.method == "POST": form = login_form(request.POST) if form.is_valid(): next = request.POST['next'] username = form.cleaned_data['username'] password = form.cleaned_data['password'] usuario = authenticate(username=username,password=password) ctx = {'usuario':username} if usuario is not None and usuario.is_active: login(request, usuario) return HttpResponseRedirect(next) #return HttpResponseRedirect('/') else: mensaje = "Usuario y/o password incorrectos" next = request.REQUEST.get('next') form = login_form() ctx= {'form':form,'next':next,'mensaje':mensaje} return render_to_response('home/login.html',ctx,context_instance=RequestContext(request)) def logout_view(request): """ logout_view(request) Logout ====== Vista del sistema que administra el cierre de sesión del usuario logeado. @param request: Contiene información sobre la consulta realizada a la vista como el usuario que la hizo, desde dónde se hizo, datos que incluye la consulta(si existieran) etc. """ logout(request) return HttpResponseRedirect('/login/') def recuperar_pass_view(request): """ recuperar_pass_view(request) Recuperar Contraseña ==================== Vista del sistema que administra la recuperación de la contraseña de cierto usuario. Se solicita el email del usuario, se controla que el email este registrado en la base de datos y en dicho caso se genera una contraseña aleatoria y se le asigna al usuario notificandole vía mail los cambios y su nueva contraseña. @param request: Contiene información sobre la consulta realizada a la vista como el usuario que la hizo, desde dónde se hizo, datos que incluye la consulta(si existieran) etc. """ form = recuperar_contra() if request.method == "POST": form = recuperar_contra(request.POST) if form.is_valid(): mail =form.cleaned_data['email'] passw= User.objects.make_random_password() user = User.objects.get(email = mail) user.set_password(passw) user.save() send_mail('Recuperacion de contrasenha', 'Usuario su nuevo password es %s.' %(passw), 'is2.pagiles@gmail.co', [mail], fail_silently=False) return HttpResponseRedirect('/login/') else: ctx = {'form':form} return render_to_response('home/passw_recovery.html',ctx,context_instance= RequestContext(request)) ctx = {'form':form} return render_to_response('home/passw_recovery.html',ctx,context_instance= RequestContext(request))
true
9a764277fa8a27405a401b5ce082227792345bdd
Python
jamesfallon99/CA117
/week04/swap_v1_042.py
UTF-8
136
2.875
3
[]
no_license
#!/usr/bin/env python3 def swap_keys_values(d): new_d = {} for k, v in d.items(): new_d[v] = k return new_d
true
18b4267c49aa4068fbc017b15835c820690ac2af
Python
cathalhughes/eyelearn
/eyelearn-frontend/get_averages.py
UTF-8
1,621
2.625
3
[]
no_license
from app import create_app, db from app.models import Activity_Results, Daily_Average, Daily_Class_Average, Student_Daily_Average, Class_Daily_Average, Class_Average import datetime import requests app = create_app() with app.app_context(): db.init_app(app) def get_daily_averages(): print("in here") current_time = datetime.datetime.utcnow() one_day_ago = current_time - datetime.timedelta(days=1) print(one_day_ago) a = Activity_Results() students_daily_averages = a.get_average_in_class_for_every_student(time=one_day_ago).all() print(students_daily_averages) for student in students_daily_averages: daily_average = Daily_Average(average=student[0], date=current_time) db.session.add(daily_average) db.session.commit() student_daily_average = Student_Daily_Average(user_id=student[2], average_id=daily_average.average_id) class_daily_average = Class_Daily_Average(class_id=student[1], average_id=daily_average.average_id) db.session.add_all([student_daily_average, class_daily_average]) db.session.commit() class_daily_averages = a.get_average_for_class(time=one_day_ago).all() print(class_daily_averages) for classx in class_daily_averages: daily_class_average = Daily_Class_Average(average=classx[0], date=current_time) db.session.add(daily_class_average) db.session.commit() class_average = Class_Average(class_id=classx[1], average_id=daily_class_average.average_id) db.session.add(class_average) db.session.commit() print("Added daily Averages")
true
cd24966f033f2dc7db0cd19609d44c77d9a0e743
Python
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_1/382.py
UTF-8
930
2.71875
3
[]
no_license
import sets, sys fh = open("inputs/%s" % sys.argv[1], 'r') lines = fh.readlines() engines = sets.Set() cases = int(lines[0]) index = 1 output = open("outputs/A.out", 'w') #O(N) in input, O(2N) in memory, could be better #I spent over 90 minutes combing the input and output before I realized I was starting my case numbers base 0, YAY for i in range(0, cases): engines.clear() engineCount = int(lines[index]) index += engineCount + 1 queryCount = int(lines[index]) index += 1 queries = lines[index:index+queryCount] switchCount = 0 #print "Engine Count: %s" % engineCount count = 0 for query in queries: count += 1 engines.add(query.rstrip('\n')) if len(engines) == engineCount: engines.clear() engines.add(query.rstrip('\n')) switchCount += 1 output.write("Case #%i: %i\n" % (i+1, switchCount)) index += queryCount
true
2127016efa86d121ef3e68795731e0ca462d45a3
Python
Georgeh30/Curso_2_Python
/clases/video51_interfaces_graficas(checkbutton).py
UTF-8
1,938
3.890625
4
[]
no_license
from tkinter import * root = Tk() root.title("Ejemplo") # Inicializando variables playa = IntVar() montana = IntVar() turismoRural = IntVar() # Funcion para indicar cuales se han seleccionado def opcionesViaje(): opcionesEscogida = "" if playa.get() == 1: opcionesEscogida += " playa" if montana.get() == 1: opcionesEscogida += " montaña" if turismoRural.get() == 1: opcionesEscogida += " turismo rural" textoFinal.config(text=opcionesEscogida) # Obteniendo una imagen desde la ruta indicada foto = PhotoImage(file="../img/cerdo.png") # Insertando Imagen dentro del label_text y empaquetandolo dentro del root Label(root, image=foto).pack() frame = Frame(root) frame.pack() Label(frame, text="Elige Destinos", width=50).pack() """ FUNCION DE CADA ATRIBUTO DENTRO DE LOS CHECKBUTTONS: 1. frame --> indica que debe de estar dentro del frame 2. text --> para mostrar el texto dentro del checkbutton 3. variable --> enlaza variable inicializada hasta arriba del codigo con el checkbutton ... para guardar el valor que obtenga de "onvalue" y "offvalue". 4. onvalue --> manda el valor "1" a la variable "playa" indicando que esta seleccionada 5. offvalue --> manda el valor "0" a la variable "playa" indicando que NO esta seleccionada 6. command --> para mandar a llamar la funcion 7. .pack() --> empaqueta el objeto checkbutton dentro del frame """ # Creando y empaquetando varios checkbutton dentro de root Checkbutton(frame, text="Playa", variable=playa, onvalue=1, offvalue=0, command=opcionesViaje).pack() Checkbutton(frame, text="Montaña", variable=montana, onvalue=1, offvalue=0, command=opcionesViaje).pack() Checkbutton(frame, text="Turismo", variable=turismoRural, onvalue=1, offvalue=0, command=opcionesViaje).pack() # LabelText para mostrar las opciones seleccionadas textoFinal = Label(frame) textoFinal.pack() root.mainloop()
true
810dc06dffd974b11a2cfd21407b4dc341d086d2
Python
shubham2652/HR_Resume_Management
/ML model and API/LogisticRegression.py
UTF-8
1,575
2.53125
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Fri Feb 28 07:00:57 2020 @author: Shubham Shah """ # -*- coding: utf-8 -*- """ Created on Tue Jan 21 16:20:22 2020 @author: Shubham Shah """ import pandas as pd dataset = pd.read_csv('Data.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, -1].values from sklearn.preprocessing import LabelEncoder,OneHotEncoder from sklearn.compose import ColumnTransformer labelencoder_X = LabelEncoder() X[:,2] = labelencoder_X.fit_transform(X[:,2]) X[:,3] = labelencoder_X.fit_transform(X[:,3]) """transformer = ColumnTransformer( transformers=[ ("OneHot", OneHotEncoder(), [2,3] ) ], remainder='passthrough' ) X = transformer.fit_transform(X.tolist()) X = X.astype('float64')""" labelencoder_Y = LabelEncoder() y = labelencoder_Y.fit_transform(y) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train[:,[0,1,4]] = sc_X.fit_transform(X_train[:,[0,1,4]]) X_test[:,[0,1,4]] = sc_X.transform(X_test[:,[0,1,4]]) def featurescale(skill,experiance,testScore): a = [skill,experiance,testScore] featured_value=(sc_X.transform([a])) return featured_value from sklearn.linear_model import LogisticRegression classifier = LogisticRegression(random_state = 0) classifier.fit(X_train,y_train) y_pred = classifier.predict(X_test) from sklearn.externals import joblib joblib.dump(classifier,'model2.pkl')
true
ee2f966488cb3ba5a69d1147771cca5eacc134b2
Python
BaronDaugherty/400-Data-Structure-and-Algorithm-Problems
/2 - Sort binary array in linear time.py
UTF-8
398
3.890625
4
[]
no_license
#create an array and pass for processing def main(): arr = [1,0,1,0,1,0,0,1] print(proc(arr)) #process the array def proc(a): #number of zeros zero = a.count(0) #0 to number of zeros - 1, make them all 0 for x in range(zero): a[x] = 0 #make the rest 1 for x in range(zero+1, len(a)-1): a[x] = 1 #return the processed array return a main()
true
be6589c1e7870317c8343b37476cc0ddf79fcefb
Python
udaypatel1/My_Python_Projects
/MeetingAvailability.py
UTF-8
8,456
3
3
[]
no_license
import math as m pOneSchedule = [ ["09:00", "10:30"],["12:00", "13:00"],["16:00", "18:00"], ] pOneBounds = ["09:00", "20:00"] #################################### pTwoSchedule = [ ["10:00", "11:30"],["12:30", "14:30"],["14:30", "15:00"],["16:00", "17:00"] ] pTwoBounds = ["10:00", "18:30"] #################################### meetingDuration = 30 #################################### ''' dataset 2 ''' p1 = [ ["07:35", "11:22"],["12:00", "13:10"],["14:00", "16:48"] ] p1Bound = ["6:55", "18:00"] p2 = [ ["10:00", "10:45"],["12:00", "13:30"],["17:45", "20:00"],["20:30", "21:30"] ] p2Bound = ["8:30", "21:30"] meetTime = 15 def addTimes(time1, time2): totalMin1 = toMinutes(time1) totalMin2 = toMinutes(time2) bothTotal = totalMin1 + totalMin2 finalTime = toTimeFormat(bothTotal) return finalTime def toTimeFormat(minutes): hour = minutes // 60 minute = minutes % 60 strMinute = "" strHour = "" if minute == 0: strMinute = "00" else: if len(str(minute)) == 1: strMinute = "0" + str(minute) else: strMinute = str(minute) if hour == 0: strHour = "00" else: if len(str(hour)) == 1: strHour = "0" + str(hour) else: strHour = str(hour) final = strHour + ":" + strMinute return final def toMinutes(time): intHour1 = int(time.split(':')[0]) totalMin1 = (intHour1 * 60) + int(time.split(':')[1]) #print(time.split(':')[1]) return totalMin1 def compareTimes(time1, time2): totalMin1 = toMinutes(time1) totalMin2 = toMinutes(time2) if totalMin1 < totalMin2: return -1 elif totalMin1 > totalMin2: return 1 else: return 0 def differenceBetween(time1,time2): # returns difference between two times in minutes totalMin1 = toMinutes(time1) totalMin2 = toMinutes(time2) return totalMin1 - totalMin2 def meetingAvailability(pOneSchedule, pOneBounds, pTwoSchedule, pTwoBounds, meetingDuration): mergedSchedules = [] ptr1 = 0 ptr2 = 0 ptr1Status = True ptr2Status = True while ptr1 != len(pOneSchedule) or ptr2 != len(pTwoSchedule): if ptr1 == len(pOneSchedule): mergedSchedules.append(pTwoSchedule[ptr2]) ptr2 += 1 ptr1Status = False continue elif ptr2 == len(pTwoSchedule): mergedSchedules.append(pOneSchedule[ptr1]) ptr1 += 1 ptr2Status = False continue if ptr1Status == True and ptr2Status == True: endCross = pOneSchedule[ptr1][1] startCross = pTwoSchedule[ptr2][0] if compareTimes(endCross, startCross) == -1 or compareTimes(endCross, startCross) == 0 and (ptr1Status == True and ptr2Status == True): #endCross is less than startCross OR endCross is equal to startCross # append them to merged schedule in order mergedSchedules.append(pOneSchedule[ptr1]) mergedSchedules.append(pTwoSchedule[ptr2]) elif compareTimes(endCross, startCross) == 1 and (ptr1Status == True and ptr2Status == True): #endCross is greater than startCross # take start of endCross block and end of startCross block and append the pair tempList = [] startOfEndCross = pOneSchedule[ptr1][0] endOfStartCross = pTwoSchedule[ptr2][1] exception = False if toMinutes(endCross) >= toMinutes(endOfStartCross): tempList.append(startOfEndCross) tempList.append(endCross) exception = True if compareTimes(startOfEndCross, endOfStartCross) == 1 and (exception == False): # reorder in appending tempList.append(endOfStartCross) tempList.append(startOfEndCross) else: if(exception == False): tempList.append(startOfEndCross) tempList.append(endOfStartCross) mergedSchedules.append(tempList) if ptr1Status == True and ptr2Status == True: ptr1+=1 ptr2+=1 # mergedSchedules should be populated after this while loop # parse the bounds and add them to the mergedSchedules beginBound = [] endBound = [] if compareTimes(pOneBounds[0],pTwoBounds[0]) == -1 or compareTimes(pOneBounds[0], pTwoBounds[0]) == 0: # if start time of pOneBound is less than or equal to start time of pTwoBound beginBound = ["0:00", pOneBounds[0]] else: beginBound = ["0:00", pTwoBounds[0]] if compareTimes(pOneBounds[1], pTwoBounds[1]) == 1 or compareTimes(pOneBounds[1], pTwoBounds[1]) == 0: endBound = [pOneBounds[1], "24:00"] else: endBound = [pTwoBounds[1], "24:00"] mergedSchedules.insert(0,beginBound) mergedSchedules.append(endBound) # mergedSchedule is a complete with bounds # print(mergedSchedules) freeSlots = [] for elem in range(len(mergedSchedules)): tempList = [] start = mergedSchedules[elem][1] try: end = mergedSchedules[elem + 1][0] except: break tempList.append(start) tempList.append(end) freeSlots.append(tempList) #print("Merged: ", mergedSchedules) #print('Unparsed Free Slots', freeSlots) # parse through freeSlots and find ones that are of meetingDuration validMeetingSlots = [] for elem in range(len(freeSlots)): # remove invalid free slots with respect to meeting duration try: meetingDifference = differenceBetween(freeSlots[elem][1], freeSlots[elem][0]) except: break if meetingDifference < meetingDuration: del freeSlots[elem] #print("Parsed Free Slots ", freeSlots) for elem in range(len(freeSlots)): meetingDifference = differenceBetween(freeSlots[elem][1], freeSlots[elem][0]) if meetingDifference == meetingDuration: validMeetingSlots.append(freeSlots[elem]) elif meetingDifference > meetingDuration: lenOfLoop = meetingDifference // meetingDuration # floor division firstRun = True for i in range(lenOfLoop): tempList = [] if firstRun == False: tempList.append(validMeetingSlots[-1][-1]) #print(validMeetingSlots[-1]) toMin = toMinutes(validMeetingSlots[-1][-1]) newTime = toMin + meetingDuration formattedTime = toTimeFormat(newTime) tempList.append(formattedTime) else: tempList.append(freeSlots[elem][0]) toMin = toMinutes(freeSlots[elem][0]) newTime = toMin + meetingDuration formattedTime = toTimeFormat(newTime) tempList.append(formattedTime) firstRun = False validMeetingSlots.append(tempList) #print("Valid Meeting Slots in Time Duration: ", validMeetingSlots) return mergedSchedules, freeSlots, validMeetingSlots ''' @parameters - person one schedule (in format) - person one working bounds (in format) - person two schedule (in format) - person two working bounds (in format) - time of meeting (in minutes) @return (in order) - merged busy schedules of both persons - all possible free slots among merged schedules - valid free slots with respect to the length of meeting ''' mergedSchedules, allFreeSlots, durationalFreeSlots = meetingAvailability(pOneSchedule, pOneBounds, pTwoSchedule, pTwoBounds, meetingDuration) #mergedSchedules, allFreeSlots, durationalFreeSlots = meetingAvailability(p1, p1Bound, p2, p2Bound, meetTime) print("Merged Schedules: \n") print(mergedSchedules) print() print("All Free Slots: \n") print(allFreeSlots) print() print("Durational Free Slots \n") print(durationalFreeSlots)
true
a00a56d698b7e39b9f708e39aa69172c405132ad
Python
AdamZhouSE/pythonHomework
/Code/CodeRecords/2308/60812/289780.py
UTF-8
512
3.125
3
[]
no_license
def inorder(tree, node, answer): lch, rch = tree[node] last = 0 if lch != 0: last = inorder(tree, lch, answer) answer[last] = node if rch != 0: return inorder(tree, rch, answer) return node n, root = [int(i) for i in input().split(' ')] tree = {i: [] for i in range(1, n+1)} for i in range(n): fa, lch, rch = [int(i) for i in input().split(' ')] tree[fa] = [lch, rch] if root != 0: answer = {} inorder(tree, root, answer) print(answer[int(input())])
true
80cbb41356dd0cbaf78fe8f955987eae6fdb650c
Python
keyliin0/2048-Solver
/main.py
UTF-8
1,695
2.71875
3
[]
no_license
import gym_2048 import gym import pygame import search grid_size = 70 def render(screen, observation): black = (0, 0, 0) grey = (128, 128, 128) blue = (0, 0, 128) white = (255, 255, 255) tile_colour_map = { 2: (238, 228, 218), 4: (237, 224, 200), 8: (242, 177, 121), 16: (234, 149, 99), 32: (246, 124, 95), 64: (246, 94, 59), 128: (237, 207, 114), 256: (237,204,97), 512: (237,200,80), 1024: (237,197,63), 2048: (237,197,1), } # Background screen.fill(black) # Board pygame.draw.rect(screen, grey, (0, 0, grid_size * 4, grid_size * 4)) myfont = pygame.font.SysFont('Tahome', 30) for y in range(4): for x in range(4): o = observation[y][x] if o: pygame.draw.rect(screen, tile_colour_map[o], (x * grid_size, y * grid_size, grid_size, grid_size)) text = myfont.render(str(o), False, white) text_rect = text.get_rect() width = text_rect.width height = text_rect.height assert width < grid_size assert height < grid_size screen.blit(text, (x * grid_size + grid_size / 2 - text_rect.width / 2, y * grid_size + grid_size / 2 - text_rect.height / 2)) pygame.display.update() env = gym.make('2048-v0') env.seed(42) search = search search.init() height = 4 * grid_size width = 4 * grid_size screen = pygame.display.set_mode((width, height), 0, 32) pygame.font.init() current_state = env.reset() done = False while not done: best_action = search.get_best_move(env, current_state) new_state, reward, done, info = env.step(best_action) current_state = new_state render(screen, new_state) env.render() env.close()
true
08da5ed48b7a5f740c0fc58c20acb728a778e9a5
Python
JuanRojasC/Python-Mision-TIC-2021
/Control Flow Statements/Ejercicio 16 - Notas.py
UTF-8
1,055
4.15625
4
[]
no_license
# 7. Construya un programa que permita leer la nota de un examen. Mostrar mediante un mensaje el state del estudiante de acuerdo a la nota. # NOTA state # Entre 0.0 y 2.5 Deficiente # Entre 2.6 y 3.9 Insuficiente # Entre 4.0 y 4.4 Aceptable # Entre 4.5 y 4.9 Suficiente # 5.0 Excelente note1=float(input("\n ingrese nota 1 >>> ")) note2=float(input("\n ingrese nota 2 >>> ")) note3=float(input("\n ingrese nota 3 >>> ")) percentNote1 = (note1 / 5) * 0.3 percentNote2 = (note2 / 5) * 0.2 percentNote3 = (note3 / 5) * 0.5 finalNote = (percentNote1 + percentNote2 + percentNote3) * 5 if finalNote <= 2.5 : state = 'Deficiente' elif 2.6 <= finalNote <= 3.9 : state = 'Insuficiente' elif 4.0 <= finalNote <= 4.4 : state = 'Aceptable' elif 4.5 <= finalNote <= 4.9 : state = 'Suficiente' elif finalNote == 5 : state = 'Excelente' print('\n La calificacion del estudiante es', state, '\n') # print('\n Su nota es {:0.1f}' .format(finalNote) , 'se encuentra aprobado' if finalNote>=3.5 else 'se encuentra reprobado')
true