def testVectorOp(): x = [23, 34, 53] y = [12, 17, 7] additon = op.Addition(x, y) subtraction = op.Subtraction(x, y) innerProduct = op.InnerProduct(x, y) crossProduct = op.CrossProduct(x, y) scalarProduct = op.ScalarMultiplication(x, .5) print(additon, subtraction, innerProduct, crossProduct, x, sep='\n')
def AOPSinusoidModeling(filename, WindowSize=2): path = 'C:\\Users\\shijingliu\\workspace\\PowerFactor\\' file = filename finalname = path + file + '.txt' LabelVector, DataMatrix = DataFileLoader.load(finalname) AOPcolumn = VectorOperations.FindColumn('AOP', LabelVector) if AOPcolumn > 10: print "finding new AOP" AOPcolumn = VectorOperations.FindColumn('AOP 1', LabelVector) AOP = DataMatrix[:, AOPcolumn] 'declare a file' saveEVFile = open('SinusoidModeling CPR Flow 347.csv', 'wb') fileWriter = csv.writer(saveEVFile) fileWriter.writerows( [["index", "estimated A:", "estimated B", "estimated D"]]) for i in range((len(AOP) / 100) - WindowSize): 'define the start time and end time of each interval' StartTime = i EndTime = StartTime + WindowSize AopInterval = AOP[StartTime * 100:EndTime * 100] t = np.linspace(StartTime, EndTime - 0.01, WindowSize * 100) 'figure out the appropriate guess using FFT' amplitude = np.abs(np.fft.fft(AopInterval))[1:(len(t) / 2 + 1)] frequency = np.fft.fftfreq(len(t), 0.01)[1:(len(t) / 2 + 1)] 'find out the maximum amplitude and its corresponding frequency' maxFreq, maxAmp = MaximumRecorder(amplitude) 'now we guess the a, b, c, d for the sinusoid modeling' guess_a = VectorOperations.RMS( scipy.signal.detrend(AopInterval)) * np.sqrt(2) guess_b = (3.1415926 * 2.0) * frequency[maxFreq] guess_c = 0.0 guess_d = np.mean(AopInterval) 'optimize the guess values using least square algorithm' optimize_func = lambda x: x[0] * np.sin(x[1] * t + x[2]) + x[ 3] - AopInterval result = leastsq(optimize_func, [guess_a, guess_b, guess_c, guess_d]) 'we only record the sets when the least square can converge' if (result[1] == 1) or (result[1] == 2) or (result[1] == 3) or (result[1] == 4): est_a, est_b, est_c, est_d = result[0] fileWriter.writerows([[i, est_a, est_b, est_d]]) saveEVFile.close()
def PowerFactor(filename, time, type): path = 'C:\\Users\\shijingliu\\workspace\\PowerFactor\\' file = filename filename = path + file + '.txt' LabelVector, DataMatrix = DataFileLoader.LoadADIData(filename) AORTScolumn = VectorOperations.FindColumn('Aorta', LabelVector) AOPcolumn = VectorOperations.FindColumn('AOP', LabelVector) RAPcolumn = VectorOperations.FindColumn('RAP', LabelVector) IVCTScolumn = VectorOperations.FindColumn('IVC', LabelVector) if AOPcolumn > 10: print "finding new AOP" RAPcolumn = VectorOperations.FindColumn('RAP 1', LabelVector) AOPcolumn = VectorOperations.FindColumn('AOP 1', LabelVector) if type == 'aorta': 'obtain data from the first t seconds' Aorts = DataMatrix[:, AORTScolumn][0:time * 100] 'process the flow one more time get all absolute values' AbsAorts = np.abs(Aorts) Aop = DataMatrix[:, AOPcolumn][0:time * 100] S = np.multiply(AbsAorts, Aop) elif type == 'vena': Ivcts = DataMatrix[:, IVCTScolumn][0:time * 100] AbsIvcts = np.abs(Ivcts) Rap = DataMatrix[:, RAPcolumn][0:time * 100] S = np.multiply(AbsIvcts, Rap) else: print "wrong input!" return 'smooth the value with 11 in window and hanning in type' sasmooth = VectorOperations.smooth(S, 11, 'hanning') 'obtain the RMS value of t minutes baseline' SValue = VectorOperations.RMS(sasmooth[0:12000], 0) 'obtain the min, max value of each phase' min, max = VectorOperations.FindExtrema(sasmooth, 0.6, 100) 'now we obtain the RMS value of each phase during t minutes' SEachPhase = [] for i in range(2, len(max)): SEachPhase.append( VectorOperations.RMS(sasmooth[max[i - 1][0]:max[i][0]], 0)) 'obtain the power factor vector' PF = [x / (SValue * 1.0) for x in SEachPhase] return PF
def Basis(u, v): temp = copy.deepcopy(u) VectorOperations.ScalarMultiplication( temp, VectorOperations.InnerProduct(temp, v) / lengthnorms.LengthNorm2(temp)**2) VectorOperations.ScalarMultiplication(temp, 1 / lengthnorms.LengthNorm2(temp)) orthogonal = copy.deepcopy(temp) orthogonal[0] *= -1 return temp, orthogonal
def AMSAcalculation(filename, windowSize=4, timeStep=1): path = 'C:\\Users\\shijingliu\\workspace\\PowerFactor\\' file = filename finalname = path + file + '.txt' LabelVector, DataMatrix = DataFileLoader.LoadADIData(finalname) EKGcolumn = VectorOperations.FindColumn('EKG', LabelVector) time = DataMatrix[:, 0] EKG = DataMatrix[:, EKGcolumn] AMSA = [] for i in xrange(0, len(time) / 100, timeStep): intervalStart = i intervalEnd = i + windowSize currentTS = time[intervalStart * 100:intervalEnd * 100] currentES = EKG[intervalStart * 100:intervalEnd * 100] 'first of all get rid of nan value in EKG' recordNan = [] for j in range(len(currentES)): if np.isnan(currentES[j]): recordNan.append(j) currentESRefine = currentES[~np.isnan(currentES)] currentTSRefine = np.delete(currentTS, recordNan) 'now we can apply the FFT' time_step = 0.01 freqs = np.fft.fftfreq(len(currentTSRefine), time_step) halfFreqs = freqs[0:len(freqs) / 2] 'then we calculate the amplitude using FFT' amplitude = np.abs(np.fft.fft(currentESRefine))**2 amplitudeNorm = amplitude / np.sum(amplitude) 'only analyze half of the amplitude due to symmetrical problems' halfAmplitude = amplitudeNorm[0:len(amplitude) / 2] 'now we need to get rid of the frequency beyond the range of 4 and 48 ' amplitudefilter = [] frequencyfilter = [] for k in range(len(halfFreqs)): if halfFreqs[k] >= 4.0 and halfFreqs[k] <= 48.0: frequencyfilter.append(halfFreqs[k]) amplitudefilter.append(halfAmplitude[k]) 'now calculate the amsa score here' AMSA.append(np.sum(np.multiply(amplitudefilter, frequencyfilter))) return AMSA
def FFTAnalysis(filename, windowSize=4, timeStep=1): path = 'C:\\Users\\shijingliu\\workspace\\PowerFactor\\' file = filename finalname = path + file + '.txt' LabelVector, DataMatrix = DataFileLoader.LoadADIData(finalname) EKGcolumn = VectorOperations.FindColumn('EKG', LabelVector) time = DataMatrix[:, 0] EKG = DataMatrix[:, EKGcolumn] Fmean = [] Fmax = [] Amean = [] Amax = [] for i in xrange(0, len(time) / 100, timeStep): intervalStart = i intervalEnd = i + windowSize currentTS = time[intervalStart * 100:intervalEnd * 100] currentES = EKG[intervalStart * 100:intervalEnd * 100] 'first of all get rid of nan value in EKG' recordNan = [] for j in range(len(currentES)): if np.isnan(currentES[j]): recordNan.append(j) currentESRefine = currentES[~np.isnan(currentES)] currentTSRefine = np.delete(currentTS, recordNan) 'now we can apply the FFT' time_step = 0.01 freqs = np.fft.fftfreq(len(currentTSRefine), time_step) halfFreqs = freqs[0:len(freqs) / 2] 'then we calculate the amplitude using FFT' amplitude = np.abs(np.fft.fft(currentESRefine))**2 amplitudeNorm = amplitude / np.sum(amplitude) 'only analyze half of the amplitude due to symmetrical problems' halfAmplitude = amplitudeNorm[0:len(amplitude) / 2] 'now we calculate the Fmean, Fmax, Amean, and Amax' Fmean.append(halfFreqs.mean()) Fmax.append(halfFreqs.max()) Amean.append(halfAmplitude.mean()) Amax.append(halfAmplitude.max()) return Fmax, Fmean, Amax, Amean
def EigenValueAnalysis(filename, windowSize=1): path = 'C:\\Users\\shijingliu\\workspace\\PowerFactor\\' file = filename finalname = path + file + '.txt' LabelVector, DataMatrix = DataFileLoader.LoadADIData(finalname) EKGcolumn = VectorOperations.FindColumn('EKG', LabelVector) time = DataMatrix[:, 0] EKG = DataMatrix[:, EKGcolumn] 'first of all get rid of nan value in EKG' recordNan = [] for j in range(len(EKG)): if np.isnan(EKG[j]): recordNan.append(j) EKGrefined = EKG[~np.isnan(EKG)] Timerefined = np.delete(time, recordNan) 'declare a file' saveEVFile = open('EigenVector and EigenValue CPR Flow 347.csv', 'wb') fileWriter = csv.writer(saveEVFile) 'now we go through the entire txt data file' for i in xrange(0, (len(Timerefined) / 100)): intervalStart = i intervalEnd = i + windowSize * windowSize currentTS = Timerefined[intervalStart * 100:intervalEnd * 100] currentES = EKGrefined[intervalStart * 100:intervalEnd * 100] 'matrix construction' MConstruction = np.zeros(shape=(10 * windowSize, 10 * windowSize)) for j in range(10 * windowSize): center = ( currentES[j * 10 * windowSize + 5 * windowSize] + currentES[j * 10 * windowSize + 5 * windowSize - 1]) / 2.0 for k in range(10 * windowSize): MConstruction[j][k] = currentTS[j * 10 * windowSize + k] - center 'then calculate the eigenvectors' eigenvalues, eigenvectors = np.linalg.eig(MConstruction) fileWriter.writerows([[i]]) fileWriter.writerows([["eigenvalues:"]]) fileWriter.writerows([eigenvalues]) fileWriter.writerows([["eigenvectors:"]]) fileWriter.writerows(eigenvectors) fileWriter.writerows([""]) saveEVFile.close()
def PowerFactor(filename, time, type): path = 'C:\\Users\\shijingliu\\workspace\\PowerFactor\\' file = filename filename = path+file+'.txt' LabelVector, DataMatrix = DataFileLoader.LoadADIData(filename) AORTScolumn = VectorOperations.FindColumn('Aorta', LabelVector) AOPcolumn = VectorOperations.FindColumn('AOP',LabelVector) RAPcolumn = VectorOperations.FindColumn('RAP',LabelVector) IVCTScolumn = VectorOperations.FindColumn('IVC', LabelVector) if AOPcolumn > 10: print "finding new AOP" RAPcolumn = VectorOperations.FindColumn('RAP 1',LabelVector) AOPcolumn = VectorOperations.FindColumn('AOP 1',LabelVector) if type == 'aorta': 'obtain data from the first t seconds' Aorts = DataMatrix[:,AORTScolumn][0:time*100] 'process the flow one more time get all absolute values' AbsAorts = np.abs(Aorts) Aop = DataMatrix[:,AOPcolumn][0:time*100] S = np.multiply(AbsAorts, Aop) elif type == 'vena': Ivcts = DataMatrix[:,IVCTScolumn][0:time*100] AbsIvcts = np.abs(Ivcts) Rap = DataMatrix[:,RAPcolumn][0:time*100] S = np.multiply(AbsIvcts, Rap) else: print "wrong input!" return 'smooth the value with 11 in window and hanning in type' sasmooth = VectorOperations.smooth(S, 11, 'hanning') 'obtain the RMS value of t minutes baseline' SValue = VectorOperations.RMS(sasmooth[0:12000], 0) 'obtain the min, max value of each phase' min, max = VectorOperations.FindExtrema(sasmooth, 0.6, 100) 'now we obtain the RMS value of each phase during t minutes' SEachPhase = [] for i in range (2, len(max)): SEachPhase.append(VectorOperations.RMS(sasmooth[max[i-1][0]:max[i][0]], 0)) 'obtain the power factor vector' PF = [x/(SValue*1.0) for x in SEachPhase] return PF
1) Norm 2) Unit Vector 3) Scalar Multiplication 4) Addition 5) Subtraction 6) Dot Product 7) Angle 8) Cross Product (Only for 3D vectors) """) if vector_selection == "1": size = int(input("Enter the size of the vector:")) vector = [ int(input("Enter value for the vector: ")) for i in range(size) ] norm = VectorOperations.norm(vector) print("Norm: ", norm) if vector_selection == "2": size = int(input("Enter the size of the vector:")) vector = [int(input("Enter value for vector: ")) for i in range(size)] unit_vector = VectorOperations.unit(vector) print(unit_vector) if vector_selection == "3": size = int(input("Enter the size of the vector:")) vector = [int(input("Enter Value for Vector: ")) for i in range(size)] scalar = float(input("Please input scale factor: ")) scaled_vector = VectorOperations.scalar_multiply(vector, scalar) print(scaled_vector) if vector_selection == "4": size = int(input("Enter the size of the vectors:")) vector = [
def best_fit(x, terms=1, step=1): h = get_h(terms, len(x), step) a = VecOps.multiply_matrices(VecOps.transpose(h), h) b = VecOps.multiply_matrices(VecOps.transpose(h), x) c = VecOps.multiply_matrices(VecOps.get_inverse(a), b) return c / step
def least_squares(actual, axis_coords): a = VecOps.multiply_matrices(VecOps.transpose(axis_coords), actual) b = VecOps.multiply_matrices(VecOps.transpose(axis_coords), axis_coords) return a[0][0] / b[0][0]
def setUp(self): self.matrix1 = Vo.rand_matrix(5, 5, -5, 5) self.matrix2 = Vo.rand_matrix(5, 1, -5, 5) self.identity = Vo.get_identity(5)
def test_gaussian_solve(self): solved = Vo.gaussian_solve(self.matrix1, self.matrix2) solved = Vo.multiply_matrices(self.matrix1, solved) for i in range(5): self.assertAlmostEqual(solved[i][0], self.matrix2[i][0])
def parseObj(string, batch): vertex_list = [] face_list = [] vertex_normals = { } #key is index of vertex, value is list of normals for three faces #bounding box for knot minCoord = [None, None, None] maxCoord = [None, None, None] for line in string.splitlines(): data = [string.strip() for string in re.split(" +", line)] #assumes that vertices are written before faces if data[0] == 'v': thisVertex = [float(vertex) for vertex in data[1:]] for i in range(len(thisVertex)): if minCoord[i] == None or minCoord[i] > thisVertex[i]: minCoord[i] = thisVertex[i] if maxCoord[i] == None or maxCoord[i] < thisVertex[i]: maxCoord[i] = thisVertex[i] vertex_list += thisVertex if data[0] == 'f': indices = [int(tri) - 1 for tri in data[1:]] face_list += indices vertex1 = vertex_list[((indices[0]) * 3):((indices[0] + 1) * 3)] vertex2 = vertex_list[((indices[1]) * 3):((indices[1] + 1) * 3)] vertex3 = vertex_list[((indices[2]) * 3):((indices[2] + 1) * 3)] vector1 = vecop.createVector(vertex1, vertex2) vector2 = vecop.createVector(vertex1, vertex3) normal = vecop.crossProduct(vector1, vector2) for key in indices: if key in vertex_normals: vertex_normals[key].append(normal) else: vertex_normals[key] = [normal] #logic to resize the knot DESIRED_SIDE_LENGTH = 1 center = [(max + min) / 2 for max, min in zip(maxCoord, minCoord)] sideLengths = [max - min for max, min in zip(maxCoord, minCoord)] divisor = max(sideLengths) / DESIRED_SIDE_LENGTH for index in range(len(vertex_list)): comp = index % 3 #0 for x, 1 for y, 2 for z vertex_list[index] -= center[comp] vertex_list[index] /= divisor calculatedVertexNormals = [] for index, normals in sorted(vertex_normals.items()): sum = normals[0] for i in range(1, len(normals)): sum = vecop.vectorSum(sum, normals[i]) calculatedVertexNormals += vecop.normalize(sum) batch.add_indexed( len(vertex_list) // 3, GL_TRIANGLES, None, face_list, ('v3f', vertex_list), ('n3f', calculatedVertexNormals))