def dec(a, b): if 0 <= abs(a) / abs(b) <= 1: return a / b elif 0 <= abs(b) / abs(a) <= 1: return b / a else: return 0
def calc_radius(self, x1, y1, radius): # scale radius cx1, cy1 = self.canvascoords(x1, y1) cx2, cy2 = self.canvascoords(x1, y1 + radius) # TODO: the accuracy of this calculation of radius might be improved? cradius = math.sqrt(abs(cy2 - cy1)**2 + abs(cx2 - cx1)**2) return (cx1, cy1, cradius)
def solve_matrix(mat, variables): m, n = mat.shape if len(variables) != n - 1: raise ValueError("Expected %d variables" % (n - 1,)) if m >= n: # add fake columns at the front mat = numpy.hstack((numpy.zeros((m, m-n)), mat)) variables[0:0] = ["_fake%d" % (i,) for i in range(m-n)] m, n = mat.shape eliminate(mat) assignments = {} for row in mat[::-1]: nonzero = list(itertools.dropwhile(lambda v: abs(v) <= EPSILON, row)) if not nonzero: continue const = nonzero.pop(-1) if not nonzero: # a row of the form (0 0 ... 0 x) means a contradiction raise NoSolutionsExist() vars = variables[-len(nonzero):] assignee = vars.pop(0) assert abs(nonzero.pop(0) - 1) <= EPSILON assignments[assignee] = const for i, v in enumerate(vars): if v not in assignments: assignments[v] = FreeVar(v) assignments[assignee] -= nonzero[i] * assignments[v] return assignments
def __eq__(self, rhs): #return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z return ( abs(self.x-rhs.x)<11e-3 and abs(self.y-rhs.y)<11e-3 and abs(self.z-rhs.z)<11e-3 )
def get_ruler_distances(self, x1, y1, x2, y2): mode = self.t_drawparams.get('units', 'arcmin') try: image = self.fitsimage.get_image() if mode == 'arcmin': # Calculate RA and DEC for the three points # origination point ra_org, dec_org = image.pixtoradec(x1, y1) # destination point ra_dst, dec_dst = image.pixtoradec(x2, y2) # "heel" point making a right triangle ra_heel, dec_heel = image.pixtoradec(x2, y1) text_h = image.get_starsep_RaDecDeg(ra_org, dec_org, ra_dst, dec_dst) text_x = image.get_starsep_RaDecDeg(ra_org, dec_org, ra_heel, dec_heel) text_y = image.get_starsep_RaDecDeg(ra_heel, dec_heel, ra_dst, dec_dst) else: dx = abs(x2 - x1) dy = abs(y2 - y1) dh = math.sqrt(dx**2 + dy**2) text_x = str(dx) text_y = str(dy) text_h = ("%.3f" % dh) except Exception, e: text_h = 'BAD WCS' text_x = 'BAD WCS' text_y = 'BAD WCS'
def resize(image, dim): #print "Resizing" todo = [True, True] while any(todo): if dim[1] != image.shape[1]: virtical_seams = find_seams(cost(image.sum(axis=-1)/3.)) num_needed = abs(image.shape[1]-dim[1]) #print "Found %d vert seams (%d more)"%(len(virtical_seams), num_needed) allpaths = reduce(lambda a,b : a+b, (seam["path"] for seam in virtical_seams[:num_needed])) if dim[1] < image.shape[1]: image = remove_path(image, allpaths) else: image = stretch_path(image, allpaths) else: todo[1] = False if dim[0] != image.shape[0]: horizontal_seams = find_seams(cost((image.sum(axis=-1)/3.).T)) num_needed = abs(image.shape[0]-dim[0]) #print "Found %d horiz seams (%d more)"%(len(horizontal_seams), num_needed) allpaths = reduce(lambda a,b : a+b, (seam["path"] for seam in horizontal_seams[:num_needed])) if dim[0] < image.shape[0]: image = remove_path(image.swapaxes(0,1), allpaths).swapaxes(0,1) else: image = stretch_path(image.swapaxes(0,1), allpaths).swapaxes(0,1) else: todo[0] = False return image
def getDist(self): mainCharX = self.mainChar.getPos().x mainCharY = self.mainChar.getPos().y pandaX = self.pandaActor2.getPos().x pandaY = self.pandaActor2.getPos().y dist = math.sqrt(abs(mainCharX - pandaX) ** 2 + abs(mainCharY - pandaY) ** 2) return dist
def drawLink(self, src, dst, style): p = self.params lineStyle = self.scene.lineStyles[style] # shorten the line by the radius of the node to prevent # parts of the line from being covered by the node endpoints = computeLinkEndPoints(src, dst, p.nodesize) # both nodes are on the same location, link not visible if endpoints == None: return (sx, sy, dx, dy) = endpoints # draw nothing if the line is not visible after shortened if abs(dx-sx) < 0.01 and abs(dy-sy) < 0.01: return if lineStyle.arrow == 'both': arrow = "ArrowHead ArrowTail" elif lineStyle.arrow == 'head': arrow = "ArrowHead" elif lineStyle.arrow == 'tail': arrow = "ArrowTail" else: arrow = "" print >> self.stream, "LS%d %7.2f %7.2f %7.2f %7.2f %s Line" % ( style, sx, sy, dx, dy, arrow )
def defaultGait(self,leg): # just walk forward for now travelX = 50 travelY = 0 travelRotZ = 0 if abs(travelX)>5 or abs(travelY)>5 or abs(travelRotZ) > 0.05: # are we moving? if(self.order[leg] == self.step): # up, middle position self[leg][0] = 0 # x self[leg][1] = 0 # y self[leg][2] = -20 # z self[leg][3] = 0 # r elif (self.order[leg]+1 == self.step) or (self.order[leg]-7 == self.step): # gaits in step -1 # leg down! self[leg][0] = travelX/2 self[leg][1] = travelY/2 self[leg][2] = 0 self[leg][3] = travelRotZ/2 else: # move body forward self[leg][0] = self[leg][0] - travelX/6 self[leg][1] = self[leg][1] - travelY/6 self[leg][2] = 0 self[leg][3] = self[leg][3] - travelRotZ/6 return self[leg]
def secant(func, x0, x1, eps, max_iter=50): # Evaluate the function at the interval f_l = func(x0) f_x = func(x1) # Set the initial x if abs(f_l) < abs(f_x): x = x0 xl = x1 f_l, f_x = f_x, f_l else: xl = x0 x = x1 # Iterate for i in range(max_iter): dx = (xl - x) * f_x / (f_x - f_l) xl = x f_l = f_x x += dx f_x = func(x) # If we've reached the root, return if abs(dx) < eps or f_x == 0.0: return x # Raise an exception if we reach maximum iterations raise RuntimeError('Maximum iterations reached')
def test_scal(vector_array): v = vector_array for ind in valid_inds(v): if v.len_ind(ind) != v.len_ind_unique(ind): with pytest.raises(Exception): c = v.copy() c[ind].scal(1.) continue ind_complement_ = ind_complement(v, ind) c = v.copy() c[ind].scal(1.) assert len(c) == len(v) assert np.all(almost_equal(c, v)) c = v.copy() c[ind].scal(0.) assert np.all(almost_equal(c[ind], v.zeros(v.len_ind(ind)))) assert np.all(almost_equal(c[ind_complement_], v[ind_complement_])) for x in (1., 1.4, np.random.random(v.len_ind(ind))): c = v.copy() c[ind].scal(x) assert np.all(almost_equal(c[ind_complement_], v[ind_complement_])) assert np.allclose(c[ind].sup_norm(), v[ind].sup_norm() * abs(x)) assert np.allclose(c[ind].l2_norm(), v[ind].l2_norm() * abs(x)) if hasattr(v, 'data'): y = v.data.copy() if NUMPY_INDEX_QUIRK and len(y) == 0: pass else: if isinstance(x, np.ndarray) and not isinstance(ind, Number): x = x[:, np.newaxis] y[ind] *= x assert np.allclose(c.data, y)
def test_testUfuncs1 (self): "Test various functions such as sin, cos." (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d self.assertTrue (eq(numpy.cos(x), cos(xm))) self.assertTrue (eq(numpy.cosh(x), cosh(xm))) self.assertTrue (eq(numpy.sin(x), sin(xm))) self.assertTrue (eq(numpy.sinh(x), sinh(xm))) self.assertTrue (eq(numpy.tan(x), tan(xm))) self.assertTrue (eq(numpy.tanh(x), tanh(xm))) olderr = numpy.seterr(divide='ignore', invalid='ignore') try: self.assertTrue (eq(numpy.sqrt(abs(x)), sqrt(xm))) self.assertTrue (eq(numpy.log(abs(x)), log(xm))) self.assertTrue (eq(numpy.log10(abs(x)), log10(xm))) finally: numpy.seterr(**olderr) self.assertTrue (eq(numpy.exp(x), exp(xm))) self.assertTrue (eq(numpy.arcsin(z), arcsin(zm))) self.assertTrue (eq(numpy.arccos(z), arccos(zm))) self.assertTrue (eq(numpy.arctan(z), arctan(zm))) self.assertTrue (eq(numpy.arctan2(x, y), arctan2(xm, ym))) self.assertTrue (eq(numpy.absolute(x), absolute(xm))) self.assertTrue (eq(numpy.equal(x, y), equal(xm, ym))) self.assertTrue (eq(numpy.not_equal(x, y), not_equal(xm, ym))) self.assertTrue (eq(numpy.less(x, y), less(xm, ym))) self.assertTrue (eq(numpy.greater(x, y), greater(xm, ym))) self.assertTrue (eq(numpy.less_equal(x, y), less_equal(xm, ym))) self.assertTrue (eq(numpy.greater_equal(x, y), greater_equal(xm, ym))) self.assertTrue (eq(numpy.conjugate(x), conjugate(xm))) self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((xm, ym)))) self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((x, y)))) self.assertTrue (eq(numpy.concatenate((x, y)), concatenate((xm, y)))) self.assertTrue (eq(numpy.concatenate((x, y, x)), concatenate((x, ym, x))))
def test(): '''Test the basic workings of `parse_slice`.''' r1 = range(5) r2 = range(2, 10) r3 = range(100, 3, -7) ranges = [r1, r2, r3] slices = [slice(3), slice(5), slice(9), slice(1, 4), slice(4, 7), slice(6, 2), slice(1, 4, 1), slice(1, 5, 3), slice(6, 2, 3), slice(6, 2, -3), slice(8, 2, -1), slice(2, 5, -2), slice(None, 5, -2), slice(6, None, -2), slice(8, 4, None), slice(None, None, -2)] for slice_ in slices: (start, stop, step) = parse_slice(slice_) # Replacing `infinity` with huge number cause Python's lists can't # handle `infinity`: if abs(start) == infinity: start = 10**10 * math_tools.get_sign(start) if abs(stop) == infinity: stop = 10**10 * math_tools.get_sign(stop) if abs(step) == infinity: step = 10**10 * math_tools.get_sign(step) ####################################################################### assert [start, stop, step].count(None) == 0 parsed_slice = slice(start, stop, step) for range_ in ranges: assert range_[slice_] == range_[parsed_slice]
def addExtrusionIntro( self, line ): "Adds the additional linear gcode movement for the extrusion intro." splitG1Line = self.firstLinearGcodeMovement.split() firstMovementLocation = gcodec.getLocationFromSplitLine(None, splitG1Line) firstMovementFeedrate = gcodec.getFeedRateMinute(self.feedRateMinute/self.repository.firstPerimeterFeedrateOverFeedrate.value, splitG1Line) introX = abs( self.repository.absMaxXIntro.value ) introY = abs( self.repository.absMaxYIntro.value ) xAxisFirst=False if abs( firstMovementLocation.x ) < abs( firstMovementLocation.y ): xAxisFirst=True if (xAxisFirst and firstMovementLocation.x > 0) or (not xAxisFirst and firstMovementLocation.x < 0): introX = -introX; if (xAxisFirst and firstMovementLocation.y < 0) or (not xAxisFirst and firstMovementLocation.y > 0): introY = -introY; introLine = self.deriveIntroLine(self.firstLinearGcodeMovement, splitG1Line, introX, introY, firstMovementFeedrate) self.distanceFeedRate.addLine(introLine) self.distanceFeedRate.addLine( line ) if xAxisFirst: introLine = self.deriveIntroLine(self.firstLinearGcodeMovement, splitG1Line, firstMovementLocation.x, introY, self.feedRateMinute) else: introLine = self.deriveIntroLine(self.firstLinearGcodeMovement, splitG1Line, introX, firstMovementLocation.y, self.feedRateMinute) self.distanceFeedRate.addLine(introLine) introLine = self.getRaftlessSpeededLine(self.firstLinearGcodeMovement, splitG1Line) self.distanceFeedRate.addLine(introLine) self.wantsExtrusionIntro = False
def demoNoiseWS(iteration=11): print("reading image...") image = readImage('../samples/monsters.png', grayScale=True) adj4 = AdjacencyNdRegular.getAdjacency2d4(image.embedding.size) image = rescaleGray(image, 0, 1) convolve = False noiseInImage = True sal0 = None for i in range(iteration): print("-> Iteration " + str(i)) print("Constructing gradient graph...") if noiseInImage: im2 = imageMap(image, lambda x: x + rnd.uniform(-0.001, 0.001), marginal=True, inPlace=False) adjacency = WeightedAdjacency.createAdjacency(adj4, lambda i, j: abs(im2[i] - im2[j])) else: adjacency = WeightedAdjacency.createAdjacency(adj4, lambda i, j: abs(image[i] - image[j])) adjacency = imageMap(adjacency, lambda x: x + rnd.uniform(-0.001, 0.001), marginal=True, inPlace=True) print("Constructing area watershed...") # wsh = transformAltitudeBPTtoWatershedHierarchy(constructAltitudeBPT(adjacency)) # addAttributeArea(wsh) # wsha= transformBPTtoAttributeHierarchy(wsh,"area") wsha = constructExactRandomSeedsWatershed(adjacency) sal = computeSaliencyMapFromAttribute(wsha, adj4) print("Averaging and Drawing saliency...") if convolve: lineGraph = WeightedAdjacency.createLineGraph(sal) adjLineGraph = WeightedAdjacency.createReflexiveRelation(lineGraph) meanSal = spatialFilter(sal, adjLineGraph, BasicAccumulator.getMeanAccumulator()) else: meanSal = sal saveImage(normalizeToByte( imageMap(rescaleGray(drawSaliencyMap(image.embedding.size, meanSal), 0, 1), lambda x: x ** 0.33333)), "Results/Random noise gradient " + str(i) + ".png") if sal0 is None: sal0 = meanSal for j in range(len(sal0)): sal0[j] = [sal0[j]] else: for j in range(len(sal0)): sal0[j].append(meanSal[j]) print("Merging results...") for i in range(len(sal0)): sal0[i] = meanV(sal0[i]) saveImage(normalizeToByte( imageMap(rescaleGray(drawSaliencyMap(image.embedding.size, sal0), 0, 1), lambda x: x ** 0.33333)), "Results/Random noise combined gradient.png") print("Ultra metric opening...") bpt = transformAltitudeBPTtoWatershedHierarchy(constructAltitudeBPT(sal0)) addAttributeArea(bpt) nbpt = filterBPTbyCriterion(bpt, lambda i: min(bpt.area[bpt.children[i][0]], bpt.area[bpt.children[i][1]]) < 10) saveImage(drawSaliencyForVisualisation(bpt, image), "Results/Random noise WS bpt.png") saveImage(drawSaliencyForVisualisation(nbpt, image), "Results/Random noise WS filteredbpt.png")
def get_probability(xyz1s,xyz2s,sigma1s,sigma2s,psis,length,slope): onemprob = 1.0 for n in range(len(xyz1s)): xyz1=xyz1s[n] xyz2=xyz2s[n] sigma1=sigma1s[n] sigma2=sigma2s[n] psi = psis[n] psi = psi.get_scale() dist=IMP.core.get_distance(xyz1, xyz2) sigmai = sigma1.get_scale() sigmaj = sigma2.get_scale() voli = 4.0 / 3.0 * pi * sigmai * sigmai * sigmai volj = 4.0 / 3.0 * pi * sigmaj * sigmaj * sigmaj fi = 0 fj = 0 if dist < sigmai + sigmaj : xlvol = 4.0 / 3.0 * pi * (length / 2) * (length / 2) * \ (length / 2) fi = min(voli, xlvol) fj = min(volj, xlvol) else: di = dist - sigmaj - length / 2 dj = dist - sigmai - length / 2 fi = sphere_cap(sigmai, length / 2, abs(di)) fj = sphere_cap(sigmaj, length / 2, abs(dj)) pofr = fi * fj / voli / volj factor = (1.0 - (psi * (1.0 - pofr) + pofr * (1 - psi))*exp(-slope*dist)) onemprob = onemprob * factor prob = 1.0 - onemprob return prob
def G(x, k): result = [] X = np.fft.fft(x, k) for i in range(len(X)): result.append(1/len(X) * (abs(X[i]) * abs(X[i]))) return result
def process(self,Y,X=None,Xt=None,tests=None): self.setYX(Y,X,Xt) bivariter = 0 sumSSE = 0 esiter = list() es.state()["iterations"] = esiter # in the first iteration we calculate W by using ones on U U = ssp.csc_matrix(ones(self.u.shape)) while True: esiterdict = dict() esiterdict["i"] = bivariter logger.debug("Starting iteration: %d"%bivariter) bivariter += 1 W,w_bias,err = self.calculateW(U,tests=tests) esiterdict["w"] = W esiterdict["w_sparcity"] = (abs(W) > 0).sum() esiterdict["w_bias"] = w_bias esiterdict["w_test_err"] = err if "test" in err: logger.debug("W sparcity=%d,test_total_err=%2.2f,test_err=%s"%(esiterdict["w_sparcity"],err['test']["totalsse"],str(err['test']["diffsse"]))) W = ssp.csc_matrix(W) U,u_bias,err = self.calculateU(W,tests=tests) esiterdict["u"] = U esiterdict["u_sparcity"] = (abs(U) > 0).sum() esiterdict["u_bias"] = u_bias esiterdict["u_test_err"] = err if "test" in err: logger.debug("U sparcity=%d,test_total_err=%2.2f,test_err=%s"%(esiterdict["u_sparcity"],err['test']["totalsse"],str(err['test']["diffsse"]))) U = ssp.csc_matrix(U) self.u = U self.w = W self.w_bias = w_bias self.u_bias = u_bias esiter += [esiterdict] if self.allParams['bivar_max_it'] <= bivariter: break return sumSSE
def __new__(cls, latitude=None, longitude=None, altitude=None): single_arg = longitude is None and altitude is None if single_arg and not isinstance(latitude, util.NUMBER_TYPES): arg = latitude if arg is None: pass elif isinstance(arg, Point): return cls.from_point(arg) elif isinstance(arg, basestring): return cls.from_string(arg) else: try: seq = iter(arg) except TypeError: raise TypeError( "Failed to create Point instance from %r." % (arg,) ) else: return cls.from_sequence(seq) latitude = float(latitude or 0) if abs(latitude) > 90: latitude = ((latitude + 90) % 180) - 90 longitude = float(longitude or 0) if abs(longitude) > 180: longitude = ((longitude + 180) % 360) - 180 altitude = float(altitude or 0) self = super(Point, cls).__new__(cls) self.latitude = latitude self.longitude = longitude self.altitude = altitude return self
def genData(): c1 = 0.5 r1 = 0.4 r2 = 0.3 Ndat = 1000 # generate enough data to filter N = 20* Ndat X = array(random_sample(N)) Y = array(random_sample(N)) X1 = X[(X-c1)*(X-c1) + (Y-c1)*(Y-c1) < r1*r1] Y1 = Y[(X-c1)*(X-c1) + (Y-c1)*(Y-c1) < r1*r1] X2 = X1[(X1-c1)*(X1-c1) + (Y1-c1)*(Y1-c1) > r2*r2] Y2 = Y1[(X1-c1)*(X1-c1) + (Y1-c1)*(Y1-c1) > r2*r2] X3 = X2[ abs(X2-Y2)>0.05 ] Y3 = Y2[ abs(X2-Y2)>0.05 ] #X3 = X2[ X2-Y2>0.15 ] #Y3 = Y2[ X2-Y2>0.15] X4=zeros( Ndat, dtype=float32) Y4=zeros( Ndat, dtype=float32) for i in xrange(Ndat): if (X3[i]-Y3[i]) >0.05: X4[i] = X3[i] + 0.08 Y4[i] = Y3[i] + 0.18 else: X4[i] = X3[i] - 0.08 Y4[i] = Y3[i] - 0.18 print "X", size(X3[0:Ndat]), "Y", size(Y3) return vstack((X4[0:Ndat],Y4[0:Ndat])), vstack((array(random_sample(Ndat)),array(random_sample(Ndat))))
def get_balance(self): if not getlist(self.doclist,'entries'): msgprint("Please enter atleast 1 entry in 'GL Entries' table") else: flag, self.doc.total_debit, self.doc.total_credit = 0, 0, 0 diff = flt(self.doc.difference, 2) # If any row without amount, set the diff on that row for d in getlist(self.doclist,'entries'): if not d.credit and not d.debit and diff != 0: if diff>0: d.credit = diff elif diff<0: d.debit = diff flag = 1 # Set the diff in a new row if flag == 0 and diff != 0: jd = addchild(self.doc, 'entries', 'Journal Voucher Detail', self.doclist) if diff>0: jd.credit = abs(diff) elif diff<0: jd.debit = abs(diff) # Set the total debit, total credit and difference for d in getlist(self.doclist,'entries'): self.doc.total_debit += flt(d.debit, 2) self.doc.total_credit += flt(d.credit, 2) self.doc.difference = flt(self.doc.total_debit, 2) - flt(self.doc.total_credit, 2)
def has_split_dividents(mdata, from_date, to_date): ''' Verifies if market data interval has splits, dividends ''' from_diff = abs(mdata['close'][from_date] - mdata['adj_close'][from_date]) to_diff = abs(mdata['close'][to_date] - mdata['adj_close'][to_date]) if approx_equal(from_diff, to_diff, 0.0001): return False return not percent_equal(from_diff, to_diff, mdata['close'][to_date], 0.8)
def mouseInput(): cont = logic.getCurrentController() owner = cont.owner centerX = (render.getWindowWidth()//2)/render.getWindowWidth() centerY = (render.getWindowHeight()//2)/render.getWindowHeight() global oldMouseVec if oldMouseVec == None: oldMouseVec = mathutils.Vector([0.0,0.0]) logic.mouse.position = (centerX,centerY) return mathutils.Vector([0,0]) x = logic.mouse.position[0] - centerX if abs(x) < abs(2/render.getWindowWidth()): x = 0 y = centerY - logic.mouse.position[1] if abs(y) < abs(2/render.getWindowWidth()): y = 0 newMouseVec = mathutils.Vector([x, y]) global mouseSensitivity newMouseVec *= mouseSensitivity # Smooth movement global mouseSmooth oldMouseVec = oldMouseVec*mouseSmooth + newMouseVec*(1.0-mouseSmooth) newMouseVec = oldMouseVec # Center mouse in game window logic.mouse.position = (centerX,centerY) return mathutils.Vector(newMouseVec)
def to_polynomial(self, c): """ Convert clause to :class:`sage.rings.polynomial.pbori.BooleanPolynomial` INPUT: - ``c`` - a clause EXAMPLE:: sage: B.<a,b,c> = BooleanPolynomialRing() sage: from sage.sat.converters.polybori import CNFEncoder sage: from sage.sat.solvers.dimacs import DIMACS sage: fn = tmp_filename() sage: solver = DIMACS(filename=fn) sage: e = CNFEncoder(solver, B, max_vars_sparse=2) sage: _ = e([a*b + a + 1, a*b+ a + c]) sage: e.to_polynomial( (1,-2,3) ) a*b*c + a*b + b*c + b """ def product(l): # order of these multiplications for performance res = l[0] for p in l[1:]: res = res*p return res phi = self.phi product = self.ring(1) for v in c: if phi[abs(v)] is None: raise ValueError("Clause containst an XOR glueing variable.") product *= phi[abs(v)] + int(v>0) return product
def fit_CSU_edges(profile): fitter = fitting.LevMarLSQFitter() amp1_est = profile[profile == min(profile)][0] mean1_est = np.argmin(profile) amp2_est = profile[profile == max(profile)][0] mean2_est = np.argmax(profile) g_init1 = models.Gaussian1D(amplitude=amp1_est, mean=mean1_est, stddev=2.) g_init1.amplitude.max = 0 g_init1.amplitude.min = amp1_est*0.9 g_init1.stddev.max = 3 g_init2 = models.Gaussian1D(amplitude=amp2_est, mean=mean2_est, stddev=2.) g_init2.amplitude.min = 0 g_init2.amplitude.min = amp2_est*0.9 g_init2.stddev.max = 3 model = g_init1 + g_init2 fit = fitter(model, range(0,profile.shape[0]), profile) # Check Validity of Fit if abs(fit.stddev_0.value) <= 3 and abs(fit.stddev_1.value) <= 3\ and fit.amplitude_0.value < -1 and fit.amplitude_1.value > 1\ and fit.mean_0.value > fit.mean_1.value: x = [fit.mean_0.value, fit.mean_1.value] x1 = int(np.floor(min(x)-1)) x2 = int(np.ceil(max(x)+1)) else: x1 = None x2 = None return x1, x2
def test_translational_alignment(self): """ Test the translational alignment in 2D routine """ random.seed() name=self.get_input_file_name("1z5s-projection-2.spi") srw = IMP.em2d.SpiderImageReaderWriter() image=IMP.em2d.Image() image.read(name,srw) translated=IMP.em2d.Image() # random translation trans=IMP.algebra.Vector2D(random.random()*10,random.random()*10) transformation = IMP.algebra.Transformation2D(trans) IMP.em2d.get_transformed(image.get_data(),translated.get_data(), transformation) fn_translated = self.get_input_file_name("translated.spi") # translated.write(fn_translated,srw) result=IMP.em2d.get_translational_alignment( image.get_data(),translated.get_data(),True) fn_aligned = self.get_input_file_name("trans_aligned.spi") # translated.write(fn_aligned,srw) # -1 to get the translation applied to reference. # Result contains the translation required for align the second matrix determined_trans= (-1)*result[0].get_translation() # Tolerate 1 pixel error self.assertAlmostEqual(abs(determined_trans[0]-trans[0]),0, delta=1, msg="1st coordinate is incorrect: Applied %f Determined %f" \ % (trans[0], determined_trans[0])) self.assertAlmostEqual(abs(determined_trans[1]-trans[1]),0, delta=1, msg="2nd coordinate is incorrect: Applied %f Determined %f" \ % (trans[1], determined_trans[1]))
def karatsuba_multiply(x, y): if x == 0 or y == 0: return 0 sign = 1 if (x < 0 and y > 0) or (x > 0 and y < 0): sign = -1 x = abs(x) y = abs(y) max_digit = max(x.bit_length(), y.bit_length()) if max_digit == 1: return 1 half_digit = max_digit // 2 filter_mask = (1 << half_digit) - 1 x_upper_half = x >> half_digit x_lower_half = x & filter_mask y_upper_half = y >> half_digit y_lower_half = y & filter_mask z_0 = karatsuba_multiply(x_lower_half, y_lower_half) z_2 = karatsuba_multiply(x_upper_half, y_upper_half) z_1 = karatsuba_multiply((x_lower_half + x_upper_half), (y_lower_half + y_upper_half)) - z_0 - z_2 abs_res = ((z_2 << half_digit << half_digit) + (z_1 << half_digit) + z_0) if sign == -1: return ~abs_res + 1 else: return abs_res
def getPartInfo( part ): points = part['points'] n = len(points) area = cx = cy = 0 xmin = ymin = 360 xmax = ymax = -360 pt = points[n-1]; xx = pt[0]; yy = pt[1] for pt in points: x = pt[0]; y = pt[1] # bounds xmin = min( x, xmin ); ymin = min( y, ymin ) xmax = max( x, xmax ); ymax = max( y, ymax ) # area and centroid a = xx * y - x * yy area += a cx += ( x + xx ) * a cy += ( y + yy ) * a # next xx = x; yy = y area /= 2 if area: centroid = [ cx / area / 6, cy / area / 6 ] else: centroid = None part.update({ 'area': abs(area), 'bounds': [ [ xmin, ymin ], [ xmax, ymax ] ], 'center': [ ( xmin + xmax ) / 2, ( ymin + ymax ) / 2 ], 'centroid': centroid, 'extent': [ abs( xmax - xmin ), abs( ymax - ymin ) ] })
def test_rotational_alignment(self): """ Test the rotational alignment in 2D routine (new) """ random.seed() name=self.get_input_file_name("1z5s-projection-2.spi") srw = IMP.em2d.SpiderImageReaderWriter() image=IMP.em2d.Image() image.read(name,srw) rotated=IMP.em2d.Image() # random rotation angle=random.random()*2*pi rot=IMP.algebra.Rotation2D(angle) transformation = IMP.algebra.Transformation2D(rot) IMP.em2d.get_transformed(image.get_data(),rotated.get_data(), transformation) fn_rotated = self.get_input_file_name("rotated.spi") # rotated.write(fn_rotated,srw) result=IMP.em2d.get_rotational_alignment( image.get_data(),rotated.get_data(),True) fn_aligned = self.get_input_file_name("rot_aligned.spi") # rotated.write(fn_aligned,srw) determined_angle=result[0].get_rotation().get_angle() # approximately 6 degrees tolerance, 0.1 rad. x = angle+determined_angle modulo = (abs(x % (2*pi)) < 0.1) or (abs(x % (2*pi)-2*pi) < 0.1) self.assertEqual(modulo,True,msg="Angles applied %f and " "determined %f are different, difference %f" % (angle ,determined_angle,x))
def _str(self, i, x): """Handles string formatting of cell data i - index of the cell datatype in self._dtype x - cell data to format """ try: f = float(x) except: return str(x) n = self._precision dtype = self._dtype[i] if dtype == 'i': return str(int(round(f))) elif dtype == 'f': return '%.*f' % (n, f) elif dtype == 'e': return '%.*e' % (n, f) elif dtype == 't': return str(x) else: if f - round(f) == 0: if abs(f) > 1e8: return '%.*e' % (n, f) else: return str(int(round(f))) else: if abs(f) > 1e8: return '%.*e' % (n, f) else: return '%.*f' % (n, f)
def make(self, tags_additional=[], isSocket=True): param = self.params lib_name = "Connector_PinSocket_{0:03.2f}mm".format(param.pin_pitch) footprint_name = self.makeModelName("") description = "Through hole angled socket strip, {0}x{1:02}, {2:03.2f}mm pitch, {3}mm socket length"\ .format(param.num_pin_rows, param.num_pins, param.pin_pitch, param.body_width) tags = "Through hole angled socket strip THT {0}x{1:02} {2:03.2f}mm".format( param.num_pin_rows, param.num_pins, param.pin_pitch) tags += txt_tag[param.num_pin_rows] description += txt_descr[param.num_pin_rows] pad = [param.pad_length, param.pad_width] rowdist = param.pin_pitch if len(tags_additional) > 0: for t in tags_additional: footprint_name = footprint_name + "_" + t description = description + ", " + t tags = tags + " " + t if len(param.datasheet) > 0: description += " (" + param.datasheet + ")" description += ", script generated" print("###################") print(footprint_name, "in", lib_name) # init kicad footprint kicad_mod = Footprint(footprint_name) kicad_mod.setDescription(description) kicad_mod.setTags(tags) # anchor for SMD-symbols is in the center, for THT-sybols at pin1 kicad_modg = Translation(0, 0) kicad_mod.append(kicad_modg) # create layer canvases silk = Layer(kicad_modg, 'F.SilkS') fab = Layer(kicad_modg, 'F.Fab') crt = Layer(kicad_modg, 'F.CrtYd', offset=0.5) # offset 0.5 for connectors pads = PadLayer(kicad_modg, pad, Pad.TYPE_THT, Pad.SHAPE_OVAL, shape_first=Pad.SHAPE_RECT, drill=param.pin_drill) keepout = Keepout(silk) if Keepout.DEBUG: kicad_mod.setSolderMaskMargin(silk.getSoldermaskMargin()) rmh = param.pin_pitch / 2.0 r_dist = rowdist * (param.num_pin_rows - 1) h_fab = (param.num_pins - 1) * param.pin_pitch + param.pin_pitch w_fab = -param.body_width l_fab = -(r_dist + param.body_offset) t_fab = -rmh h_slk = h_fab + silk.offset * 2.0 w_slk = w_fab - silk.offset * 2.0 l_slk = l_fab + silk.offset t_slk = t_fab - silk.offset w_crt = -(rmh + r_dist + param.body_offset + param.body_width + crt.offset * 2.0) h_crt = h_fab + crt.offset * 2.0 l_crt = rmh + crt.offset t_crt = -rmh - crt.offset # create pads y = 0.0 for r in range(1, param.num_pins + 1): x = 0.0 for c in range(1, param.num_pin_rows + 1): pads.add(x, y) x -= rowdist y += param.pin_pitch # add pads to silk keepout keepout.addPads() keepout.debug_draw() # add text to silk silk.goto(l_crt + w_crt / 2.0, t_crt - silk.txt_offset)\ .text('reference', 'REF**') # create FAB-layer bevel = min(Layer.getBevel(h_fab, abs(w_fab)), -t_fab - param.pin_width / 2.0) fab.goto(l_fab + w_fab / 2.0, (h_fab - param.pin_pitch) / 2.0)\ .text('user', '%R', rotation=(90 if h_fab >= -w_fab else 0))\ .rect(-w_fab, h_fab, bevel=(0.0, bevel, 0.0, 0.0))\ .goto(l_crt + w_crt / 2.0, h_crt + t_crt + fab.txt_offset)\ .text('value', footprint_name) # add pin markers fab.goto(l_fab / 2.0, 0.0) for r in range(1, param.num_pins + 1): fab.rect(l_fab, param.pin_width, draw=(True, False, True, True))\ .down(param.pin_pitch, False) # continue silk layer, set origin and fill pin1 rectangle silk.setOrigin(l_fab + w_slk + silk.offset, t_slk)\ .jump(0.0, -t_slk - rmh)\ .fillrect(-w_slk, param.pin_pitch + silk.offset + (silk.offset if param.num_pins == 1 else 0.0))\ pw = param.pin_width + silk.offset * 2.0 # add pin markers silk.goto(l_slk / 2.0, 0.0) for r in range(1, param.num_pins + 1): silk.rect(l_slk, pw, draw=(True, False, True, False))\ .down(param.pin_pitch, False) #add separation lines silk.goHome()\ .jump(0.0, silk.line_width / 2.0) for r in range(1, param.num_pins + 1): silk.right(-w_slk, r != 1)\ .jump(w_slk, param.pin_pitch) # add outline silk.goHome()\ .rect(-w_slk, h_slk, origin='topLeft') pin1 = keepout.getPadBB(1) # add pin1 marker silk.goto(pin1.x + pin1.width / 2.0, pin1.y)\ .up(max(-t_slk, pin1.height / 2.0))\ .left(silk.x - pin1.x) # create courtyard crt.setOrigin(l_crt + w_crt / 2.0, t_crt + h_crt / 2.0)\ .rect(w_crt, h_crt) # add model kicad_modg.append( Model(filename="${KISYS3DMOD}/" + lib_name + ".3dshapes/" + footprint_name + ".wrl")) # write file file_handler = KicadFileHandler(kicad_mod) file_handler.writeFile( root_dir.saveTo(lib_name) + footprint_name + '.kicad_mod')
def getDistance(p1,p2,q1,q2): if p1==q1: return abs(p2-q2)-1 if p2==q2: return abs(p1-q1)-1 return gcd(abs(p1-q1),abs(p2-q2))-1
nums=int(input()) def gcd(a,b): if b == 0: return a else : return gcd(b,a%b) def getDistance(p1,p2,q1,q2): if p1==q1: return abs(p2-q2)-1 if p2==q2: return abs(p1-q1)-1 return gcd(abs(p1-q1),abs(p2-q2))-1 for i in range(nums): p1,p2=input().split(' ') q1,q2=input().split(' ') r1,r2=input().split(' ') p1,p2,q1,q2,r1,r2=int(p1),int(p2),int(q1),int(q2),int(r1),int(r2) boundary=getDistance(p1,p2,q1,q2)+getDistance(p1,p2,r1,r2)+getDistance(q1,q2,r1,r2)+3 area=abs( p1*(q2-r2) + q1*(r2-p2) + r1*(p2-q2) ) res=(area-boundary+2)/2 print(res)
s = 0 for xm in range(0, N): #find the value of the function at every y and multiply it by the weights to get the sum s += wpx[xm] * f(xp[xm]) return s N = [2, 4, 8, 12, 16] G = [] S = [] exact = 2.1620386 for n in N: x, w = gaussxw(n) t1, t2, s = swhole(n, 1, 8, f) G.append(G1d(1, 8, x, w, n, f)) S.append(s) G = np.array(G) S = np.array(S) ErrorG = abs(G - exact) ErrorS = abs(S - exact) figure1 = plt.figure() ax = figure1.add_subplot() ax.loglog(N, ErrorG, label="Error Gaussian", color='green') ax.loglog(N, ErrorS, label="Error Midpoint", color='blue') ax.set_xlabel("x") ax.set_ylabel("absolute error") ax.legend(loc='best') figure1.suptitle("Error of each method") plt.show()
def __init__(self): rospy.init_node('calibrate_angular_node', anonymous=False) # Set rospy to execute a shutdown function when terminating the script rospy.on_shutdown(self.shutdown) try: self.rate = rospy.get_param("~check_odom_rate", 12) self.circle_cnt = rospy.get_param("~test_circle", '2') self.test_angle = eval('self.circle_cnt*2*pi') self.speed = rospy.get_param("~angular_speed", 0.3) #radians speed self.tolerance = rospy.get_param("~tolerance_angle", 0.02) self.odom_angular_scale = rospy.get_param("~angular_scale", 1.000) # Publisher to control the robot's speed cmd_topic = rospy.get_param("~cmd_topic", '/cmd_vel') self.cmd_vel = rospy.Publisher(cmd_topic, Twist, queue_size=5) # The base frame is usually base_link or base_footprint self.base_frame = rospy.get_param('~base_frame', '/base_footprint') # The odom frame is usually just /odom self.odom_frame = rospy.get_param('~odom_frame', '/odom') except: rospy.logerr("ERROR: Get config param error from yaml file...") # How fast will we check the odometry values? r = rospy.Rate(self.rate) # Initialize the tf listener self.tf_listener = tf.TransformListener() # Give tf some time to fill its buffer rospy.sleep(2) # Make sure we see the odom and base frames self.tf_listener.waitForTransform(self.odom_frame, self.base_frame, rospy.Time(), rospy.Duration(30.0)) start_time = rospy.get_time() #get start test time while not rospy.is_shutdown(): # Get the current rotation angle from tf self.odom_angle = 0 last_angle = 0 turn_angle = 0.0 rest_angle = self.test_angle - turn_angle # config move cmd move_cmd = Twist() move_cmd.angular.z = self.speed while rest_angle > self.tolerance: if rospy.is_shutdown(): return rospy.loginfo("***************************************") # Rotate the robot to reduce the rest_angle self.cmd_vel.publish(move_cmd) r.sleep() # Get the current rotation angle from tf self.odom_angle = self.get_odom_angle() rospy.loginfo("current rotation angle: " + str(self.odom_angle)) # Compute how far we have gone since the last measurement delta_angle = self.odom_angular_scale * normalize_angle(self.odom_angle - last_angle) # Add to our total angle so far turn_angle += delta_angle rospy.loginfo("turn_angle: " + str(turn_angle)) # Compute the new rest angle rest_angle = self.test_angle - abs(turn_angle) rospy.loginfo("rest_angle: " + str(rest_angle)) # Store the current angle for the next comparison last_angle = self.odom_angle # test completed end_time = rospy.get_time() #get test end time rospy.logwarn("----------------------------") rospy.logwarn("---Angular Test Completed---") rospy.logwarn("----------------------------") rospy.logwarn("Test angle:" + str(self.test_angle)) rospy.logwarn("Test Time:" + str(end_time-start_time)) rospy.logwarn("Test Angular speed:" + str(self.test_angle/(end_time-start_time))) rospy.logwarn("Input Angular speed:" + str(self.speed)) rospy.logwarn("-----------END--------------") rospy.signal_shutdown('End Test')
def delta(p): if len(p) == 1: return oo return min(abs(i[0] - i[1]) for i in subsets(p, 2))
def test_harmonic_rational(): ne = S(6) no = S(5) pe = S(8) po = S(9) qe = S(10) qo = S(13) Heee = harmonic(ne + pe/qe) Aeee = (-log(10) + 2*(-1/S(4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + 5/S(8))) + 2*(-sqrt(5)/4 - 1/S(4))*log(sqrt(sqrt(5)/8 + 5/S(8))) + pi*(1/S(4) + sqrt(5)/4)/(2*sqrt(-sqrt(5)/8 + 5/S(8))) + 13944145/S(4720968)) Heeo = harmonic(ne + pe/qo) Aeeo = (-log(26) + 2*log(sin(3*pi/13))*cos(4*pi/13) + 2*log(sin(2*pi/13))*cos(32*pi/13) + 2*log(sin(5*pi/13))*cos(80*pi/13) - 2*log(sin(6*pi/13))*cos(5*pi/13) - 2*log(sin(4*pi/13))*cos(pi/13) + pi*cot(5*pi/13)/2 - 2*log(sin(pi/13))*cos(3*pi/13) + 2422020029/S(702257080)) Heoe = harmonic(ne + po/qe) Aeoe = (-log(20) + 2*(1/S(4) + sqrt(5)/4)*log(-1/S(4) + sqrt(5)/4) + 2*(-1/S(4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + 5/S(8))) + 2*(-sqrt(5)/4 - 1/S(4))*log(sqrt(sqrt(5)/8 + 5/S(8))) + 2*(-sqrt(5)/4 + 1/S(4))*log(1/S(4) + sqrt(5)/4) + 11818877030/S(4286604231) + pi*(sqrt(5)/8 + 5/S(8))/sqrt(-sqrt(5)/8 + 5/S(8))) Heoo = harmonic(ne + po/qo) Aeoo = (-log(26) + 2*log(sin(3*pi/13))*cos(54*pi/13) + 2*log(sin(4*pi/13))*cos(6*pi/13) + 2*log(sin(6*pi/13))*cos(108*pi/13) - 2*log(sin(5*pi/13))*cos(pi/13) - 2*log(sin(pi/13))*cos(5*pi/13) + pi*cot(4*pi/13)/2 - 2*log(sin(2*pi/13))*cos(3*pi/13) + 11669332571/S(3628714320)) Hoee = harmonic(no + pe/qe) Aoee = (-log(10) + 2*(-1/S(4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + 5/S(8))) + 2*(-sqrt(5)/4 - 1/S(4))*log(sqrt(sqrt(5)/8 + 5/S(8))) + pi*(1/S(4) + sqrt(5)/4)/(2*sqrt(-sqrt(5)/8 + 5/S(8))) + 779405/S(277704)) Hoeo = harmonic(no + pe/qo) Aoeo = (-log(26) + 2*log(sin(3*pi/13))*cos(4*pi/13) + 2*log(sin(2*pi/13))*cos(32*pi/13) + 2*log(sin(5*pi/13))*cos(80*pi/13) - 2*log(sin(6*pi/13))*cos(5*pi/13) - 2*log(sin(4*pi/13))*cos(pi/13) + pi*cot(5*pi/13)/2 - 2*log(sin(pi/13))*cos(3*pi/13) + 53857323/S(16331560)) Hooe = harmonic(no + po/qe) Aooe = (-log(20) + 2*(1/S(4) + sqrt(5)/4)*log(-1/S(4) + sqrt(5)/4) + 2*(-1/S(4) + sqrt(5)/4)*log(sqrt(-sqrt(5)/8 + 5/S(8))) + 2*(-sqrt(5)/4 - 1/S(4))*log(sqrt(sqrt(5)/8 + 5/S(8))) + 2*(-sqrt(5)/4 + 1/S(4))*log(1/S(4) + sqrt(5)/4) + 486853480/S(186374097) + pi*(sqrt(5)/8 + 5/S(8))/sqrt(-sqrt(5)/8 + 5/S(8))) Hooo = harmonic(no + po/qo) Aooo = (-log(26) + 2*log(sin(3*pi/13))*cos(54*pi/13) + 2*log(sin(4*pi/13))*cos(6*pi/13) + 2*log(sin(6*pi/13))*cos(108*pi/13) - 2*log(sin(5*pi/13))*cos(pi/13) - 2*log(sin(pi/13))*cos(5*pi/13) + pi*cot(4*pi/13)/2 - 2*log(sin(2*pi/13))*cos(3*pi/13) + 383693479/S(125128080)) H = [Heee, Heeo, Heoe, Heoo, Hoee, Hoeo, Hooe, Hooo] A = [Aeee, Aeeo, Aeoe, Aeoo, Aoee, Aoeo, Aooe, Aooo] for h, a in zip(H, A): e = expand_func(h).doit() assert cancel(e/a) == 1 assert abs(h.n() - a.n()) < 1e-12
a = float(input('Digite o valor da reta A: ')) b = float(input('Digite o valor da reta B: ')) c = float(input('Digite o valor da reta C: ')) ab_menos = abs(a - b) ab_mais = a + b ac_menos = abs(a - c) ac_mais = a + c bc_menos = abs(b - c) bc_mais = b + c if ((ab_menos < c) and (c < ab_mais)) and ((ac_menos < b) and (c < ac_mais)) and ((bc_menos < a) and (a < bc_mais)): if a == b == c: print('Triângulo Equilátero.') elif a == b or a == c or b == c: print('Triângulo Isósceles.') else: print('Triângulo Escaleno.') else: print('Estas retas NÃO podem formar um triângulo')
def avoirEnsembleSansValeurIninteressante(self, ensemble): ecart_type, moyenne = self.avoirEcartTypeEtMoyenne(ensemble) return [x for x in ensemble if abs(x - moyenne) < 2 * ecart_type]
def feq(a, b): return abs(a - b) < 1E-10
def cost1(nums, target): return sum(abs(n - target) for n in nums)
def degree(self): return abs(self) - 1
def isclose(a, b=1., rel_tol=1e-09, abs_tol=0.0): return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def cost2(nums, target): sum = 0 for n in nums: m = abs(n - target) sum += (m + m**2) // 2 return sum
def dual(bot, update, log_update=False): """ Update the ranking of the chat where the update originated from. The format of the message is expected to follow format of a 2-vs-2 game. Args: bot (Telegram Bot): Bot that received the message. update (Telegram Update): Full description of the Telegram message. Returns: Duals: Duals-object describing the match """ # Assume format: # subm_1, subm_2, rival_1, rival_2, subm_sc, rival_sc if log_update: update_log(update) if PRINT_UPDATES: print_upd(update) chat_id = update.message.chat_id if not __check_ranking_exists(chat_id): try: __lazy_load_ranking(chat_id) except FileNotFoundError: if update.message.chat.type == "private": msg = bot.send_message(chat_id=update.message.chat_id, text=("Unfortunately, private-chats cannot have rankings.\n\n" + "To get started with a ranking:\n" + "* Create a new channel\n" + "* Invite @table_soccer_ranker_bot to the channel\n" + "* Send '/start' message to the channel")) else: msg = bot.send_message(chat_id=update.message.chat_id, text=("No ranking has been started yet.\n" + "To get started with one, send '/start' to this chat.\n")) if log_update: bot_log(msg) return None try: sub, sub_tm, rival, rival_tm, sub_score, riv_score = parse_dual_update(update) except ValueError as e: msg = bot.send_message(chat_id=update.message.chat_id, text="Uh oh, malformatted game result ({}). Should be form: /duals @teammate rival_1 rival_2 your_score rival_score".format(e.args[0])) if log_update: bot_log(msg) return None pregame_ranks = {} # Convert to dict for i, (user, _) in enumerate(RANKINGS[chat_id].get_leaderboard()): if user in [sub[0], sub_tm[0], rival[0], rival_tm[0]]: pregame_ranks[user] = i try: ts = int(update.message.date.timestamp()) duals = RANKINGS[chat_id].add_dual_match(sub, sub_tm, rival, rival_tm, sub_score, riv_score, ts) except (TypeError, UnacceptedMatch, DuplicateMatch, RateLimitExceeded) as err: # TODO COmmunicate rate-limit logging.log(logging.ERROR, msg="Internal error: {}".format(err)) msg = bot.send_message(chat_id=update.message.chat_id, text="Uh oh, Internal error when tried to process the result.") if log_update: bot_log(msg) return None postgame_ranks = {} # Convert to dict for i, (user, _) in enumerate(RANKINGS[chat_id].get_leaderboard()): if user in [sub[0], sub_tm[0], rival[0], rival_tm[0]]: postgame_ranks[user] = i message = ["Succesfully added the game to the records."] additional = False for uid, uname in [sub, sub_tm, rival, rival_tm]: rise = postgame_ranks[uid] - pregame_ranks[uid] if uname is None: try: chat_member = bot.get_chat_member(chat_id, uid) user = chat_member.user.full_name except (TimeoutError, AttributeError): uname = "Unknown" if rise < 0: # Do not add extra new-lines if nothing to report. if not additional: message.append("\n\n") additional = True if rise == -1: message.append("Player {}, rose {} rank\n".format(uname, abs(rise))) else: message.append("Player {}, rose {} ranks\n".format(uname, abs(rise))) elif rise > 0: if not additional: message.append("\n\n") additional = True # Do not report lost ranks to the users. Humans' tend to weight losing higher than winning, so avoid reporting # a loss. # if rise == 1: # message.append("Player {}, lost {} rank\n".format(uname, abs(rise))) # else: # message.append("Player {}, lost {} ranks\n".format(uname, abs(rise))) msg = bot.send_message(chat_id=update.message.chat_id, text="".join(message)) if log_update: bot_log(msg) return duals
def approx_equal(in_1,in_2,max_delta): if abs(in_1 - in_2) <= max_delta : return True return False
def main(): num_images = 0 num_no_ground_truth = 0 num_no_detected_face = 0 GT_bboxes = [] GT_bboxes_principle = [] Pre_bboxes = [] images_folder = str.split(evaluate_data, '.')[0] if not os.path.exists(os.path.join(cbdar_path, images_folder)): os.mkdir(os.path.join(cbdar_path, images_folder)) with open(os.path.join(cbdar_path, evaluate_data), 'r') as f: lines = f.readlines() for line in lines: num_images += 1 line = str.split(line, ' ') img_file = line[0] if img_file == '14_deu_id_new/images/PS/PS14_28.tif': print('%s' % img_file) else: print('%s' % img_file) continue ## read image img = cv2.imread(os.path.join(image_path, img_file)) ## read the ground truth of bounding box gt_num = int(line[1]) if not gt_num: print( '===============>>>> No groud truth of bounding box in %s!' % img_file) num_no_ground_truth += 1 continue gt_bboxes = np.zeros((gt_num, 4)) ## read groud truth of bounding box for i in range(gt_num): i_start = 2 + i * 4 i_end = 2 + (i + 1) * 4 gt_bboxes[i] = list(map(int, line[i_start:i_end])) #shift_pixel = 35 ## draw the ground truth cv2.rectangle(img, (int(gt_bboxes[i][0]), int(gt_bboxes[i][1])), (abs(int((gt_bboxes[i][2] - gt_bboxes[i][0]))), abs(int((gt_bboxes[i][3] - gt_bboxes[i][1])))), (255, 0, 0), 3) gt_idx_end = i_end ## read the predicted bounding box and the confidences pre_num = (len(line) - gt_idx_end) // 5 if pre_num == 0: print('%s No face has been detected!' % img_file) num_no_detected_face += 1 else: pre_bboxes = np.zeros((pre_num, 5)) for i in range(pre_num): i_start = gt_idx_end + i * 5 i_end = gt_idx_end + (i + 1) * 5 pre_bboxes[i, 0:4] = list(map(int, line[i_start:i_end - 1])) ## draw the predicted boxes for PCN & MTCNN & Cascade-CNN shfit_pixel = 5 cv2.rectangle(img, (int(pre_bboxes[i][0] + shfit_pixel), int(pre_bboxes[i][1] + shfit_pixel)), (abs(int(pre_bboxes[i][2]) + shfit_pixel), abs(int(pre_bboxes[i][3]) + shfit_pixel)), (0, 255, 0), 3, 8) img_new_file = img_file.replace('/', '_') cv2.imwrite(os.path.join(cbdar_path, images_folder, img_new_file), img) print('Total %d images, %d No ground truth, %d No detected face!' % (num_images, num_no_ground_truth, num_no_detected_face)) return GT_bboxes, GT_bboxes_principle, Pre_bboxes
x, y = y, x parent[y] = x if rank[x] == rank[y]: rank[x] += 1 return True N, M = map(int, input().split()) points = [0] + [list(map(int, input().split())) for _ in range(N)] parent = [i for i in range(N + 1)] rank = [1] * (N + 1) for _ in range(M): union(*map(int, input().split())) heap = [] for i in range(1, N): for j in range(i + 1, N + 1): dis = (abs(points[i][0] - points[j][0]) ** 2 + abs(points[i][1] - points[j][1]) ** 2) ** 0.5 heapq.heappush(heap, (dis, i, j)) answer = 0 while heap: cost, start, end = heapq.heappop(heap) if union(start, end): answer += cost print(f'{answer:.2f}')
def update(self, time): update = super(AIFighter, self).update(time) self.ai_timer.update(time) # the super has already made a change to the avatar if update == True: return True # we are attacking right now, so just let it be... if self.ai_timer.finished: # if we are attacking, then let it finish if self.in_attack: return # make it dumb by stopping once in a while if self.rand_diff(5, 40): self.ai_timer.alarm = random.randint(250, 1000) return # get a list of stuff we could do here to punish options = self.plan_attack() # WE DON'T WANT THE BANNED ONES for ani in self.banned_animations: try: options.remove(ani) except ValueError: pass if options == []: # play random animation, just for variety if self.rand_diff(5, 15): ani = self.block_frames[random.randint(0, len(self.block_frames)-1)].parent self.avatar.play(ani) self.ai_timer.alarm = random.randint(250, 1000) return # if we are idling, then we can walk foe = self.match.closest_foe(self) if self.avatar.current_animation == self.idle_animation: if abs(foe.position[0] - self.position[0]) > self.personal_space: self.avatar.play(self.forward_animation) self.ai_timer.alarm = random.randint(60, 120) return True else: # throw an attack we can land if random.random() * 100 > 101 - self.difficulty: if self.avatar.current_animation == self.idle_animation: attack = options[random.randint(0, len(options)-1)] self.avatar.play(attack) # BUG: causes race conditions #self.in_attack = attack self.ai_timer.alarm = random.randint(200, 400) return else: self.avatar.play(self.idle_animation) self.ai_timer.alarm = random.randint(120, 200) self.ai_timer.alarm = self.update_freq
# print "kk",kk for i in xrange(n_par): #进行n_par个坐标循环 # print(' i='+str(i)) range1 = [lowb[i], upperb[i]] tmp2data = tmpdata.copy() tmp2data[i] = vdata[i] vji = vdata[i] dj2 = sum((vdata - tmp2data)**2) for k in xrange(size(datasum, 0)): if k == orpt: continue tmp2data[i] = datasum[k, i] vki = datasum[k, i] dk2 = sum((datasum[k, :] - tmp2data)**2) # print 'dk2',dk2 if abs(vki - vji) < 1e-10: continue xji = 1 / 2. * (vki + vji + (dk2 - dj2) / (vki - vji)) #计算xj的第i个分量 # print xji if xji > range1[0] and xji <= tmpdata[i]: range1[0] = xji elif xji < range1[1] and xji >= tmpdata[i]: range1[1] = xji # print "range1",range1 # exit() # print range1 newx_loc = range1[0] + (range1[1] - range1[0]) * random.rand() #均分分布生成新的坐标 tmpdata[i] = newx_loc oridata = list(oridata) + [list(tmpdata)] #该次迭代生成的ns个样本
import pyfits import cofe_util as util import toitools as toi import cPickle import numpy as np import matplotlib.pyplot as plt #working directories: current level, old (for servofile), main data dir (for UT of crossings) wd='/cofe/flight_data/Level1/1.2/' wds='/cofe/flight_data/Level1/1.1/' wdmain='/cofe/flight_data/Level1/' d10=pyfits.open(wd+'all_10GHz_data.fits') s10=pyfits.open(wds+'all_10GHz_servo.fits') a10=pyfits.open(wd+'magaz10.fits') ut=d10['TIME'].data['UT'] lon=s10[5].data['HYBRIDLONGITUDE'] mlon=np.mean(lon[abs(lon+1.8)<.3]) lon[abs(lon+1.8) >=.3]=mlon uts10=s10['time'].data['ut'] lat=s10[5].data['HYBRIDLATITUDE'] gaz=a10['10ghz'].data['az'] utcf=open(wd+'utcrossinputs10.pkl','rb') utcrossings=cPickle.load(utcf) utcf.close() print utcrossings azoffdic = { 1:np.zeros(3), 3:np.zeros(3), 5:np.zeros(3) } eltargetdic = { 1:np.zeros(3), 3:np.zeros(3), 5:np.zeros(3)} aztargetdic = {1:np.zeros(3), 3:np.zeros(3), 5:np.zeros(3) } utcrossdic = { 1:np.zeros(3), 3:np.zeros(3), 5:np.zeros(3) } loncrossdic = { 1:np.zeros(3), 3:np.zeros(3), 5:np.zeros(3) }
def sizing_calc(iParameters, gases, fData): #unpack all of the JSON data objects iParameters = json.loads(iParameters) if iParameters else { } #user parameters gases = json.loads(gases) if gases else {} #database gas composition fData = json.loads(fData) if fData else {} #database flammability data if iParameters and gases and fData: #find UFL - LFL - Su - Pmax from flammabilty data if fData is not None: fData.pop('_id') df = pd.DataFrame.from_dict(fData, orient='index').transpose() ufl = max(df[(df.Xi == 0) & (df.Flammable == 1)].Xf) * 100 lfl = min(df[(df.Xi == 0) & (df.Flammable == 1)].Xf) * 100 su = max(df.Su) p_max = max(df.Pmax) fuel_species = _get_fuel_species( gases) #makes non-cantera species propane Aw1 = iParameters['Length'] * iParameters['Height'] Aw2 = iParameters['Width'] * iParameters['Height'] Aw3 = iParameters['Width'] * iParameters['Length'] iVentPercent = 0.4 #create gas properties object gas_comp = Fuel(air=AIR_SPECIES, fuel=fuel_species, phi=iParameters['Phi'], f=1.0, P=iParameters['AmbientP'], T=iParameters['AmbientT'], S=su, Block=iParameters['Block'], Reduced=iParameters['rPressure'], Drag=iParameters['Discharge'], Static=iParameters['Static'], Number=iParameters['Number'], Adiabatic=p_max) userInput = Fuel( L=iParameters['Length'], W=iParameters['Width'], H=iParameters['Height'], ) cntrl = Fuel(tmax=0.35) explode = Vent(gas=gas_comp, room=userInput, cntrl=cntrl) ventPercent = 0.3 ventNum = iParameters['Number'] Av1 = ventPercent * Aw1 Avg = 0.001 Avo = 0 Asurface = 2 * Aw1 + 2 * Aw2 + Aw3 while 100 * abs(Avo - Avg) / (0.5 * (Avo + Avg)) > 1: Avo = explode.areaV(Av1) Avg = Av1 Av1 = Avo #dddd = explode.areaV(Av1) #dedud = {'VentArea': Avo} #dedud = json.dumps(dedud) #dddd = json.dumps(dddd) #return dddd, fuel_species return '{:.2f} m\u00b2'.format(Avo), '{:.2f} m\u00b2'.format(Asurface) else: return 'Error', 'Error'
def network_info(datapath): # f = open('data/node_info.csv', 'r', encoding='UTF8') f = open('data/node_info_final.csv', 'r', encoding='UTF8') rdr = csv.reader(f) a = 0 linenum = 0 node_data = {} newnodeid = {} minx = 1000.0 miny = 1000.0 maxx = 0.0 maxy = 0.0 nid = 0 for line in rdr: if linenum == 0: a = line else: newnodeid[int(line[0])] = nid node_data[nid] = {'NODE_ID': nid, 'NODE_TYPE': int(line[1]), 'NODE_NAME': line[2], 'lat': float(line[6]), 'long': float(line[5]), 'NODE_ID_OLD': float(line[0])} # 'NODE_ID', 'NODE_TYPE', 'NODE_NAME', 'lat'위도(Y), 'long' nid += 1 if minx > float(line[5]): minx = float(line[5]) if miny > float(line[6]): miny = float(line[6]) if maxx < float(line[5]): maxx = float(line[5]) if maxy < float(line[6]): maxy = float(line[6]) linenum += 1 print('total nodes', linenum - 1) f.close() # f = open('data/link_info.csv', 'r', encoding='UTF8') f = open('data/link_info_final.csv', 'r', encoding='UTF8') rdr = csv.reader(f) a = 0 lid = 0 linenum = 0 link_data = {} newlinkid = {} for line in rdr: if linenum == 0: a = line else: fn = newnodeid[int(line[1])] tn = newnodeid[int(line[2])] newlinkid[int(line[0])] = lid link_data[lid] = {'LINK_ID': lid, 'F_NODE': fn, 'T_NODE': tn, 'MAX_SPD': float(line[11]), 'LENGTH': float(line[15])/1000, 'CUR_SPD': float( 0), 'WEIGHT': float(line[15])} # 'LINK_ID', 'F_NODE', 'T_NODE', 'MAX_SPD', 'LENGTH' (line[0], line[1], line[2], line[11], line[15]) lid += 1 linenum += 1 print('total links', linenum-1) f.close() f = open(datapath, 'r', encoding='UTF8') rdr = csv.reader(f) a = 0 linenum = 0 link_traffic = {} for line in rdr: linenum += 1 if int(line[1]) > 4000000000 and int(line[1]) < 4090000000: if int(line[1]) not in newlinkid.keys(): continue lid = newlinkid[int(line[1])] # print(lid, int(line[1])) if lid in link_traffic: link_traffic[lid].append(float(line[2])) else: link_traffic[lid] = [float(line[2])] # print(line) # print('l', linenum) f.close() f = open('data/chargingstation.csv', 'r') rdr = csv.reader(f) linenum = 0 cs_info = {} for line in rdr: if linenum == 0: print(line) else: if line[7] == 'Y': mindist = 100000 n_id = -1 # print(linenum, line[7],line[17],line[16], line) x1 = float(line[17]) y1 = float(line[16]) for n in node_data.keys(): x2 = node_data[n]['long'] y2 = node_data[n]['lat'] diff = abs(x1 - x2) + abs(y1 - y2) if mindist > diff: mindist = diff n_id = n # print(n_id, mindist ) if n_id in cs_info.keys(): if diff < cs_info[n_id]['diff_node']: cs_info[n_id] = {'CS_ID': n_id, 'CS_NAME': line[0], 'lat': node_data[n_id]['lat'], 'long': node_data[n_id]['long'],'real_lat': float(line[16]), 'real_long': float(line[17]), 'diff_node': mindist} else: cs_info[n_id] = {'CS_ID': n_id, 'CS_NAME': line[0], 'lat': node_data[n_id]['lat'], 'long': node_data[n_id]['long'], 'real_lat': float(line[16]), 'real_long': float(line[17]), 'diff_node': mindist} linenum+=1 f.close() # print(len(cs_info)) # for n_id in cs_info.keys(): # print(cs_info[n_id]) # f = open('data/node_info_all_final.csv', 'w', newline='') # wr = csv.writer(f) # for n_id in node_data.keys(): # wr.writerow([node_data[n_id]['NODE_ID'],node_data[n_id]['NODE_TYPE'],node_data[n_id]['NODE_NAME'],node_data[n_id]['lat'],node_data[n_id]['long'],node_data[n_id]['NODE_ID_OLD']]) # f.close() # # # f = open('data/link_info_all_final.csv', 'w', newline='') # wr = csv.writer(f) # for n_id in link_data.keys(): # wr.writerow([link_data[n_id]['LINK_ID'],link_data[n_id]['F_NODE'],link_data[n_id]['T_NODE'],link_data[n_id]['MAX_SPD'],link_data[n_id]['LENGTH'],link_data[n_id]['CUR_SPD'], link_data[n_id]['WEIGHT']]) # f.close() # # f = open('data/cs_info_all_final.csv', 'w', newline='') # wr = csv.writer(f) # for n_id in cs_info.keys(): # wr.writerow([cs_info[n_id]['CS_ID'],cs_info[n_id]['CS_NAME'],cs_info[n_id]['lat'],cs_info[n_id]['long'],cs_info[n_id]['real_lat'],cs_info[n_id]['real_long']]) # f.close() return link_data, node_data, link_traffic, cs_info, minx, miny, maxx, maxy
s = input() n = 97 c = 0 for i in s: x = abs(ord(i) - n) if x > 13: c += abs(x - 26) else: c += x n = ord(i) print(c)
def combine_kp(standard_inst=None, recent_inst=None, forecast_inst=None, start=None, stop=None, fill_val=np.nan): """ Combine the output from the different Kp sources for a range of dates Parameters ---------- standard_inst : pysat.Instrument or NoneType Instrument object containing data for the 'sw' platform, 'kp' name, and '' tag or None to exclude (default=None) recent_inst : pysat.Instrument or NoneType Instrument object containing data for the 'sw' platform, 'kp' name, and 'recent' tag or None to exclude (default=None) forecast_inst : pysat.Instrument or NoneType Instrument object containing data for the 'sw' platform, 'kp' name, and 'forecast' tag or None to exclude (default=None) start : dt.datetime or NoneType Starting time for combining data, or None to use earliest loaded date from the pysat Instruments (default=None) stop : dt.datetime Ending time for combining data, or None to use the latest loaded date from the pysat Instruments (default=None) fill_val : int or float Desired fill value (since the standard instrument fill value differs from the other sources) (default=np.nan) Returns ------- kp_inst : pysat.Instrument Instrument object containing Kp observations for the desired period of time, merging the standard, recent, and forecasted values based on their reliability Note ---- Merging prioritizes the standard data, then the recent data, and finally the forecast data Will not attempt to download any missing data, but will load data """ notes = "Combines data from" # Create an ordered list of the Instruments, excluding any that are None all_inst = list() tag = 'combined' inst_flag = None if standard_inst is not None: all_inst.append(standard_inst) tag += '_standard' if inst_flag is None: inst_flag = 'standard' if recent_inst is not None: all_inst.append(recent_inst) tag += '_recent' if inst_flag is None: inst_flag = 'recent' if forecast_inst is not None: all_inst.append(forecast_inst) tag += '_forecast' if inst_flag is None: inst_flag = 'forecast' if len(all_inst) < 2: raise ValueError("need at two Kp Instrument objects to combine them") # If the start or stop times are not defined, get them from the Instruments if start is None: stimes = [inst.index.min() for inst in all_inst if len(inst.index) > 0] start = min(stimes) if len(stimes) > 0 else None if stop is None: stimes = [inst.index.max() for inst in all_inst if len(inst.index) > 0] stop = max(stimes) if len(stimes) > 0 else None stop += pds.DateOffset(days=1) if start is None or stop is None: raise ValueError(' '.join(("must either load in Instrument objects or", "provide starting and ending times"))) # Initialize the output instrument kp_inst = pysat.Instrument(labels=all_inst[0].meta_labels) kp_inst.inst_module = pysat_sw.instruments.sw_kp kp_inst.tag = tag kp_inst.date = start kp_inst.doy = int(start.strftime("%j")) kp_inst.meta = pysat.Meta(labels=kp_inst.meta_labels) initialize_kp_metadata(kp_inst.meta, 'Kp', fill_val=fill_val) kp_times = list() kp_values = list() # Cycle through the desired time range itime = start while itime < stop and inst_flag is not None: # Load and save the standard data for as many times as possible if inst_flag == 'standard': standard_inst.load(date=itime) if notes.find("standard") < 0: notes += " the {:} source ({:} to ".format( inst_flag, itime.date()) if len(standard_inst.index) == 0: inst_flag = 'forecast' if recent_inst is None else 'recent' notes += "{:})".format(itime.date()) else: kp_times.extend(list(standard_inst.index)) kp_values.extend(list(standard_inst['Kp'])) itime = kp_times[-1] + pds.DateOffset(hours=3) # Load and save the recent data for as many times as possible if inst_flag == 'recent': # Determine which files should be loaded if len(recent_inst.index) == 0: files = np.unique(recent_inst.files.files[itime:stop]) else: files = [None] # No load needed, if already initialized # Cycle through all possible files of interest, saving relevant # data for filename in files: if filename is not None: recent_inst.load(fname=filename) if notes.find("recent") < 0: notes += " the {:} source ({:} to ".format( inst_flag, itime.date()) # Determine which times to save local_fill_val = recent_inst.meta[ 'Kp', recent_inst.meta.labels.fill_val] good_times = ((recent_inst.index >= itime) & (recent_inst.index < stop)) good_vals = recent_inst['Kp'][good_times] != local_fill_val # Save output data and cycle time kp_times.extend(list(recent_inst.index[good_times][good_vals])) kp_values.extend(list( recent_inst['Kp'][good_times][good_vals])) itime = kp_times[-1] + pds.DateOffset(hours=3) inst_flag = 'forecast' if forecast_inst is not None else None notes += "{:})".format(itime.date()) # Load and save the forecast data for as many times as possible if inst_flag == "forecast": # Determine which files should be loaded if len(forecast_inst.index) == 0: files = np.unique(forecast_inst.files.files[itime:stop]) else: files = [None] # No load needed, if already initialized # Cycle through all possible files of interest, saving relevant # data for filename in files: if filename is not None: forecast_inst.load(fname=filename) if notes.find("forecast") < 0: notes += " the {:} source ({:} to ".format( inst_flag, itime.date()) # Determine which times to save local_fill_val = forecast_inst.meta[ 'Kp', forecast_inst.meta.labels.fill_val] good_times = ((forecast_inst.index >= itime) & (forecast_inst.index < stop)) good_vals = forecast_inst['Kp'][good_times] != local_fill_val # Save desired data and cycle time new_times = list(forecast_inst.index[good_times][good_vals]) kp_times.extend(new_times) new_vals = list(forecast_inst['Kp'][good_times][good_vals]) kp_values.extend(new_vals) itime = kp_times[-1] + pds.DateOffset(hours=3) notes += "{:})".format(itime.date()) inst_flag = None if inst_flag is not None: notes += "{:})".format(itime.date()) # Determine if the beginning or end of the time series needs to be padded freq = None if len(kp_times) < 2 else pysat.utils.time.calc_freq(kp_times) end_date = stop - pds.DateOffset(days=1) date_range = pds.date_range(start=start, end=end_date, freq=freq) if len(kp_times) == 0: kp_times = date_range if date_range[0] < kp_times[0]: # Extend the time and value arrays from their beginning with fill # values itime = abs(date_range - kp_times[0]).argmin() kp_times.reverse() kp_values.reverse() extend_times = list(date_range[:itime]) extend_times.reverse() kp_times.extend(extend_times) kp_values.extend([fill_val for kk in extend_times]) kp_times.reverse() kp_values.reverse() if date_range[-1] > kp_times[-1]: # Extend the time and value arrays from their end with fill values itime = abs(date_range - kp_times[-1]).argmin() + 1 extend_times = list(date_range[itime:]) kp_times.extend(extend_times) kp_values.extend([fill_val for kk in extend_times]) # Save output data kp_inst.data = pds.DataFrame(kp_values, columns=['Kp'], index=kp_times) # Resample the output data, filling missing values if (date_range.shape != kp_inst.index.shape or abs(date_range - kp_inst.index).max().total_seconds() > 0.0): kp_inst.data = kp_inst.data.resample(freq).fillna(method=None) if np.isfinite(fill_val): kp_inst.data[np.isnan(kp_inst.data)] = fill_val # Update the metadata notes for this custom procedure notes += ", in that order" kp_inst.meta['Kp', kp_inst.meta.labels.notes] = notes return kp_inst
def build_matched_spec(search_results, identified_spectra, cluster_data): #if none identification data found if not identified_spectra or len(identified_spectra) < 1: return None matched_spec = list() # psm_dict = dict() logging.info("start to build matched spec details") for spec_title in search_results.keys(): search_result = search_results.get(spec_title) dot = float(search_result.get('dot')) f_val = float(search_result.get('fval')) cluster_id = search_result.get('lib_spec_id') cluster = cluster_data.get(cluster_id) if cluster == None: logging.debug("Null cluster for: %s, which may small than 5"%(cluster_id)) continue cluster_ratio = float(cluster.get('ratio')) cluster_size = int(cluster.get('size')) cluster_conf_sc_str = json_stand(cluster.get('conf_sc')) seqs_ratios_str = json_stand(cluster.get('seqs_ratios')) seqs_mods_str = cluster.get('seqs_mods') conf_sc_dict = None seqs_ratios_dict = None mods_dict = None if cluster_conf_sc_str: conf_sc_dict = json.loads(cluster_conf_sc_str) if seqs_ratios_str: seqs_ratios_dict = json.loads(seqs_ratios_str) if seqs_mods_str: mods_dict = json.loads(seqs_mods_str) max_sc = 0.0 max_sc_seq = '' if conf_sc_dict == None: logging.info("cluster %s do not has confidence score str" % (cluster_id)) continue for each_seq in conf_sc_dict.keys(): if float(conf_sc_dict.get(each_seq)) > max_sc: max_sc = float(conf_sc_dict.get(each_seq)) max_sc_seq = each_seq identification = identified_spectra.get(spec_title) recomm_seq = "" recomm_mods = "" conf_sc = 0.0 recomm_seq_sc = 0.0 if identification: # pre_seq = identification.get('id_seq') # pre_mods = identification.get('id_mods') pre_seq = identification.get('peptideSequence') if pre_seq == None: pre_seq = identification.get('id_seq') pre_mods = identification.get('modifications') if pre_mods == None: pre_mods = identification.get('id_mods') # il_seq = pre_seq.replace('I', 'L') seq_ratio = float(seqs_ratios_dict.get(pre_seq, -1)) if abs(seq_ratio - cluster_ratio) <= 0.001: # this seq matches to the highest score seq recomm_seq = "PRE_" recomm_mods = "" conf_sc = float(conf_sc_dict.get(pre_seq, -1)) if abs(conf_sc + 1) <=0.001: #pre_seq has matched seq_ratio but not in conf_sc_dict, error logging.error("Found no conf_sc for pre_seq %s" %(pre_seq)) logging.error("From conf_sc_dict %s" %(conf_sc_dict)) recomm_seq_sc = conf_sc elif pre_seq in conf_sc_dict.keys(): # this seq matches to the lower score seq recomm_seq = "R_Better_" + max_sc_seq if mods_dict: recomm_mods = mods_dict.get(max_sc_seq) else: recomm_mods = "" conf_sc = float(conf_sc_dict.get(pre_seq)) recomm_seq_sc = max_sc else: # this seq matches non seq in the cluster pre_seq = '' pre_mods = '' recomm_seq = "R_NEW_" + max_sc_seq if mods_dict: recomm_mods = mods_dict.get(max_sc_seq) else: recomm_mods = "" conf_sc = 0 recomm_seq_sc = max_sc matched_spec.append((spec_title, dot, f_val, cluster_id, cluster_size, cluster_ratio, pre_seq, pre_mods, recomm_seq, recomm_mods, conf_sc, recomm_seq_sc)) logging.info("Done build_matched_spec, build %d matched spec from %d search results and %d identified spectra."%(len(matched_spec), len(search_results), len(identified_spectra))) return matched_spec
def fitness_MD(self, list_of_x: np.ndarray): value = 0.0 for el in self.T: # value += abs(list_of_x[0] * el[0] ** list_of_x[1] - el[1]) value += abs(el[1] - list_of_x[0] * el[0]**list_of_x[1]) return value
def place_varga(A, B, p, dtime=False, alpha=None): """Place closed loop eigenvalues K = place_varga(A, B, p, dtime=False, alpha=None) Required Parameters ---------- A : 2D array Dynamics matrix B : 2D array Input matrix p : 1D list Desired eigenvalue locations Optional Parameters --------------- dtime : bool False for continuous time pole placement or True for discrete time. The default is dtime=False. alpha : double scalar If `dtime` is false then place_varga will leave the eigenvalues with real part less than alpha untouched. If `dtime` is true then place_varga will leave eigenvalues with modulus less than alpha untouched. By default (alpha=None), place_varga computes alpha such that all poles will be placed. Returns ------- K : 2D array (or matrix) Gain such that A - B K has eigenvalues given in p. Algorithm --------- This function is a wrapper for the slycot function sb01bd, which implements the pole placement algorithm of Varga [1]. In contrast to the algorithm used by place(), the Varga algorithm can place multiple poles at the same location. The placement, however, may not be as robust. [1] Varga A. "A Schur method for pole assignment." IEEE Trans. Automatic Control, Vol. AC-26, pp. 517-519, 1981. Notes ----- The return type for 2D arrays depends on the default class set for state space operations. See :func:`~control.use_numpy_matrix`. Examples -------- >>> A = [[-1, -1], [0, 1]] >>> B = [[0], [1]] >>> K = place_varga(A, B, [-2, -5]) See Also: -------- place, acker """ # Make sure that SLICOT is installed try: from slycot import sb01bd except ImportError: raise ControlSlycot("can't find slycot module 'sb01bd'") # Convert the system inputs to NumPy arrays A_mat = np.array(A) B_mat = np.array(B) if (A_mat.shape[0] != A_mat.shape[1] or A_mat.shape[0] != B_mat.shape[0]): raise ControlDimension("matrix dimensions are incorrect") # Compute the system eigenvalues and convert poles to numpy array system_eigs = np.linalg.eig(A_mat)[0] placed_eigs = np.array(p) # Need a character parameter for SB01BD if dtime: DICO = 'D' else: DICO = 'C' if alpha is None: # SB01BD ignores eigenvalues with real part less than alpha # (if DICO='C') or with modulus less than alpha # (if DICO = 'D'). if dtime: # For discrete time, slycot only cares about modulus, so just make # alpha the smallest it can be. alpha = 0.0 else: # Choosing alpha=min_eig is insufficient and can lead to an # error or not having all the eigenvalues placed that we wanted. # Evidently, what python thinks are the eigs is not precisely # the same as what slicot thinks are the eigs. So we need some # numerical breathing room. The following is pretty heuristic, # but does the trick alpha = -2 * abs(min(system_eigs.real)) elif dtime and alpha < 0.0: raise ValueError("Discrete time systems require alpha > 0") # Call SLICOT routine to place the eigenvalues A_z, w, nfp, nap, nup, F, Z = \ sb01bd(B_mat.shape[0], B_mat.shape[1], len(placed_eigs), alpha, A_mat, B_mat, placed_eigs, DICO) # Return the gain matrix, with MATLAB gain convention return _ssmatrix(-F)
def match_request_time_in_orderbook_entry(control_db: str, target_db: str, col_name: str, start_time: int, end_time: int): db_client = SharedMongoClient.instance() control_col = db_client[control_db][col_name] target_col = db_client[target_db][col_name] ctrl_data_set: Cursor = control_col.find({ "requestTime": { "$gte": start_time, "$lte": end_time } }).sort([("requestTime", 1)]) # get first nearest request time from control db first_ctrl_rq = ctrl_data_set[0]["requestTime"] # get first and second request time from target db trgt_data_set = list( target_col.find({ "requestTime": { "$gte": start_time, "$lte": end_time } }).sort([("requestTime", 1)])[:2]) # first target requestTime first_trgt_rq = trgt_data_set[0]["requestTime"] # second target requestTime second_trgt_rq = trgt_data_set[1]["requestTime"] # calc difference between control reqTime and target reqTimes ctrl_first_trgt_first_diff = abs(first_ctrl_rq - first_trgt_rq) ctrl_first_trgt_second_diff = abs(first_ctrl_rq - second_trgt_rq) # if first in target is nearer to first in control, set first in target as starting point if ctrl_first_trgt_first_diff < ctrl_first_trgt_second_diff: trgt_start_rq = first_trgt_rq # if second in target is nearer to first in control, set second in target as starting point elif ctrl_first_trgt_first_diff > ctrl_first_trgt_second_diff: trgt_start_rq = second_trgt_rq else: raise Exception( "Difference is same, please Manually check the database and fix!!" ) # get count of data from control db ctrl_data_count = ctrl_data_set.count() # get same count of data from target db with the starting point as start time and without end time trgt_data_set: Cursor = target_col.find({ "requestTime": { "$gte": trgt_start_rq } }).sort([("requestTime", 1)]).limit(ctrl_data_count) trgt_data_count = trgt_data_set.count(with_limit_and_skip=True) logging.info("ctrl count count: %d, trgt: %d" % (ctrl_data_count, trgt_data_count)) assert (ctrl_data_count == trgt_data_count) last_index = ctrl_data_count - 1 ctrl_last_rq = ctrl_data_set[last_index]["requestTime"] trgt_last_rq = trgt_data_set[last_index]["requestTime"] assert (abs(ctrl_last_rq - trgt_last_rq) < 3) # loop through both # update target's request time with control's request for ctrl_data, trgt_data in zip(ctrl_data_set, trgt_data_set): ctrl_rq = ctrl_data["requestTime"] trgt_rq = trgt_data["requestTime"] logging.info("ctrl_rqt: %d, trgt_rqt: %d" % (ctrl_rq, trgt_rq)) if trgt_rq == ctrl_rq: continue SharedMongoClient._async_update(target_col, {"requestTime": trgt_rq}, {"$set": { "requestTime": ctrl_rq }})
volatilityList, riskFreeRateList, timeToMaturityList, dividendYieldList, optionPriceList, deltaList, gammaList, vegaList, thetaList, rhoList, OptionType.Call, numAssets) print("Done") runtime = CFBlackScholesMerton.lastruntime() #Format output to match the example in C++, simply to aid comparison of results print( "+-------+-----------+----------------+--------------+---------------+---------------+---------------+" ) print( "| Index | Price | Delta | Gamma | Vega | Theta | Rho |" ) print( "+-------+-----------+----------------+--------------+---------------+---------------+---------------+" ) for loop in range(0, numAssets): print(loop, "\t%9.5f" % optionPriceList[loop], "\t%9.5f" % deltaList[loop], "\t%9.5f" % gammaList[loop], "\t%9.5f" % vegaList[loop], "\t%9.5f" % thetaList[loop], "\t%9.5f" % rhoList[loop]) if (abs(expectedResultList[loop] - optionPriceList[loop])) > tolerance: print("Comparison failure - expected", expectedResultList[loop], "returned %9.5f" % optionPriceList[loop]) print("\nThis run took", str(runtime), "microseconds") #Relinquish ownership of the card CFBlackScholesMerton.releaseDevice()