def superposition(ref_curve, curve): """ P.superposition(numpy.ndarray,numpy.ndarray) -> (numpy.ndarray,numpy.ndarray) Convenience function to perform a procrustes superposition on two curves, using the reference curve as the template for the rotation of the other curve. The output will be a tuple with the refence curve and the other curve superposed respectively. Note that if the curves don't have the same number of points, this will take the curve with the smaller number of points and reparameterise the linear interpolation of its points using arclength. """ # firstly, we need to make sure the ref_curve and the other curve have # the same number of points. num_points = max([c.shape[1] for c in [ref_curve, curve]]) if ref_curve.shape[0] > curve.shape[0]: curve = Curve(curve).gen_num_points(ref_curve.shape[0]) else: ref_curve = Curve(ref_curve).gen_num_points(curve.shape[0]) s_ref_curve, s_curve = [ scale(translate(curve)) for curve in [ref_curve, curve] ] return (s_ref_curve, rotate(s_ref_curve, s_curve))
def test_addCaseOne(self): c = Curve(9, 5, 13) assert c.isCorrect(), "curve is not correct" p = Point(4, 1) r = addPoints(c, p, p) correctResult = Point(8, 2) assert r == correctResult, "should be (8,2)"
def test_addCaseThree(self): c = Curve(2, 2, 13) assert c.isCorrect(), "curve is not correct" p1 = Point(4, 0) p2 = Point(4, 0) r = addPoints(c, p1, p2) correctResult = Point.generateInfinity() assert r == correctResult, "incorrect result"
def test_addCaseFour(self): c = Curve(2, 9, 13) assert c.isCorrect(), "curve is not correct" p1 = Point(6, 9) p2 = Point(4, 2) r = addPoints(c, p1, p2) correctResult = Point(12, 9) assert r == correctResult, "incorrect result"
def __init__(self, paramters: Dict, password: str): """ Initializes the algorithm with the specified paramters. """ self.D = paramters self.curve = Curve(self.D['A'], self.D['B'], self.D['P']) self.G = (Mod(self.D['Gx'], self.D['P']), Mod(self.D['Gy'], self.D['P'])) self.N = self.D['N'] self.kpriv = self.intsha256(password) self.kpub = self.curve.multiply(self.G, self.kpriv)
def test_ctypto_scalar_operations(): elipcurve = Curve(1, 2) p1 = Point(-1, 0, elipcurve) p2 = Point(0, 1.414, elipcurve) print("p1 is on curve: ", elipcurve.check_if_point_is_on_curve(p1)) print("p2 is on curve: ", elipcurve.check_if_point_is_on_curve(p2)) p1.add(p2) print("p3 is on curve: ", elipcurve.check_if_point_is_on_curve(p1)) print("P1 + P2 = Point({}, {})".format(p1.get_x(), p1.get_y()))
def getNode(self,node): nameNodes=node.getElementsByTagName('OID') self.name=nameNodes[0].firstChild.nodeValue normNodes=node.getElementsByTagName('Normal') self.normal=Vector().getNode(normNodes[0]) thicknessNodes=node.getElementsByTagName('TotalThickness') if len(thicknessNodes)==0: thicknessNodes=node.getElementsByTagName('Thickness') self.thickness=float(thicknessNodes[0].firstChild.nodeValue) boundaryNodes=node.getElementsByTagName('Boundary') if len(boundaryNodes)==0: boundaryNodes=node.getElementsByTagName('Contour') complexString3dNodes=boundaryNodes[0].getElementsByTagName('ComplexString3d') if len(complexString3dNodes)==0: complexString3dNodes=node.getElementsByTagName('Contour') self.curve=Curve().getNode(complexString3dNodes[0]) return self
def setUp(self): self.aCurve = Curve() self.bCurve = Curve() self.cCurve = Curve() self.aNode = CurveNode('testDirectory1', self.aCurve, 'green') self.bNode = CurveNode('testDirectory2', self.bCurve, 'blue') self.cNode = CurveNode('testDirectory3', self.cCurve, 'pink') self.aNode.prevNode = self.cNode self.aNode.nextNode = self.bNode self.bNode.prevNode = self.aNode self.bNode.nextNode = self.cNode self.cNode.prevNode = self.bNode self.cNode.nextNode = self.aNode
def all_curves(self): curves = [] for name, values in self.datasets.items(): curve = Curve(name=name, dataset=values, flat_line_error_rate=self.flat_line_error_rate) curves.append(curve) return curves
def test_addCaseOne2(self): c = Curve( 2, 2, 47218595856952157806696569632545678027423892273209310176067431692817752992683 ) assert c.isCorrect(), "curve is not correct" p = Point( 12862157267214899810361926955908539612877409450391118811465627945348641414699, 12019096858601327682205759357597394733984175977637230947682741345278170525625 ) r = addPoints(c, p, p) correctResult = Point( 8427593452907253031911973389814307956594156143196768939002634990187043644156, 19381585424404293305376546768509776437754879171682733989060920467515335940764 ) assert r == correctResult, "incorect result"
def save(self, data): if IS_AIRPLANE_EDITOR: writeValue(self, data, 'yawMin', -179.99) writeValue(self, data, 'yawMax', 180.0) writeValue(self, data, 'pitchMin', -179.99) writeValue(self, data, 'pitchMax', 180.0) writeValue(self, data, 'trackYawMin', 0.0) writeValue(self, data, 'trackYawMax', 360.0) writeValue(self, data, 'trackPitchMin', -179.99) writeValue(self, data, 'trackPitchMax', 180.0) writeValue(self, data, 'animatorDirectionOffset', Math.Vector3(0, 0, 0)) writeValue(self, data, 'animatorDirectionDefault', Math.Vector3(0, 0, 0)) writeValue(self, data, 'animatorDieDirection', Math.Vector3(0, 0, 0)) writeValue(self, data, 'axisDirections', Math.Vector3(2, 1, 0)) writeValue(self, data, 'angularVelocity', math.pi) writeValue(self, data, 'angularThreshold', 0.0) writeValue(self, data, 'angularHalflife', 0.0) writeValue(self, data, 'pitchNodeName', 'joint3') writeValue(self, data, 'yawNodeName', 'joint2') writeValue(self, data, 'directionNodeName', 'joint3_BlendBone') writeValue(self, data, 'shootingNodeName', 'joint4') writeValue(self, data, 'idleFrequencyScalerX', 1.0) writeValue(self, data, 'idleAmplitudeScalerX', 0.02) writeValue(self, data, 'idleFrequencyScalerY', 1.0) writeValue(self, data, 'idleAmplitudeScalerY', 0.02) writeValue(self, data, 'shootTime', 0.25) writeValue(self, data, 'shootCooldownTime', 0.75) writeValue(self, data, 'shootingAmplitudeScaler', 0.05) writeValue(self, data, 'enableIdleAnimation', True) writeValue(self, data, 'useGunProfile', True) writeValue(self, data, 'recoilCurve', Curve())
def drawFigure(self, qp): size = self.size() pen = QPen(Qt.white, 1, Qt.SolidLine) qp.setPen(pen) cordinate_axes = CordinateAxes( size.width(), size.height(), self.travel_screen, self.scale * 10) cordinate_axes.draw(qp) pen = QPen(Qt.red, 2, Qt.SolidLine) qp.setPen(pen) curve = Curve(qp, size.width(), size.height(), self.__parameter, self.step, self.travel_screen, self.phi, self.scale) curve.draw()
def gather_curves(self, directory): for ii in xrange(self.num_midpoint_slices): new_curve = Curve(directory + '/curve_midslice_' + str(ii)) self.midpoint_slices.append(new_curve) for ii in xrange(self.num_critical_slices): new_curve = Curve(directory + '/curve_critslice_' + str(ii)) self.critical_point_slices.append(new_curve) critical_curve = Curve(directory + '/curve_crit') self.critical_curve.append(critical_curve) sphere_curve = Curve(directory + '/curve_crit') for ii in xrange(self.num_singular_curves): filename = directory + '/curve_singular_mult_' + str( self.singular_curve_multiplicities[ii][0]) + '_' + str( self.singular_curve_multiplicities[ii][1]) new_curve = Curve(filename) self.singular_curves.append(new_curve) self.singular_names.append(new_curve.inputfilename)
def getNode(self, node): nameNodes = node.getElementsByTagName('OID') self.name = nameNodes[0].firstChild.nodeValue sectionNodes = node.getElementsByTagName('Section') if len(sectionNodes) == 0: sectionNodes = node.getElementsByTagName('StructureCrossSection') thicknessNodes = sectionNodes[0].getElementsByTagName('Thickness') self.thickness = float(thicknessNodes[0].firstChild.nodeValue) heightNodes = sectionNodes[0].getElementsByTagName('Height') self.height = float(heightNodes[0].firstChild.nodeValue) pathNodes = node.getElementsByTagName('Path') complexString3dNodes = pathNodes[0].getElementsByTagName( 'ComplexString3d') if len(complexString3dNodes) == 0: self.curve = Curve().getNode(pathNodes[0]) else: self.curve = Curve().getNode(complexString3dNodes[0]) return self
class Floor: 'class part definition' def __init__(self): self.name = '' self.thickness = 0 self.curve = Curve() def out(self): print("name=", self.name) print(" thickness=", self.thickness) print(" lines=") for l in self.curve.lines: l.out() def center(self): R1 = self.curve.center() R2 = Vector(0, 0, 1) R2.scale(0.5 * self.thickness) return R1 + R2 def draw(self, display, c): pol = self.curve.polygon() if pol != None: pol = pol.Wire() face = BRepBuilderAPI_MakeFace(pol, True).Face() #prism = BRepPrimAPI_MakePrism(pol,n).Shape() if c == 0: color = 'YELLOW' elif c == 1: color = 'BLUE' elif c == 2: color = 'GREEN' elif c == 3: color = 'BLACK' elif c == 4: color = 'RED' elif c == 5: color = 'WHITE' elif c == 6: color = 'CYAN' else: color = 'ORANGE' display.DisplayColoredShape(face, color, update=True)
def readData(self, data): if data is None: return else: readValue(self, data, 'yawMin', -179.99) readValue(self, data, 'yawMax', 180.0) readValue(self, data, 'pitchMin', -179.99) readValue(self, data, 'pitchMax', 180.0) readValue(self, data, 'trackYawMin', 0.0) readValue(self, data, 'trackYawMax', 360.0) readValue(self, data, 'trackPitchMin', -179.99) readValue(self, data, 'trackPitchMax', 180.0) readValue(self, data, 'animatorDirectionOffset', Math.Vector3(0, 0, 0)) readValue(self, data, 'animatorDirectionDefault', Math.Vector3(0, 0, 0)) readValue(self, data, 'animatorDieDirection', Math.Vector3(0, 0, 0)) readValue(self, data, 'axisDirections', Math.Vector3(2, 1, 0)) readValue(self, data, 'angularVelocity', math.pi) readValue(self, data, 'angularThreshold', 0.0) readValue(self, data, 'angularHalflife', 0.0) readValue(self, data, 'pitchNodeName', 'joint3') readValue(self, data, 'yawNodeName', 'joint2') readValue(self, data, 'directionNodeName', 'joint3_BlendBone') readValue(self, data, 'shootingNodeName', 'joint4') readValue(self, data, 'idleFrequencyScalerX', 1.0) readValue(self, data, 'idleAmplitudeScalerX', 0.02) readValue(self, data, 'idleFrequencyScalerY', 1.0) readValue(self, data, 'idleAmplitudeScalerY', 0.02) readValue(self, data, 'shootTime', 0.25) readValue(self, data, 'shootCooldownTime', 0.75) readValue(self, data, 'enableIdleAnimation', False) readValue(self, data, 'recoilCurve', Curve()) readValue(self, data, 'useGunProfile', True) for i in range(0, 3): self.animatorDirectionOffset[i] = self.animatorDirectionOffset[ i] for i in range(0, 3): self.animatorDirectionDefault[ i] = self.animatorDirectionDefault[i] if self.pitchMin > self.pitchMax: if self.pitchMax < 0: self.pitchMax += 360 else: self.pitchMin -= 360 return
def test_multiply2(self): c = Curve( 9, 9, 1220688155435260123416698775875983763836072035444529752273150378775402574239 ) p = Point( 924812513218946557760338246264312520657414397880413636853317984556123176672, 901482186226661984437937203673347769982210913465995729381057735314565221292 ) r = mul(c, p, 932) correctResult = Point( 998036328406205595765169951306681464055471715091787640432371773378967290101, 1032505436168794803391453916475059567680570631100446822540746527697742553389 ) assert r == correctResult, "incorrect result"
def plot_graphics (self): obj=Curve() self.take_the_best_model_from_last_training() for i in range (len(self.list_of_projected_dataset)): obj.plot_2D_H (self.list_of_projected_dataset[i],self.y,self.regressors[i][self.best_est[i]],i+1) for i in range (len(self.models)): vb=list(self.list_of_projected_dataset[i]) vb=list(vb[0]) if (len(vb)>=2): obj.plot_3D_H (self.list_of_projected_dataset[i],self.y,self.regressors[i][self.best_est[i]],i+1) if (len(self.rec_deg)>0): for i in range (len(self.rec_deg)): obj.plot_degree_graphic(self.rec_deg[i].degree,self.rec_deg[i].j_train,self.rec_deg[i].j_cv,self.rec_deg[i].idx)
def __init__(self, section): readValue(self, section, 'ROLL_AXIS', 0) readValue(self, section, 'ALLOW_LEAD', 0) readValue(self, section, 'INVERT_ROLL', 0) readValue(self, section, 'ROLL_SENSITIVITY', 0.0) readValue(self, section, 'ROLL_DEAD_ZONE', 0.05) readValue(self, section, 'VERTICAL_AXIS', 2) readValue(self, section, 'INVERT_VERTICAL', 0) readValue(self, section, 'VERTICAL_SENSITIVITY', 0.0) readValue(self, section, 'VERTICAL_DEAD_ZONE', 0.05) readValue(self, section, 'FORCE_AXIS', 1) readValue(self, section, 'INVERT_FORCE', 0) readValue(self, section, 'FORCE_SENSITIVITY', 0.0) readValue(self, section, 'FORCE_DEAD_ZONE', 0.05) readValue(self, section, 'HORIZONTAL_AXIS', 3) readValue(self, section, 'INVERT_HORIZONTAL', 0) readValue(self, section, 'HORIZONTAL_SENSITIVITY', 0.0) readValue(self, section, 'HORIZONTAL_DEAD_ZONE', 0.05) readValueOnCondition(self, section, 'CAMERA_TYPE', cameraTypeCondition, default=0) readValue(self, section, 'MOUSE_SENSITIVITY', 1.0) readValue(self, section, 'MOUSE_INVERT_VERT', False) readValue(self, section, 'AUTOMATIC_FLAPS', True) readValue(self, section, 'RADIUS_OF_CONDUCTING', 1.0) readValue(self, section, 'CAMERA_FLEXIBILITY', 1.0) readValue(self, section, 'EQUALIZER_ZONE_SIZE', 0.75) readValue(self, section, 'ROLL_SPEED_CFC', 1.0) readValue(self, section, 'EQUALIZER_FORCE', 1.0) readValue(self, section, 'SHIFT_TURN', True) readValue(self, section, 'SAFE_ROLL_ON_LOW_ALTITUDE', True) readValueOnCondition( self, section, 'MOUSE_INTENSITY_SPLINE', curveCondition, default=Curve( [Vector2(0.0, 1.0), Vector2(1.0, 1.0)], MOUSE_INTENSITY_SPLINE_POINT_COUNT)) readValue(self, section, 'CAMERA_ROLL_SPEED', 0.5) readValue(self, section, 'CAMERA_ANGLE', 1.0) readValue(self, section, 'CAMERA_ACCELERATION', 0.0) readValue(self, section, 'METHOD_OF_MIXING', 1)
class Test_Curve(unittest.TestCase): def setUp(self): self.a = Curve() self.a.x = [1,2,3,4,5] self.a.y = [1,2,3,4,5] def test_interpolateX(self): self.a.interpolate(0.5) actual = self.a.x expected = np.array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5]) np.testing.assert_array_almost_equal(actual, expected) def test_interpolateY(self): self.a.interpolate(0.5) actual = self.a.y expected = np.array([1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5]) np.testing.assert_array_almost_equal(actual,expected) def test_calculateYCrossover1(self): self.a.y = [5,4,3,2,1] expected = [1,3,3] actual = self.a.calculateYCrossover(1,5,3,"down") np.testing.assert_array_almost_equal(actual, expected) def test_calculateXCrossover1(self): self.a.y = [5,4,3,2,1] expected = [1,3,3] actual = self.a.calculateXCrossover(1,5,3,"left") np.testing.assert_array_almost_equal(actual, expected) def test_calculateXCrossover2(self): self.a.y = [1,2,3,4,5] expected = [1,3,3] actual = self.a.calculateXCrossover(1,5,3,"left") np.testing.assert_array_almost_equal(actual, expected) def test_getFinalPosition(self): self.a.x = [1,2,3] self.a.y = [4,5,6] expected = [3,6] actual = self.a.getFinalPosition() np.testing.assert_array_almost_equal(actual, expected)
def test_multiply3(self): c = Curve( 2, 9, 96281371306927170306389951196597823460570662626980553583404679319845737621179 ) p = Point( 77711034355206779453930664906458039637702484798239068469560162633184802062493, 30786291639696761965167869698697498910544151780866668167901418464901698964895 ) r = mul(c, p, 627612371987491651398471) assert True == isOnCurve(c, p.x, p.y), "point is not on curve" correctResult = Point( 20406789176534290626028596664035634063243163498815495983166089441243132778820, 87161788161837973833639219974573185263280424901172934399359340868662438231260 ) assert r == correctResult, "incorrect result"
def min_distance(ref_curve, curve, acc=1): """ P.min_distance(numpy.ndarray,numpy.ndarray) -> (int) For each point in a curve, find the smallest distance from it to the reference curve. Returns the total distance between all points on the curve calculated to a certain accuracy acc """ euc_length = lambda a, b: pow(sum(pow(a - b, 2)), 0.5) ref_curve_c = Curve(ref_curve) #print("comparing distance") calc_dist = lambda r: sum( (euc_length(r.find_nearest_point(point), point) for point in curve)) #ref_distance = calc_dist(ref_curve_c) #ref_curve_c.set_points(ref_curve_c.gen_num_points(ref_curve_c.points.shape[0]*2)) distance = calc_dist(ref_curve_c) #print(ref_distance,distance) return pow(distance, 0.5)
def steplocTrsmQuadMem2(c, step=.5, sample=4): """ quadratic fit for transmission; plotting separately for each member (side) curves """ # same as above but with member curves x0 = [0, 0, 0, 0] for i in range(1, 5): ci = c.data[i] if ci is not 0: cit = Curve.trsm(ci) try: index = np.argmax(cit < step) s = slice(index - (sample / 2), index + (sample / 2)) x1 = Curve_TimeFit.x[s] A = np.vstack([x1**2, x1, np.ones(len(x1))]).T a, b, c0 = np.linalg.lstsq(A, cit[s])[0] x0[i - 1] = (-b + np.sqrt(b**2 - 4 * a * (c0 - step))) / 2 / a # x0.append((-b+np.sqrt(b**2-4*a*(c-step)))/2/a) except ValueError: print s, x1, c.label() raise return x0, 0
allcurves = curveCreation(date(2016,11,1), ['data/EJ_20161101_air_calib.csv','data/EJ_20161101_air_calib2.csv', 'data/EJ_20161101_air.csv'], verbose = 1,skips=1) # #allcurves = readCurveFile('measuredates_Oct.txt', verbose = 1, skips = 1) farben = ['blue', 'green', 'darkcyan','red' ,'magenta','blueviolet', 'slategray','magenta'] farben += ['hotpink', 'salmon','springgreen','chocolate', 'crimson'] ## parameters mode = 2 # 0: plot average 1: plot all member curves # 2: all memeber curves with comparison # 3: all memeber curves with Diff keyword = '' #'EJ200SP-1P-N1' #'1X1P N1' # read sample #keyword2 = '1X1P N6' # read sample s = Curve.makeslice(300,600) # x-range (band of wavelength in nm) t = True # transmission or absorption curve; None for absorption newdate = True dateN2 = date(2015,12,19) dateN3 = date(2016,01,14) dateN4 = date(2016,01,11) if newdate: dateN4 = date(2016,03,25) dateCT = date(2015,11,3) # inaccurate allc = curvesKeyword(allcurves, name = keyword) #allc2 = curvesKeyword(allcurves, name = keyword2) #allc += allc2 #allc = curveCreation(date.today(), ['data/EJ_20160328_air_SPN4.csv'], verbose = 1)
def __init__(self): self.name='' self.normal=Vector() self.thickness=0 self.curve=Curve()
class Slab: 'class part definition' def __init__(self): self.name='' self.normal=Vector() self.thickness=0 self.curve=Curve() def getNode(self,node): nameNodes=node.getElementsByTagName('OID') self.name=nameNodes[0].firstChild.nodeValue normNodes=node.getElementsByTagName('Normal') self.normal=Vector().getNode(normNodes[0]) thicknessNodes=node.getElementsByTagName('TotalThickness') if len(thicknessNodes)==0: thicknessNodes=node.getElementsByTagName('Thickness') self.thickness=float(thicknessNodes[0].firstChild.nodeValue) boundaryNodes=node.getElementsByTagName('Boundary') if len(boundaryNodes)==0: boundaryNodes=node.getElementsByTagName('Contour') complexString3dNodes=boundaryNodes[0].getElementsByTagName('ComplexString3d') if len(complexString3dNodes)==0: complexString3dNodes=node.getElementsByTagName('Contour') self.curve=Curve().getNode(complexString3dNodes[0]) return self def center(self): R1=self.curve.center() R2=copy.deepcopy(self.normal) R2.scale(0.5*self.thickness) return R1+R2 def toWall(self): w=Wall() w.name=self.name+'wall' w.curve.lines.clear() n=self.normal deep=self.thickness l=self.curve.lines if n.z!=0: if l[0].dr().mag()>l[1].dr().mag(): line=l[0] dr=l[2].start-l[0].start else: line=l[1] dr=l[3].start-l[1].start line=line.translate(dr,0.5) #line.out() w.curve.lines.append(line) w.height=deep w.thickness=dr.mag() else: max=self.maxV() min=self.minV() diag=max-min if diag.x>diag.y: start=Vector(min.x,(min.y+max.y)/2,min.z) end=Vector(max.x,(min.y+max.y)/2,min.z) thick=diag.y else: start=Vector((min.x+max.x)/2,min.y,min.z) end=Vector((min.x+max.x)/2,max.y,min.z) thick=diag.x line=Line(start,end) w.curve.lines.append(line) w.height=diag.z w.thickness=thick return w def toFloor(self) : f=Floor() f.name=self.name+'floor' n=self.normal deep=self.thickness lines=self.curve.lines f.curve.lines.clear() newlines1=[] newlines1.clear() newlines2=[] newlines2.clear() if n.z!=0: f.curve.lines=copy.deepcopy(lines) f.thickness=deep else: min=self.minV() dz=self.dR().z for l in lines: if l.start.z==min.z and l.end.z==min.z: newlines1.append(l) newlines2.append(l.translate(n,deep)) start1=newlines1[len(newlines1)-1].end end1=newlines2[len(newlines1)-1].end start2=newlines1[0].start end2=newlines2[0].start newlines1.append(Line(start1,end1)) newlines1.extend(newlines2) newlines1.append(Line(start2,end2)) f.curve.lines.extend(newlines1) f.thickness=dz return f def out(self): print ("name=",self.name) print ("normal=") self.normal.out() print( " thickness=",self.thickness) print (" lines=") for l in self.curve.lines: l.out() def draw(self,display,c) : pol=self.curve.polygon() if pol!=None: pol=pol.Wire() n=copy.copy(self.normal) n.scale(self.thickness) n=n.gpV() face=BRepBuilderAPI_MakeFace(pol,True).Face() #my_shell = BRepPrimAPI_MakePrism(my_pol,n1).Shape() prism = BRepPrimAPI_MakePrism(face,n).Shape() if c==0: color='YELLOW' elif c==1: color='BLUE' elif c==2: color='GREEN' elif c==3: color='BLACK' elif c==4: color='RED' elif c==5: color='WHITE' elif c==6: color='CYAN' else: color='ORANGE' display.DisplayColoredShape(prism,color, update=True) def minV(self) : minV=copy.deepcopy(self.curve.minV()) n=copy.deepcopy(self.normal) sign=n.x+n.y+n.z if sign<0: return minV+n.scale(self.thickness) else: return minV def maxV(self) : maxV=copy.deepcopy(self.curve.maxV()) n=copy.deepcopy(self.normal) sign=n.x+n.y+n.z if sign>0: return maxV+n.scale(self.thickness) else: return maxV def dR(self) : return self.maxV()-self.minV() def isWall(self): r=self.dR() n=self.normal i=0 k=0 b=0 if n.x!=0:b+=1 if n.y!=0:b+=1 if n.z!=0:b+=1 for l in self.curve.lines: if isinstance(l,Line): i+=1 else: k+=1 if r.z>2*r.y or r.z>2*r.x: if i==4 and k==0 and b==1:return True else : return False else: return False def isFloor(self): r=self.dR() if (self.isWall()==False): if 2*r.z<r.y or 2*r.z<r.x: return True else: return False else : return False # def isWall(self): # n=self.normal # l=self.curve.lines # if len(l)==4: # l1=l[1].end-l[0].start # l2=l[0].end-l[3].start # if l1.mag()==l2.mag(): # #box # h=self.thickness # r1=l[0].dr() # r2=l[1].dr() # r=r1+r2 # if (n.x==0 and n.y==0 and n.z!=0): # Sxy=(r1*r2).mag() # Sz1=h*r1.mag() # Sz2=h*r2.mag() # if Sxy<min(Sz1,Sz2): return True # else: return False # elif (n.x==0 and n.y!=0 and n.z==0): # Sxz=(r1*r2).mag() # Sxy=h*math.fabs(r.x) # Szy=h*math.fabs(r.z) # if Sxy<min(Sxz,Szy): return True # else: return False # elif (n.x!=0 and n.y==0 and n.z==0): # Szy=(r1*r2).mag() # Sxz=h*math.fabs(r.z) # Sxy=h*math.fabs(r.y) # if Sxy<min(Sxz,Szy): return True # else: return False # else: return False # # # # # # else: return False # else: return False # def isFloor(self): # n=self.normal # l=self.curve.lines # if len(l)==4: # l1=l[1].end-l[0].start # l2=l[0].end-l[3].start # if l1.mag()==l2.mag(): # #box # h=self.thickness # r1=l[0].dr() # r2=l[1].dr() # r=r1+r2 # if (n.x==0 and n.y==0 and n.z!=0): # Sxy=(r1*r2).mag() # Sz1=h*r1.mag() # Sz2=h*r2.mag() # if Sxy>max(Sz1,Sz2): return True # else: return False # elif (n.x==0 and n.y!=0 and n.z==0): # if Vector.dot(r1,Vector(0,0,1))==0 or Vector.dot(r2,Vector(0,0,1))==0: # Sxz=(r1*r2).mag() # Sxy=h*math.fabs(r.x) # Szy=h*math.fabs(r.z) # if Sxy>max(Sxz,Szy): return True # else: return False # else: return False # elif (n.x!=0 and n.y==0 and n.z==0): # if Vector.dot(r1,Vector(0,0,1))==0 or Vector.dot(r2,Vector(0,0,1))==0: # Szy=(r1*r2).mag() # Sxz=h*math.fabs(r.z) # Sxy=h*math.fabs(r.y) # if Sxy>max(Sxz,Szy): return True # else: return False # else: return False # else: return False
class DragVector: def __init__(self, ax, s_omega_x, s_omega_y, t1=10, ax2=None): self.ax = ax self.ax2 = ax2 self.start = None self.arrow = None self.arrow2 = None self.curveField = None self.curve = None self.curveFunc = None self.s_omega_x = s_omega_x self.s_omega_y = s_omega_y self.t_end = t1 self.end_curve, = ax2.plot([], [], 'b-') self.anim_curve, = ax.plot([], [], 'b-') self.anim_data = [[], []] self.anim = [] self.vector = None self.anim_current, = ax.plot([], [], 'b.') def connect(self): self.cidPress = self.ax.figure.canvas.mpl_connect( 'button_press_event', self.on_press) self.cidRelease = self.ax.figure.canvas.mpl_connect( 'button_release_event', self.on_release) self.cidMotion = self.ax.figure.canvas.mpl_connect( 'motion_notify_event', self.on_motion) def on_press(self, event): if self.ax.figure.canvas.manager.toolbar.mode != '': return if event.button != MouseButton.LEFT: return if event.inaxes != self.ax: return if self.arrow is not None: self.arrow.remove() if self.arrow2 is not None: self.arrow2.remove() self.stop_curve() self.start = x, y = event.xdata, event.ydata self.arrow, = self.ax.plot([x], [y], 'k.') self.ax.figure.canvas.draw() if self.ax2 is not None: self.arrow2, = self.ax2.plot([x], [y], 'k.') self.ax2.figure.canvas.draw() def on_motion(self, event): if self.ax.figure.canvas.manager.toolbar.mode != '': return if event.button != MouseButton.LEFT: return if event.inaxes != self.ax: return if self.start is None: return if self.arrow is not None: self.arrow.remove() if self.arrow2 is not None: self.arrow2.remove() x0, y0 = self.start dx = event.xdata - x0 dy = event.ydata - y0 if np.linalg.norm((dx, dy)) < 0.2: self.arrow, = self.ax.plot([x0, event.xdata], [y0, event.ydata], 'k.-') else: self.arrow = self.ax.arrow(x0, y0, dx, dy, head_width=0.05, head_length=0.1, fc='k', ec='k', length_includes_head=True) self.ax.figure.canvas.draw() if self.ax2 is not None: if np.linalg.norm((dx, dy)) < 0.2: self.arrow2, = self.ax2.plot([x0, event.xdata], [y0, event.ydata], 'k-') else: self.arrow2 = self.ax2.arrow(x0, y0, dx, dy, head_width=0.05, head_length=0.1, fc='k', ec='k', length_includes_head=True) self.ax2.figure.canvas.draw() def on_release(self, event): if self.ax.figure.canvas.manager.toolbar.mode != '': return if event.button != MouseButton.LEFT: return if event.inaxes != self.ax: return x0, y0 = self.start dx = event.xdata - x0 dy = event.ydata - y0 self.update_vector(x0, y0, dx, dy) self.update_curveFunc() self.start_curveAnim() self.start = None def disconnect(self): self.ax.figure.canvas.mpl_disconnect(self.cidPress) self.ax.figure.canvas.mpl_disconnect(self.cidRelease) self.ax.figure.canvas.mpl_disconnect(self.cidMotion) def update_curveField(self, _=None): self.stop_curve() self.curveField = Curve(self.s_omega_x.val, self.s_omega_y.val) self.update_curveFunc() if self.curveFunc is not None: self.start_curveAnim() def update_t(self, val): self.t_end = val self.start_curveAnim() def update_curveFunc(self): if self.vector is not None: self.curveFunc, maxx, maxy = self.curveField.start(*self.vector) curMax = self.ax.get_xlim()[1] newMax = max(maxx, maxy) * 1.2 if newMax > curMax: self.ax.set_xlim(-newMax, newMax) self.ax.set_ylim(-newMax, newMax) self.ax2.set_xlim(-newMax, newMax) self.ax2.set_ylim(-newMax, newMax) def update_vector(self, x, y, vx, vy): self.vector = (x, y, vx, vy) def stop_curve(self, until=0): while len(self.anim) > until: self.anim.pop(0).event_source.stop() if len(self.anim) == 0: self.anim_curve.set_animated(False) def start_curveAnim(self): t_cs = np.array(range(int(self.t_end) * 1000 + 1)) t = t_cs / 1000 frame = t_cs[::40] self.anim_data = self.curveFunc(t) def update(current_frame): self.anim_curve.set_data(self.anim_data[0][:current_frame], self.anim_data[1][:current_frame]) x = self.anim_data[0][current_frame] y = self.anim_data[1][current_frame] # minx, maxx = self.ax.get_xlim() # miny, maxy = self.ax.get_ylim() # if x < minx: # self.ax.set_xlim(x - max(abs(x), 1)*0.1, maxx) # elif x > maxx: # self.ax.set_xlim(minx, x + max(abs(x), 1)*0.3) # if y < miny: # self.ax.set_ylim(y - max(abs(y), 1) * 0.1, maxy) # elif y > maxy: # self.ax.set_ylim(miny, y + max(abs(y), 1) * 0.3) self.anim_current.set_data([x], [y]) # if current_frame == frame[-1]: # self.anim_curve.set_animated(False) # self.ax.figure.canvas.draw() return self.anim_curve, self.anim_current self.end_curve.set_data(*self.curveFunc(t)) self.anim_curve.set_animated(True) self.anim.append( FuncAnimation(self.ax.figure, update, frames=frame, interval=40, blit=True, repeat=False)) self.stop_curve(1) def reset(self): self.stop_curve() self.ax.set_xlim(-5, 5) self.ax.set_ylim(-5, 5) self.ax2.set_xlim(-5, 5) self.ax2.set_ylim(-5, 5)
def update_curveField(self, _=None): self.stop_curve() self.curveField = Curve(self.s_omega_x.val, self.s_omega_y.val) self.update_curveFunc() if self.curveFunc is not None: self.start_curveAnim()
class TurretVisualSettings: DEFAULT_RECOIL_CURVE = Curve([ Math.Vector2(0.0, 0.0), Math.Vector2(0.1, -0.005), Math.Vector2(1.0, 0.0) ]) def __init__(self, data): self.trackYawMin = 0.0 self.trackYawMax = 360.0 self.trackPitchMin = -180 self.trackPitchMax = 180 self.yawMin = -180 self.yawMax = 180 self.pitchMin = -180 self.pitchMax = 180 self.animatorDirectionOffset = Math.Vector3(0, 0, 0) self.animatorDirectionDefault = Math.Vector3(0, 0, 0) self.axisDirections = Math.Vector3(2, 1, 0) self.angularVelocity = 1800000 self.angularThreshold = 0.0 self.angularHalflife = 0.0 self.pitchNodeName = 'joint3' self.yawNodeName = 'joint2' self.directionNodeName = 'joint3_BlendBone' self.shootingNodeName = 'joint4' self.idleFrequencyScalerX = 1.0 self.idleAmplitudeScalerX = 0.02 self.idleFrequencyScalerY = 1.0 self.idleAmplitudeScalerY = 0.02 self.shootTime = 0.25 self.shootCooldownTime = 0.75 self.shootingAmplitudeScaler = 0.05 self.enableIdleAnimation = False self.recoilCurve = TurretVisualSettings.DEFAULT_RECOIL_CURVE.copy() self.useGunProfile = True self.readData(data) def readData(self, data): if data is None: return else: readValue(self, data, 'yawMin', -179.99) readValue(self, data, 'yawMax', 180.0) readValue(self, data, 'pitchMin', -179.99) readValue(self, data, 'pitchMax', 180.0) readValue(self, data, 'trackYawMin', 0.0) readValue(self, data, 'trackYawMax', 360.0) readValue(self, data, 'trackPitchMin', -179.99) readValue(self, data, 'trackPitchMax', 180.0) readValue(self, data, 'animatorDirectionOffset', Math.Vector3(0, 0, 0)) readValue(self, data, 'animatorDirectionDefault', Math.Vector3(0, 0, 0)) readValue(self, data, 'animatorDieDirection', Math.Vector3(0, 0, 0)) readValue(self, data, 'axisDirections', Math.Vector3(2, 1, 0)) readValue(self, data, 'angularVelocity', math.pi) readValue(self, data, 'angularThreshold', 0.0) readValue(self, data, 'angularHalflife', 0.0) readValue(self, data, 'pitchNodeName', 'joint3') readValue(self, data, 'yawNodeName', 'joint2') readValue(self, data, 'directionNodeName', 'joint3_BlendBone') readValue(self, data, 'shootingNodeName', 'joint4') readValue(self, data, 'idleFrequencyScalerX', 1.0) readValue(self, data, 'idleAmplitudeScalerX', 0.02) readValue(self, data, 'idleFrequencyScalerY', 1.0) readValue(self, data, 'idleAmplitudeScalerY', 0.02) readValue(self, data, 'shootTime', 0.25) readValue(self, data, 'shootCooldownTime', 0.75) readValue(self, data, 'enableIdleAnimation', False) readValue(self, data, 'recoilCurve', Curve()) readValue(self, data, 'useGunProfile', True) for i in range(0, 3): self.animatorDirectionOffset[i] = self.animatorDirectionOffset[ i] for i in range(0, 3): self.animatorDirectionDefault[ i] = self.animatorDirectionDefault[i] if self.pitchMin > self.pitchMax: if self.pitchMax < 0: self.pitchMax += 360 else: self.pitchMin -= 360 return def save(self, data): if IS_AIRPLANE_EDITOR: writeValue(self, data, 'yawMin', -179.99) writeValue(self, data, 'yawMax', 180.0) writeValue(self, data, 'pitchMin', -179.99) writeValue(self, data, 'pitchMax', 180.0) writeValue(self, data, 'trackYawMin', 0.0) writeValue(self, data, 'trackYawMax', 360.0) writeValue(self, data, 'trackPitchMin', -179.99) writeValue(self, data, 'trackPitchMax', 180.0) writeValue(self, data, 'animatorDirectionOffset', Math.Vector3(0, 0, 0)) writeValue(self, data, 'animatorDirectionDefault', Math.Vector3(0, 0, 0)) writeValue(self, data, 'animatorDieDirection', Math.Vector3(0, 0, 0)) writeValue(self, data, 'axisDirections', Math.Vector3(2, 1, 0)) writeValue(self, data, 'angularVelocity', math.pi) writeValue(self, data, 'angularThreshold', 0.0) writeValue(self, data, 'angularHalflife', 0.0) writeValue(self, data, 'pitchNodeName', 'joint3') writeValue(self, data, 'yawNodeName', 'joint2') writeValue(self, data, 'directionNodeName', 'joint3_BlendBone') writeValue(self, data, 'shootingNodeName', 'joint4') writeValue(self, data, 'idleFrequencyScalerX', 1.0) writeValue(self, data, 'idleAmplitudeScalerX', 0.02) writeValue(self, data, 'idleFrequencyScalerY', 1.0) writeValue(self, data, 'idleAmplitudeScalerY', 0.02) writeValue(self, data, 'shootTime', 0.25) writeValue(self, data, 'shootCooldownTime', 0.75) writeValue(self, data, 'shootingAmplitudeScaler', 0.05) writeValue(self, data, 'enableIdleAnimation', True) writeValue(self, data, 'useGunProfile', True) writeValue(self, data, 'recoilCurve', Curve())
class ECDSA: ALPHANUM = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' BASE = len(ALPHANUM) # 58 def __init__(self, paramters: Dict, password: str): """ Initializes the algorithm with the specified paramters. """ self.D = paramters self.curve = Curve(self.D['A'], self.D['B'], self.D['P']) self.G = (Mod(self.D['Gx'], self.D['P']), Mod(self.D['Gy'], self.D['P'])) self.N = self.D['N'] self.kpriv = self.intsha256(password) self.kpub = self.curve.multiply(self.G, self.kpriv) @staticmethod def intsha256(text: str) -> int: return int(sha256(text.encode('utf-8')).hexdigest(), 16) @staticmethod def random_number(blen: int) -> int: # len is in bits """ Returns cryptographically secure random numbers, unlike the built-in random() of python. """ blen = (blen & 111) + (blen >> 3) # Divide by 8 and round up. rv = 0 for e in urandom(blen): rv += e rv <<= 8 return rv & ((1 << blen) - 1) def b58encode(self, v): # TODO: This isn't used as of now. Will be used soon, change to base64 encoding. """ Encodes v, which is a string of bytes, to base58. """ long_value = 0 for (i, c) in enumerate(v[::-1]): long_value += (256**i) * ord(c) result = '' while long_value >= self.BASE: div, mod = divmod(long_value, self.BASE) result = self.ALPHANUM[mod] + result long_value = div result = self.ALPHANUM[long_value] + result # Bitcoin does a little leading-zero-compression: # leading 0-bytes in the input become leading-1s n_pad = 0 for c in v: if c == '\0': n_pad += 1 else: break return self.ALPHANUM[0] * n_pad + result def sign(self, message: str, k: int = None) -> Signature: if k is None: k: int = self.random_number(255) # TODO: HMAC Generation from hash of message in some RFC algorithm class. if k > self.N: # Random number generation is constructed in such a way that this is impossible. return self.sign(message) # But we can't always assume that RNG won't change. r: Mod = Mod(self.curve.multiply(self.G, k)[0].value, self.N) # Reduction modulo N is important. if r == 0: # A computationally impossible but theoretically possible case. WARNING: Mod to int comparison. return self.sign(message) t1: Mod = self.intsha256(message) + self.kpriv * r s: Mod = Mod(k, self.N).inverse() * t1.value if s == 0: # Again, computationally impossible but theoretically possible. WARNING: Mod to int comparison. return self.sign(message) assert isinstance(r, Mod) and isinstance(s, Mod), "Signature final values have to be Mods." return r.value, s.value def verify(self, message: str, signature: Signature) -> bool: r, s = signature if r > self.N - 1 or r < 1: return False if s > self.N - 1 or s < 1: return False inv: Mod = Mod(s, self.N).inverse() # Conversion to Mod happens here. r is still int. u1: Mod = inv * self.intsha256(message) u2: Mod = inv * r x: Mod = self.curve.add(self.curve.multiply(self.G, u1.value), self.curve.multiply(self.kpub, u2.value))[0] if x.value == r: return True return False