def linear_coef_a_b(x1, y1, x2, y2): """ Gives coefficients of the line between two points (x1,y1) & (x2,y2) x1,y1,x2,y2 can be iterables Parameters ---------- x1,y1,x2,y2 : float or list or numpy.array Coordinates of the 1st and the 2nd point Returns ------- a : float regression coefficient b1 & b2 : float regression offsets coefficient (b1 must be equal to b2) """ if genefun.is_iterable(x1): x1 = np.array(x1, dtype=np.float64) x2 = np.array(x2, dtype=np.float64) y1 = np.array(y1, dtype=np.float64) y2 = np.array(y2, dtype=np.float64) else: x1 = float(x1) x2 = float(x2) y1 = float(y1) y2 = float(y2) a = (y2 - y1) / (x2 - x1) b1 = y1 - a * x1 b2 = y2 - a * x2 return a, b1, b2
def fuv_calc(V, A, P=1, normafuv=1): """ Args : V : residuals vector A : Jacobian matrix P : weight matrix Can manage both standard arrays and sparse array Returns : fuv : Facteur unitaire de variance (unitary variance factor) Notes : le fuv dépend de la martice de poids mais les sigmas non ex : poids de 10**-6 fuv : 439828.260843 sigma : [ 5.21009306 5.09591568 0.04098106] poids de 1 fuv : 4.39828260843e-07 sigma : [ 5.21009306 5.09591568 0.04098106] """ V = np.squeeze(np.array(V)) if not genefun.is_iterable(P): P = np.ones(len(V)) * P elif scipy.sparse.issparse(P): P = P.diagonal() else: print( "DEPRECIATION : modification done in fuv_calc, P should be given as Matrix-shaped now" ) P = P.diagonal() P = P * (1 / normafuv) VPV = np.column_stack((V, P, V)) numera = np.sum(np.product(VPV, 1)) # nummera is just an adaptation of VT * P * V # EDIT 1806 : Je veux bien ... mais c'est une adaptation pourrie ! # ou alors il faut bien s'assurer que l'on a extrait la diagonale de P if A.ndim == 1: A = np.expand_dims(A, 0) fuv = numera / np.abs(A.shape[0] - A.shape[1]) return fuv
def savage_buford_formula(Vs,X,d): """ X : distance à la faille , un iterable pour toutes le profil, un nombre pour la longeur max d : profondeur de la faille retourne X , et Vdeform(X) X et d doivent être dans la même unité, Vs pas forcément """ if not genefun.is_iterable(X): X = np.arange(-X,X,1) return X , ( Vs / np.pi ) * np.arctan2(X,d)
def kwargs_for_jacobian(kwdic_generik, kwdic_variables): """ Building a list of kwargs for the jacobian function kwdic_generik : parameters which not gonna change kwdic_variable : parameters which gonna change, so must be associated with iterable """ keys_list = list(kwdic_variables.keys()) for k, v in kwdic_variables.items(): if not genefun.is_iterable(v): print('WARN : key', k, 'val', v, 'is not iterable !!!') values_combined = itertools.product(*list(kwdic_variables.values())) kwdic_list_out = [] for values in values_combined: kwdic_out = dict(kwdic_generik) for k, v in zip(keys_list, values): kwdic_out[k] = v kwdic_list_out.append(kwdic_out) return kwdic_list_out
def outlier_above_below(X, threshold_values, reference=np.nanmean, theshold_absolute=True, return_booleans=True, theshold_relative_value="reference", verbose=False): """ Gives values of X which are between threshold values Parameters ---------- threshold_values : single value (float) or a 2-tuple (lower bound theshold , upper bound theshold) `WARN` : those value(s) have to be positives. Minus sign for lower bound and plus sign for upper one will be applied internally reference : float or callable the central reference value can be a absolute fixed value (float) or a function (e.g. np.mean of np.median) theshold_absolute : bool if True threshold_values are absolutes values >>> low = reference - threshold_values[0] >>> upp = reference + threshold_values[1] if False they are fractions of theshold_relative_value >>> low = reference - threshold_values[0] * theshold_relative_value >>> upp = reference + threshold_values[1] * theshold_relative_value (see also below) theshold_relative_value : str or function if the string "reference" or None is given, then it the reference value which is used if it is a fuction (e.g. np.std()) then it is this value returned by this function which is used Only useful when theshold_absolute = False return_booleans : bool return booleans or not verbose : bool Returns ------- Xout : numpy array X between low_bound & upp_bound bbool : numpy array X-sized array of booleans """ if genefun.is_iterable(threshold_values): ths_input_low = threshold_values[0] ths_input_upp = threshold_values[1] else: ths_input_low = threshold_values ths_input_upp = threshold_values if ths_input_low < 0. or ths_input_upp < 0.: print( "WARN : outlier_above_below : threshold_values have to be positive" ) print(" minus sign for lower bound will be applied internally") if callable(reference): ref_val = reference(X) else: ref_val = reference if theshold_relative_value in ("reference", None): relativ_val = reference elif callable(theshold_relative_value): relativ_val = theshold_relative_value(X) else: relativ_val = reference if theshold_absolute: ths_low = ref_val - ths_input_low ths_upp = ref_val + ths_input_upp else: ths_low = ref_val - ths_input_low * relativ_val ths_upp = ref_val + ths_input_upp * relativ_val if verbose: print("INFO : outlier_above_below theshold values") print(" reference : ", ref_val) print(" effective lower bound : ", ths_low) print(" effective upper bound : ", ths_upp) Xout, bbool = outlier_above_below_simple(X, ths_low, ths_upp) if return_booleans: return Xout, bbool else: return Xout
def rotate_points(alphal,betal,gammal,pointlin,Rtype='R1', xyzreftuple = ([1, 0, 0], [0, 1, 0], [0, 0, 1]), angtype='deg',fullout = False): ''' R1 = Rz(g) * Ry(b) * Rx(a) si les RPY sont donnés dans le NED alors les positions résultantes sont dans le NED R2 = matrice RPY2ENU si les RPY sont donnés dans le NED alors les résultantes sont DANS LE ENU pas besoin de rotation NED2ENU Grewal et al. 2007 Entrée : Angles n = A liste de listes de P * [ points ] Sortie : liste de listes [ [ xA ] [ xA ] ... xP [ xA ] ] ''' xaxis, yaxis, zaxis = xyzreftuple if not genefun.is_iterable(alphal): alphal = np.array([alphal]) betal = np.array([betal]) gammal = np.array([gammal]) boolnotiterable = True else: boolnotiterable = False pointlout = [] R_out = [] for pt in pointlin: if not genefun.is_iterable(pt) or len(pt) != 3: print("ERR : rotate_points : pts != 3 coords") return 0 pointltmp = [] for a,b,g in zip(alphal,betal,gammal): R1 = rotmat3(a,b,g,angtype=angtype,xyzreftuple=xyzreftuple) R2 = C_rpy2enu(a,b,g,angtype=angtype) if Rtype == 'R1': R = R1 elif Rtype == 'R2': R = R2 R_out.append(R) pointltmp.append(np.dot(R,pt)) pointlout.append(pointltmp) if boolnotiterable: pointlout = pointltmp pointlout = np.array(pointlout) if fullout: return pointlout , R_out else: return pointlout
def partial_derive_old(f, var_in, var_out=0, kwargs_f={}, args_f=[], h=0): ''' var_in : detrivation with respect to this variable can be a int (starts with 0) or a string descirbing the name of the var in f var_out : the output of f which needs to be considerated as the output ** must be a int ** args_f & kwargs_f : tuple/list & dict describing the arguments of f h : derivation step, if h == 0 give x * sqrt(epsilon) (source : http://en.wikipedia.org/wiki/Numerical_differentiation) ''' # tuple => list pour plus d'aisance args_f = list(args_f) # operational arguments args_f_m = list(args_f) args_f_p = list(args_f) kwargs_f_m = dict(kwargs_f) kwargs_f_p = dict(kwargs_f) args_name_list = list(f.__code__.co_varnames) # var in is a int if type(var_in) is int: var_ind = var_in var_name = args_name_list[var_ind] # var in is a str else: var_name = var_in try: var_ind = args_name_list.index(var_name) except ValueError: print(args_name_list) raise Exception('wrong var_in name (not in args name list)') # if var_ind < len(args_f): # x = args_f[var_ind] # if h == 0: # h = x * np.sqrt(np.finfo(float).eps) # if h == 0: # print 'WARN : h == 0 ! setting @ 10**-6 ' # h = 10**-6 # args_f_m[var_ind] = x - h # args_f_p[var_ind] = x + h # else: # x = kwargs_f[var_name] # if h == 0: # h = x * np.sqrt(np.finfo(float).eps) # if h == 0: # print 'WARN : h == 0 ! setting @ 10**-6 ' # h = 10**-6 # kwargs_f_m[var_name] = x - h # kwargs_f_p[var_name] = x + h if var_ind < len(args_f): x = args_f[var_ind] else: x = kwargs_f[var_name] if h == 0: h = x * np.sqrt(np.finfo(float).eps) if h == 0: print('WARN : h == 0 ! setting @ 10**-6 ') h = 10**-6 if var_ind < len(args_f): args_f_m[var_ind] = x - h args_f_p[var_ind] = x + h else: kwargs_f_m[var_name] = x - h kwargs_f_p[var_name] = x + h m = f(*args_f_m, **kwargs_f_m) p = f(*args_f_p, **kwargs_f_p) if genefun.is_iterable(m): m = m[var_out] p = p[var_out] # print p,m,h,x # print h # print h == 0 dout = (p - m) / (2. * float(h)) return dout
def partial_derive(f, var_in, var_out=0, kwargs_f={}, args_f=[], h=0, accur=-1): ''' var_in : detrivation with respect to this variable can be a int (starts with 0) or a string describing the name of the var in f var_out : the output of f which needs to be considerated as the output ** must be a int ** args_f & kwargs_f : tuple/list & dict describing the arguments of f h : derivation step, if h == 0 give x * sqrt(epsilon) (source : http://en.wikipedia.org/wiki/Numerical_differentiation) ''' # tuple => list pour plus d'aisance args_f = list(args_f) # operational arguments args_f_i = list(args_f) kwargs_f_i = dict(kwargs_f) args_name_list = list(f.__code__.co_varnames) # var in is a int if type(var_in) is int: var_ind = var_in var_name = args_name_list[var_ind] # var in is a str else: var_name = var_in try: var_ind = args_name_list.index(var_name) except ValueError: print(args_name_list) raise Exception('wrong var_in name (not in args name list)') if var_ind < len(args_f): x = args_f[var_ind] else: x = kwargs_f[var_name] if h == 0: h = x * np.sqrt(np.finfo(float).eps) if h == 0: print('WARN : h == 0 ! setting @ 10**-6 ') h = 10**-6 res_stk = [] accur_coeff = get_accur_coeff(accur) for i, k in enumerate(accur_coeff): if k == 0: res_stk.append(0.) else: if var_ind < len(args_f): args_f_i[var_ind] = x + h * (i - 4) else: kwargs_f_i[var_name] = x + h * (i - 4) res = f(*args_f_i, **kwargs_f_i) if genefun.is_iterable(res): res = res[var_out] res_stk.append(res) dout = np.dot(np.array(res_stk), accur_coeff) / h return dout