def test_contained_square(self): poly1 = matrix([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0), ]) poly2 = matrix([(-10, -10), (20, -10), (20, 20), (-10, 20), (-10, -10), ]) new_poly = find_overlapping_polygon(poly1, poly2) result = check_polygon_equality(new_poly, poly1) self.assertTrue(result)
def ExponentialMask(self): w, h, d = self.vdim wx = WinFx.Exponential(w) wy = WinFx.Exponential(h) wz = WinFx.Exponential(d) xy = matrix(wy).T * matrix(wx) for z in range(d): self.data[z,:,:] *= xy * wz[z] return self
def GaussianMask(self): w, h, d = self.vdim wx = WinFx.Gaussian(CalcGaussianSigma(w), w) wy = WinFx.Gaussian(CalcGaussianSigma(h), h) wz = WinFx.Gaussian(CalcGaussianSigma(d), d) xy = matrix(wy).T * matrix(wx) for z in range(d): self.data[z,:,:] *= xy * wz[z] return self
def Hanning(clz, dim, dtype=float): v = np.ndarray(dim[::-1], dtype=float) w = hanning(dim[0]) h = hanning(dim[1]) d = hanning(dim[2]) p = matrix(h).T * matrix(w) for z in range(dim[2]): v[z,:,:] = p * d[z] if dtype is not float: return clz(v).AsType(dtype) return clz(v)
def Gaussian(clz, sigmas, dtype=float): dim = 2 * (ceil(array(sigmas) * 3).astype(int32) | 1) + 1 v = np.ndarray(dim[::-1], dtype=float) w = WinFx.Gaussian(sigmas[0], dim[0]) h = WinFx.Gaussian(sigmas[1], dim[1]) d = WinFx.Gaussian(sigmas[2], dim[2]) p = matrix(h).T * matrix(w) for z in range(dim[2]): v[z,:,:] = p * d[z] if dtype is not float: return clz(v).AsType(dtype) return clz(v)
def test_two_overlapping_squares(self): poly1 = matrix([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0), ]) dx, dy = (5, 5) trans_mat = getTranslationMatrix2d(dx, dy) homogeneous_trans_mat = dot(trans_mat, vstack((transpose(poly1), ones((1, poly1.shape[0]))))) poly2 = transpose(homogeneous_trans_mat[0:2, :]) intersection = matrix([(5, 5), (5, 10), (10, 10), (10, 5), (5, 5), ]) new_poly = find_overlapping_polygon(poly1, poly2) self.assertNotEqual(new_poly, None) self.assertTupleEqual(new_poly.shape, (5, 2)) result = check_polygon_equality(new_poly, intersection) self.assertTrue(result)
def logicreg_mle_iteration_reduce_single_dim(Y, X, i): ill_arr = [i] #Only one index X_reduce = logicreg_matrix_column_shrink(X, ill_arr) w_init = transpose(matrix(zeros(X_reduce.shape[1]))) w_reduced = logicreg_mle_iteration(Y, X_reduce, w_init) return X_reduce, w_reduced
def sat_in_enu(R_u, R_sat): """ Satellite coordinates in ENU at users position R_u :param R_u: (X,Y,Z) -- user's coordinates in ECEF (numpy array) :param R_sat: (X,Y,Z) -- satellite's coordinates in ECEF (numpy array) :return: unit vector of the direction to the satellite in local `east, north, up` coords See [1] p. 522 """ if isinstance(R_sat, list): R_sat = np.array(R_sat) R = R_sat - R_u phi_theta_h = ecef_to_lat_lon_alt(R_u, deg=False) # coordinate transformation matrix from ECEF to ENU: sin_p, sin_t = map(sin, phi_theta_h[:2]) cos_p, cos_t = map(cos, phi_theta_h[:2]) C_ecef_to_enu = matrix([[-sin_t, cos_t, 0], [-sin_p * cos_t, -sin_p * sin_t, cos_p], [cos_p * cos_t, cos_p * sin_t, sin_p]]) # coordinate origin shift vector from ECEF to local ENU: # S_enu = matrix([[R_u[0] * sin_t - R_u[1] * cos_t], # [R_u[0] * sin_p * cos_t - R_u[1] * sin_p * sin_t - R_u[2] * cos_p], # [-R_u[0] * cos_p * cos_t - R_u[1] * cos_p * sin_t - R_u[2] * sin_t]]) X_enu = C_ecef_to_enu * R.reshape((3, 1))# + S_enu # return normalized vector: return (X_enu / norm(X_enu)).flatten().getA()[0]
def sat_in_enu(R_u, R_sat): """ Satellite coordinates in ENU at users position R_u :param R_u: (X,Y,Z) -- user's coordinates in ECEF (numpy array) :param R_sat: (X,Y,Z) -- satellite's coordinates in ECEF (numpy array) :return: unit vector of the direction to the satellite in local `east, north, up` coords See [1] p. 522 """ if isinstance(R_sat, list): R_sat = np.array(R_sat) R = R_sat - R_u phi_theta_h = ecef_to_lat_lon_alt(R_u, deg=False) # coordinate transformation matrix from ECEF to ENU: sin_p, sin_t = map(sin, phi_theta_h[:2]) cos_p, cos_t = map(cos, phi_theta_h[:2]) C_ecef_to_enu = matrix([[-sin_t, cos_t, 0], [-sin_p * cos_t, -sin_p * sin_t, cos_p], [cos_p * cos_t, cos_p * sin_t, sin_p]]) # coordinate origin shift vector from ECEF to local ENU: # S_enu = matrix([[R_u[0] * sin_t - R_u[1] * cos_t], # [R_u[0] * sin_p * cos_t - R_u[1] * sin_p * sin_t - R_u[2] * cos_p], # [-R_u[0] * cos_p * cos_t - R_u[1] * cos_p * sin_t - R_u[2] * sin_t]]) X_enu = C_ecef_to_enu * R.reshape((3, 1)) # + S_enu # return normalized vector: return (X_enu / norm(X_enu)).flatten().getA()[0]
def test_rotated_squares(self): poly1 = matrix([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0), ]) rot_mat = getRotationMatrix2D((5, 5), 45, 1.0) homogeneous_poly1 = vstack((transpose(poly1), ones((1, poly1.shape[0])))) poly2 = transpose(dot(rot_mat, homogeneous_poly1)) new_poly = find_overlapping_polygon(poly1, poly2) ## plot the result # import matplotlib.pyplot as plt # from matplotlib.path import Path # import matplotlib.patches as patches # path = Path(new_poly) # fig = plt.figure() # ax = fig.add_subplot(111) # patch = patches.PathPatch(path, facecolor='orange', lw=2) # ax.add_patch(patch) # ax.set_xlim(-5,15) # ax.set_ylim(-5,15) # plt.show() # should be an octagon self.assertEqual(new_poly.shape[0], 9)
def logicreg_Matrix_column_shrink_recovery(X, indexes): sorted_indexes = sorted(indexes) X_pad = X zero_pad = matrix(X[:, 0] * 0) for i in sorted_indexes: X_head = append(X_pad[:, 0:i], zero_pad, 1) X_tail = X_pad[:, i:] X_pad = append(X_head, X_tail, 1) return X_pad
def main(): l1=list() for i in range(3): l1.append(list()) for j in range(3): if(i==j): l1[i].append(1) else: l1[i].append(0) m1=ml.matrix(l1) print(m1)
def get_adjugate_matrix(self): matrix = self.getA() adjugate_matrix_as_array = [] for i, line in enumerate(matrix): adjugate_matrix_as_array.append([]) for j, row in enumerate(line): tpm_sub_matrix = np.delete(matrix, i, 0) tpm_sub_matrix = np.delete(tpm_sub_matrix, j, 1) co_factor = pow(-1, i + j) * np.linalg.det(tpm_sub_matrix) adjugate_matrix_as_array[i].append(co_factor) adjugate_matrix = matrix_lib.matrix(adjugate_matrix_as_array) return adjugate_matrix
def logicreg_likelihood_ratio_chi_square_norm(Y, X, w): dim_size = w.shape[0] ratio_arr = array(zeros(dim_size)) #Raw score computation P = logicreg_func(X, w) L_base = logicreg_log_likelihood_func(Y, P) for i in range(dim_size): X_reduced, w_reduced = logicreg_mle_iteration_reduce_single_dim(Y, X, i) P_reduced = logicreg_func(X_reduced, w_reduced) L_reduced = logicreg_log_likelihood_func(Y, P_reduced) ratio = -2 * (L_reduced - L_base) ratio_arr[i] = ratio return transpose(matrix(ratio_arr))
def reduce(self): # En gros, calcul du barycentre, et définition du type en fonction du rapport (distmin/distmax) # distX = distX au barycentre self.pointList = nm.matrix([[self.pointList[k][0] for k in range(len(self.pointList))], [self.pointList[k][1] for k in range(len(self.pointList))]]) self.center = self.pointList.mean(1) dp = (self.pointList - self.center).getA() # matrice des vecteurs (colonne) ecart au barycentre r = [np.array([dp[0][k], dp[1][k]]) for k in range(dp.shape[1])] # liste des vecteurs ecart d = [np.linalg.norm(w) > 0.1 for w in r] # array des distances au barycentre if True in d: self.type = Obstacle.TYPE_LINE else: self.type = Obstacle.TYPE_ROUND
def logicreg_mle_training(Y, X, Y_test, X_test): init_dim = X.shape[1] #Get training data set w_opt = transpose(matrix(zeros(X.shape[1]))) accuracy_control = 0.75 ill_history = [] old_accuracy = 0.0 training_round = 0 while True: training_round += 1 #Param training -- core process w_opt = logicreg_mle_iteration(Y, X, w_opt) #Quality control: Param accuracy computing. accuracy = logicreg_accuracy(Y_test, X_test, w_opt) print 'Accuracy is:', accuracy, ' Training round:', training_round #Quality control: Param validate and filter, X and w_opt will be shrunk Y, X, w_opt, ill_arr = logicreg_likelihood_ratio_filter(Y, X, w_opt) #Terminating policy if size(ill_arr) > 0 or accuracy < accuracy_control: if training_round < 20 or old_accuracy != accuracy: #Initialize the w_opt to new dim size with zero value w_opt = transpose(matrix(zeros(X.shape[1]))) X_test = logicreg_matrix_column_shrink(X_test, ill_arr) ill_history += [ill_arr] old_accuracy = accuracy continue else: print 'Terminated, can not met accuracy requiredment, current Accuracy is:', accuracy break else: print 'Finished, current Accuracy is:', accuracy break if size(w_opt) > 0: #Recover the shrunk w to initial size (fill blanks with '0') return logicreg_w_dim_recovery(w_opt, ill_history) else: print 'There is no param left for this logic model, maybe you should divide the data set first...' return transpose(matrix(zeros(init_dim)))
def test_two_non_overlapping_squares(self): poly1 = matrix([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0), ]) dxys = [(-8, 0), (0, 8), (8, 0), (0, -8)] for dx, dy in dxys: if (dx, dy) == (0, 0): continue trans_mat = getTranslationMatrix2d(dx, dy) homogeneous_trans_mat = dot(trans_mat, vstack((transpose(poly1), ones((1, poly1.shape[0]))))) poly2 = transpose(homogeneous_trans_mat[0:2, :]) new_poly = find_overlapping_polygon(poly1, poly2) area = find_polygon_area(new_poly) self.assertAlmostEqual(area, 2 * 10)
def test_two_non_overlapping_squares(self): poly1 = matrix([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0), ]) dxs = [-10, 10, 0] dys = [-10, 10, 0] for dx in dxs: for dy in dys: if (dx, dy) == (0, 0): continue trans_mat = getTranslationMatrix2d(dx, dy) homogeneous_trans_mat = dot(trans_mat, vstack((transpose(poly1), ones((1, poly1.shape[0]))))) poly2 = transpose(homogeneous_trans_mat[0:2, :]) new_poly = find_overlapping_polygon(poly1, poly2) self.assertEqual(new_poly, None)
import numpy as np import numpy.matrixlib as ml l1 = [1, 2, 3], [4, 5, 6], [7, 8, 9] mat1 = ml.matrix(l1) mat2 = (1 / mat1) print(mat1) print(mat2)
def x_rotate(self, angle: int): a = radians(angle) tmp = matrix([[1, 0, 0], [0, cos(a), -sin(a)], [0, sin(a), cos(a)]]) tmp = np.linalg.inv(tmp) self.m = tmp * self.m
def test_add_multiple_keys(self): m = create_matrix_from_list_of_tuple((("x", "A", 1), ("y", "B", 100))) self.assertDictEqual(m.column_keys, {"A": 0, "B": 1}) self.assertDictEqual(m.row_keys, {"x": 0, "y": 1}) self.assertTrue((m.elements == matrix([[1, 0], [0, 100]])).all())
import numpy as np import scipy.optimize as so import numpy.matrixlib as nm ######################################################################## ### Module-local tuple of matrices of Fourier fit coefficents ### - Index within tuple is order of matrix ### - Each principal axis' (PA's) coefficients are on one line in this file ### - Note .T (transpose) at end of each so PA's coefs will be a column mtxlist = ( None, None ### 2-term Fourier fit: a0 a1 b1 a2 b2 , nm.matrix( [ [-15.94, -7.522, 48.97, -5.918, -3.235 ] ### B[0] , [ 2.484, -22.72, -9.989, 2.358, -4.198 ] ### B[1] , [ 34.93, -2.168, 10.02, -1.838, -0.6224] ### B[2] ] ).T ### 3-term Fourier fit: a0 a1 b1 a2 b2 a3 b3 , nm.matrix( [ [ 19.04, -37.98, -0.4392, -0.4125, -8.412, 1.689, 0.5891] ### B[0] , [ 13.87, 4.463, -19.73, 4.672, 1.369, -0.7784, 0.889 ] ### B[1] , [ -4.907, -8.234, 0.601, -0.0403, -1.91, 0.442, 0.1858] ### B[2] ] ).T , ) ######################################################################## def buildvec(theta, order): """ Build row vector of Fourier cos(n*Theta) and sin(n*Theta) terms to be