def calcTvalue(p, df): t = None if (df == 1): t = math.cos(p*math.pi/2.)/math.sin(p*math.pi/2.) elif (df == 2): t = math.sqrt(2./(p*(2. - p)) - 2.) else: a = 1./(df - 0.5) b = 48./(a*a) c = ((20700.*a/b - 98.)*a - 16.)*a + 96.36 d = ((94.5/(b + c) - 3.)/b + 1.)*math.sqrt(a*math.pi*0.5)*df x = d*p y = pow(x, 2./df) if (y > 0.05 + a): x = Norm_z(0.5*(1. - p)) y = x*x if (df < 5.): c = c + 0.3*(df - 4.5)*(x + 0.6) c = (((0.05*d*x - 5.)*x - 7.)*x - 2.)*x + b + c y = (((((0.4*y + 6.3)*y + 36.)*y + 94.5)/c - y - 3.)/b + 1.)*x y = a*y*y if (y > 0.002): y = math.exp(y) - 1. else: y = 0.5*y*y + y t = sqrt(df*y) else: y = ((1./(((df + 6.)/(df*y) - 0.089*d - 0.822)*(df + 2.)*3.) + 0.5/(df + 4.))*y - 1.)*(df + 1.)/(df + 2.) + 1./y; t = math.sqrt(df*y) return t
def rotateImg(img): corners = findCorners(img) center = (sum(c[0] for c in corners) / 4, sum(c[1] for c in corners) / 4) p1 = np.float32((corners[0][0] + corners[3][0], corners[0][1] + corners[3][1])) p2 = np.float32((corners[1][0] + corners[2][0], corners[1][1] + corners[2][1])) p3 = np.float32((corners[0][0] + corners[1][0], corners[0][1] + corners[1][1])) p4 = np.float32((corners[2][0] + corners[3][0], corners[2][1] + corners[3][1])) width = math.sqrt((p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1])) / 2 height = math.sqrt((p3[0] - p4[0]) * (p3[0] - p4[0]) + (p3[1] - p4[1]) * (p3[1] - p4[1])) / 2 h, w = img.shape[:2] if width < height: center = (center[1], center[0]) img = imgRotate.rotate(img, 90) hsvImg = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) hsvImg = cv2.inRange(hsvImg, np.array((90, 60, 50), dtype=np.uint8), np.array((140, 255, 255), dtype=np.uint8)) c, hy = cv2.findContours(hsvImg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for cnt in c: if len(cnt) < 5: continue ellipse = cv2.fitEllipse(cnt) signetCenter, r, a = ellipse if r[0] < 30 or r[1] < 50 or abs(signetCenter[0] - center[0]) > 50: continue if signetCenter[1] > center[1]: rot_mat = cv2.getRotationMatrix2D((w / 2, h / 2), 180, 1.0) img = cv2.warpAffine(img, rot_mat, (w , h), flags=cv2.INTER_LINEAR, borderValue=(255, 255, 255)) return img raise Exception(_("不是增值税发票"))
def synthesize(self , method = 0 , forceReSynthesis = True): """ function that will synthesise the approximant using the list of atoms this is mostly DEPRECATED""" if self.originalSignal == None: _Logger.warning("No original Signal provided") # return None if (self.recomposedSignal == None) | forceReSynthesis: synthesizedSignal = zeros(self.length) if len(self.atoms) == 0: _Logger.info("No Atoms") return None # first method by inverse MDCT if method == 0: for mdctSize in self.dico.sizes: mdctVec = zeros(self.length) for atom in self.atoms: if atom.length == mdctSize: # bugFIx n = atom.timePosition +1 frame = math.floor( float(n) / float(atom.length /2) ) +1 # mdctVec[frame*float(atom.length /2) + atom.frequencyBin] += atom.amplitude mdctVec[frame*float(atom.length /2) + atom.frequencyBin] += atom.mdct_value synthesizedSignal += imdct(mdctVec , mdctSize) # synthesizedSignal += concatenate((zeros(mdctSize/4) , imdct(mdctVec , mdctSize)) )[1:-mdctSize/4+1] # second method by recursive atom synthesis - NOT WORKING elif method == 1: for atom in self.atoms: atom.synthesizeIFFT() synthesizedSignal[atom.timePosition : atom.timePosition + atom.length] += atom.waveform # HACK here to resynthesize using LOMP atoms elif method == 2: for atom in self.atoms: atom.waveForm = atom.synthesizeIFFT() if (atom.projectionScore is not None): if (atom.projectionScore <0): atom.waveform = (-math.sqrt(-atom.projectionScore/sum(atom.waveform**2)) )*atom.waveform else: atom.waveform = (math.sqrt(atom.projectionScore/sum(atom.waveform**2)) )*atom.waveform synthesizedSignal[atom.timePosition : atom.timePosition + atom.length] += atom.waveform self.recomposedSignal = signals.Signal(synthesizedSignal , self.samplingFrequency) #return self.recomposedSignal # other case: we just give the existing synthesized Signal. return self.recomposedSignal
def Haar(points, depth): if len(points) < 2 or depth < 1: return points if depth > math.log(len(points), 2): depth = math.log(len(points), 2) sum_sequence = [] diff_sequence = [] for i in range(0, len(points), 2): diff_sequence.append((points[i] - points[i + 1]) / math.sqrt(2)) sum_sequence.append((points[i] + points[i + 1]) / math.sqrt(2)) v = Haar(sum_sequence, depth - 1) v.extend(diff_sequence) return v
def costurnangle(fromm,to): v = fromm[0]-to[0] u = fromm[1]-to[1] if v == 0: return 0 if u==0: return 1.579 r = math.sqrt(v*v + (u)*(u)) point = [v,u] length = math.sqrt((v-r)*(v-r) + u*u) if v/u>0: return math.acos( (length*length - 2*r*r)/(2*r*r)) return -math.acos((length * length - 2 * r * r) / (2 * r * r))
def DPLSW(self, thetaTild, countXVec, myMDP, featuresMatrix, gamma, epsilon, delta,batchSize, initStateDist="uniform", pi="uniform"): dim=len(featuresMatrix.T) alpha=(5.0*numpy.sqrt(2*numpy.math.log(2.0/delta)))/epsilon beta= (epsilon/4)/(dim+numpy.math.log(2.0/delta)) Gamma_w=myMDP.getGammaMatrix() for i in range(len(countXVec)): Gamma_w[i][i]=Gamma_w[i][i]*countXVec[i]/batchSize GammaSqrt= (Gamma_w) for i in range(len(GammaSqrt)): GammaSqrt[i][i]=math.sqrt(Gamma_w[i][i]) GammaSqrtPhi= numpy.mat(GammaSqrt) *numpy.mat(featuresMatrix) if self.is_invertible(GammaSqrtPhi): GammaSqrtPhiInv=linalg.inv(GammaSqrtPhi) else: GammaSqrtPhiInv=linalg.pinv(GammaSqrtPhi) PsiBetaX= self.SmootBound_LSW(myMDP, Gamma_w, countXVec, beta, myMDP.startStateDistribution()) sigmmaX= (alpha*myMDP.getMaxReward())/(1-gamma) sigmmaX=sigmmaX*numpy.linalg.norm(GammaSqrtPhiInv) sigmmaX=sigmmaX*math.pow(PsiBetaX, .5) cov_X=math.pow(sigmmaX,2)*numpy.identity(dim) mean=numpy.zeros(dim) ethaX=numpy.random.multivariate_normal(mean,cov_X) thetaTild=numpy.squeeze(numpy.asarray(thetaTild)) ethaX=numpy.squeeze(numpy.asarray(ethaX)) thetaTild_priv=thetaTild+ethaX return [thetaTild_priv,thetaTild,math.pow(sigmmaX,2)]
def LSL_subSampleAggregate(self, batch, s, numberOfsubSamples,myMDP,featuresMatrix,regCoef, pow_exp,numTrajectories,epsilon,delta,distUB): dim=len(featuresMatrix.T) alpha=(5.0*numpy.sqrt(2*numpy.math.log(2.0/delta)))/epsilon #beta= (epsilon/4)*(dim+numpy.math.log(2.0/delta)) beta= (s/(2*numberOfsubSamples)) subSamples=self.subSampleGen(batch, numberOfsubSamples) z=numpy.zeros((len(subSamples),dim)) for i in range(len(subSamples)): FVMC=self.FVMCPE(myMDP, featuresMatrix, subSamples[i]) #regc=self.computeLambdas(myMDP, featuresMatrix,regCoef, len(subSamples[i]), pow_exp) #z[i]=numpy.ravel(self.LSL(FVMC[2], myMDP, featuresMatrix,regc[0][0],len(subSamples[i]),FVMC[1])) SA_reidge_coef=100*math.pow(len(subSamples[i]), 0.5) z[i]=numpy.ravel(self.LSL(FVMC[2], myMDP, featuresMatrix,SA_reidge_coef,len(subSamples[i]),FVMC[1])) #z[i]= numpy.squeeze(numpy.asarray(FVMC[0]))#this is LSW partitionPoint=int((numberOfsubSamples+math.sqrt(numberOfsubSamples))/2) g= self.generalized_median(myMDP,z,partitionPoint,distUB) #g= self.aggregate_median(myMDP,z) #To check the following block S_z=self.computeAggregateSmoothBound(z, beta, s,myMDP,distUB) #print(S_z) cov_X=(S_z/alpha)*numpy.identity((dim)) ethaX=numpy.random.multivariate_normal(numpy.zeros(dim),cov_X) #print(S_z) #noise=(S_z/alpha)*ethaX #numpy.mat(featuresMatrix)*numpy.mat(g[1]+ethaX) temp_priv=numpy.mat(featuresMatrix)*numpy.mat(g[1]+ethaX).T return [temp_priv, numpy.mat(featuresMatrix)*numpy.mat(g[1]).T]
def great_circle_distance(lon1, lat1, lon2, lat2): # This function calculates the great circle distance between two points x_dist = abs(lon1 - lon2) y_dist = abs(lat1 - lat2) distance = math.sqrt((x_dist)**2 + (y_dist)**2) return distance
def slopeConfidence(alpha, linePoints): if len(linePoints)<2: return "Error: not enough points for calculation" if len(linePoints)==2: regression = lineRegress(linePoints) return regression["slope"], regression["intercept"],(regression["slope"],regression["slope"]) #get linear regression for points regression = lineRegress(linePoints) #get Tscore tScore = stats.t.ppf((1-alpha/2), len(linePoints)-2) #get s(b1) == (MSE)/sum(xi-mean(x))^2) xVctr, yVctr = _pointsToVectors(linePoints) MSE = _MSE(regression["slope"], regression["intercept"],linePoints) xMean = mean(xVctr) xMeanDiffArray = [] for x in xVctr: xDiff = x - xMean xDiffSq = xDiff *xDiff xMeanDiffArray.append(xDiffSq) xDiffSum = sum(xMeanDiffArray) sSqVal = MSE/xDiffSum sVal = math.sqrt(sSqVal) deltaConfidence = tScore*sVal confidenceInterval = (regression["slope"]-deltaConfidence,regression["slope"]+deltaConfidence) return regression["slope"], regression["intercept"], confidenceInterval
def weighted_dif_L2_norm(self, mdp, v ,vhat): Gamma = mdp.getGammaMatrix() temp1=numpy.mat((numpy.ravel(v)-numpy.ravel(vhat)))*numpy.mat(Gamma) temp=temp1*numpy.mat(numpy.ravel(v)-numpy.ravel(vhat)).T temp=math.sqrt(temp) return temp
def SeriesRse(f,Rse,Z0=None): """Series Skin-effect Resistance @param Rse float resistance specified as ohms/sqrt(Hz) @param f float frequency @param Z0 (optional) float of complex reference impedance (defaults to 50 ohms) @return the list of list s-parameter matrix for a series resistance due to skin-effect """ return SeriesZ(Rse*math.sqrt(f),Z0)
def goto(self, v, p, tol): while True: [x, y, theta] = self.getRobotPose(); distance = math.sqrt(((x - p.getX()) ** 2) + ((y - p.getY()) ** 2)) delta_theta = GeometryHelper.diffDegree(math.atan2(p.getY() - y, p.getX() - x), theta) if (distance < tol): return True self.move([v, delta_theta])
def move(self, motion): v = motion[0] omega = motion[1] self._currentV = v self._currentOmega = omega # translational and rotational speed is limited: if omega > self._maxOmega: omega = self._maxOmega if omega < -self._maxOmega: omega = -self._maxOmega if v > self._maxSpeed: v = self._maxSpeed if v < -self._maxSpeed: v = -self._maxSpeed # print ("motion ", v, omega * 180 / math.pi) # Odometry pose update (based on the motion command): d = v * self._T dTheta = omega * self._T self._odoX += d * math.cos(self._odoTheta + 0.5 * dTheta) self._odoY += d * math.sin(self._odoTheta + 0.5 * dTheta) self._odoTheta = (self._odoTheta + dTheta) % (2 * math.pi) # Add noise to v: if not self._motionNoise: return self._world.moveRobot(d, dTheta, self._T) sigma_v_2 = (self._k_d / self._T) * abs(v) v_noisy = v + random.gauss(0.0, math.sqrt(sigma_v_2)) # Add noise to omega: sigma_omega_tr_2 = (self._k_theta / self._T) * abs(omega) # turning rate noise sigma_omega_drift_2 = (self._k_drift / self._T) * abs(v) # drift noise omega_noisy = omega + random.gauss(0.0, math.sqrt(sigma_omega_tr_2)) omega_noisy += random.gauss(0.0, math.sqrt(sigma_omega_drift_2)) # Move robot in the world (with noise): d_noisy = v_noisy * self._T dTheta_noisy = omega_noisy * self._T # call the move listeners self._moveListener.emit() return self._world.moveRobot(d_noisy, dTheta_noisy, self._T)
def distance_to_wearable(lon1, lat1, lon2, lat2): # This function calculates the distance from each reference point to the # moveable point x_dist = abs(lon1 - lon2) y_dist = abs(lat1 - lat2) distance = math.sqrt((x_dist)**2 + (y_dist)**2) #print("Distance: ", distance) return distance
def SmoothBound_LSL(self,featurmatrix, myMDP, countXVec, rho, regCoef,beta,numTrajectories): normPhi = numpy.linalg.norm(featurmatrix,2) maxRho = numpy.linalg.norm(rho,Inf) c_lambda = normPhi*maxRho/(math.sqrt(2*regCoef)) #print('===============================================') #print(regCoef) l2Rho = numpy.linalg.norm(rho) phi_k = 0 Vals = [] for k in range(0, numTrajectories+1): minVal=0 for s in range(len(myMDP.getStateSpace())): minVal = minVal+rho[s] * min(countXVec[s]+k, numTrajectories) phi_k = c_lambda*math.sqrt(minVal)+l2Rho Vals.append((math.pow(phi_k,2))*math.exp(-k*beta)) upperBound=max(Vals) return upperBound
def heuristic(self, a, b): # a and b are indexes, must have the coordinates in OccupancyGrid a = self._grid.transformIndexesToCoordinates(a) b = self._grid.transformIndexesToCoordinates(b) (x1, y1) = a (x2, y2) = b distance = math.sqrt(abs(x1 - y1) + abs(x2 - y2)) return distance
def shapeWaveAmplitude(self, amp, wave): if self.plucked: for i in range(0, len(wave)): wave[i] *= amp * (1 - math.sqrt(i / len(wave))) return wave else: return amp * wave
def weighted_dif_L2_norm(self, mdp, v ,vhat): #v=v.flatten() #vhat=vhat.flatten() Gamma = mdp.getGammaMatrix() temp1=numpy.mat((numpy.ravel(v)-numpy.ravel(vhat)))*numpy.mat(Gamma) temp=temp1*numpy.mat(numpy.ravel(v)-numpy.ravel(vhat)).T temp=math.sqrt(temp) return temp
def _sampleMotionModel(self, noiseFaktor=30, noiseReposition=0.05): for i in range(self._numberOfParticles): v = max(self._robot._currentV, 0.01) omega = self._robot._currentOmega sigma_v_2 = (self._robot._k_d * noiseFaktor / self._robot._T) * abs(v) v_noisy = v + random.normal(0.05, math.sqrt(sigma_v_2)) # Add noise to omega: sigma_omega_tr_2 = (self._robot._k_theta / self._robot._T) * abs(omega + 0.0001) # turning rate noise sigma_omega_drift_2 = (self._robot._k_drift / self._robot._T) * abs(v) # drift noise omega_noisy = omega + random.normal(0.0, math.sqrt(sigma_omega_tr_2)) omega_noisy += random.normal(0.0, math.sqrt(sigma_omega_drift_2)) omega = omega_noisy v = v_noisy # translational and rotational speed is limited: if omega > self._robot._maxOmega: omega = self._robot._maxOmega if omega < -self._robot._maxOmega: omega = -self._robot._maxOmega if v > self._robot._maxSpeed: v = self._robot._maxSpeed if v < -self._robot._maxSpeed: v = -self._robot._maxSpeed d = v * self._robot._T dTheta = omega * self._robot._T x = self._particles[i][self.X] y = self._particles[i][self.Y] theta = self._particles[i][self.THETA] x = (x + d * math.cos(theta + 0.5 * dTheta)) y = (y + d * math.sin(theta + 0.5 * dTheta)) theta = (theta + dTheta) % (2 * math.pi) if self.drawWayOfParticle: self.drawWayOfParticle(i, x, y) self._particles[i][self.X] = x + random.normal(0.0, noiseReposition) self._particles[i][self.Y] = y + random.normal(0.0, noiseReposition) self._particles[i][self.THETA] = theta self._particles[i][self.WEIGHT] = 0 self._particles[i][self.SUM] = 0
def radiusFunction(center_x, center_y, deadzone=0.0): """ :param center_x: x coordinate of center from which the radius is computed :param center_y: y coordinate of center from which the radius is computed :param deadzone: 0 to 1.0 real value considering the portion of the inner place (small radius values) as out of image space :return: new function computing radius from a given center point considering the close region as deadzone """ return lambda x, y: (1.0 + deadzone) * (math.sqrt((center_x - x) ** 2 + (center_y - y) ** 2) / max(center_x, center_y)) - deadzone
def get_sample(params): # function which constructs the sample radius = params["radius"] height = params["height"] height_flattening = (params["height"] / params["radius"]) * params["height_flattening_ratio"] lattice_length = params["lattice_length"] damping_length = params["damping_length"] disorder_parameter = params["disorder_parameter"] # Defining materials: m_air = ba.MaterialBySLD("Air", 0.0, 0.0) m_Cu = ba.MaterialBySLD("Cu", 6.9508e-05, 5.142e-06) m_PEO = ba.MaterialBySLD("PEO", 1.0463e-05, 7.9515e-09) #m_SiO2 = ba.MaterialBySLD("SiO2", 1.8749e-05, 9.3923e-08) #m_Si = ba.MaterialBySLD("Si", 1.9893e-05, 1.795e-07) # Defining particles: tr_spheroid_ff = ba.FormFactorTruncatedSpheroid(radius, height, height_flattening) particle = ba.Particle(m_Cu, tr_spheroid_ff) # Defining interference function: interference_f = ba.InterferenceFunctionRadialParaCrystal( lattice_length, damping_length) omega = disorder_parameter * lattice_length pdf = ba.FTDistribution1DGauss(omega) interference_f.setProbabilityDistribution(pdf) # Defining layers: layout = ba.ParticleLayout() layout.addParticle(particle, 1.0) layout.setInterferenceFunction(interference_f) layout.setTotalParticleSurfaceDensity( 2 / (math.sqrt(3) * lattice_length * lattice_length)) air_layer = ba.Layer(m_air) air_layer.setNumberOfSlices(15) air_layer.addLayout(layout) PEO_layer = ba.Layer(m_PEO) #PEO_layer = ba.Layer(m_PEO, 90*nm) #Si_layer = ba.Layer(m_Si) #roughness = ba.LayerRoughness() #roughness.setSigma(10.0*nm) #roughness.setHurstParameter(1.0) #roughness.setLatteralCorrLength(1.0e-5*nm) # Assembling the multilayer: multi_layer = ba.MultiLayer() multi_layer.addLayer(air_layer) multi_layer.addLayer(PEO_layer) #multi_layer.addLayerWithTopRoughness(PEO_layer, roughness) #multi_layer.addLayer(Si_layer) return multi_layer
def distance(n1, n2): """Calculate distance in km between two nodes""" lat1, lon1 = n1[0], n1[1] lat2, lon2 = n2[0], n2[1] delta_lat = lat2 - lat1 delta_lon = lon2 - lon1 d = math.sin(math.radians(delta_lat) * 0.5) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) \ * math.sin(math.radians(delta_lon) * 0.5) ** 2 return math.asin(math.sqrt(d)) * 12742
def innerProd(self, otherAtom): """ DEPRECATED returns the inner product between current atom and the other one This method should be as fast as possible""" waveform1 = self.getWaveform() waveform2 = otherAtom.getWaveform() startIdx = max(self.frame * self.length , otherAtom.frame * otherAtom.length) stopIdx = min((self.frame+1) * self.length , (otherAtom.frame+1) * otherAtom.length) if startIdx >= stopIdx: return 0; # disjoint support start1 = startIdx- self.frame * self.length start2 = startIdx- otherAtom.frame * otherAtom.length duration = stopIdx - startIdx norm1 = math.sqrt(sum(waveform1**2)) norm2 = math.sqrt(sum(waveform2**2)) return (self.mdct_value * otherAtom.mdct_value)* sum( waveform1[start1: start1+duration] * waveform2[start2: start2+duration]) / (norm1*norm2)
def SmoothBound_LSL(self,featurmatrix, myMDP, countXVec, rho, regCoef,beta,numTrajectories): normPhi=numpy.linalg.norm(featurmatrix) maxRho=numpy.linalg.norm(rho,Inf) c_lambda=normPhi*maxRho/(math.sqrt(2*regCoef)) #print('===============================================') #print(regCoef) l2Rho=numpy.linalg.norm(rho) phi_k=0 Vals=[] for k in range(0,numTrajectories): minVal=0 for s in range(len(myMDP.getStateSpace())-1): minVal=minVal+rho[s]*min(countXVec[s]+k,numTrajectories) phi_k=c_lambda*math.sqrt(minVal)+l2Rho Vals.append((math.pow(phi_k,2))*math.exp(-k*beta)) upperBound=max(Vals) #print('Smooth upper bound= '+str(upperBound)) return upperBound
def herrmann_data(X_, TF=True, cos=False, normalization=False): X = [] for x in X_: data = {"%s" % x: 0 for x in range(1, 1515)} for k in x: data["%s" % np.abs(k)] += 1 tmp_ = [] for x in range(1, 1515): tmp_.append(data["%s" % x]) X.append(tmp_) if normalization == True: X_t = [] for x in X: x_T = [] for x_ in x: x_tmp = (x_ * 1.0) / sum(x) x_T.append(x_tmp) X_t.append(x_T) X = X_t if TF is True: X_t = [] for x in X: x_tmp_ = [] for k in x: x_tmp_.append(math.log(1.0 + k, math.e)) X_t.append(x_tmp_) X = X_t return X if cos is True: instances = X big_X = [] for k, instance in enumerate(instances): X_T = [] for x in instance: # Apply TF Transformation t_tmp = math.log(1.0 + x, 2) X_T.append(t_tmp) # Store Euclidean Length for Cosine Normalisation (Section 4.5.2) euclideanLength = 0 for attribute in X_T: euclideanLength += 1.0 * attribute * attribute euclideanLength = math.sqrt(euclideanLength) X_T2 = [] for attribute in X_T: # Apply Cosine Normalisation t_tmp = 1.0 * attribute / euclideanLength X_T2.append(t_tmp) big_X.append(X_T2) X = big_X return X
def factor(number): factors = [] for i in range(1, int(math.sqrt(number))+1): if number % i == 0: factors.append(i) factors.append(number / i) return factors
def sense(self): sensorDistNoisy = [] sensorDist = self._world.sense() for d in sensorDist: if d is not None: # print "d: ", d sigma2 = self._sensorNoise ** 2 * d d += random.gauss(0.0, math.sqrt(sigma2)) sensorDistNoisy.append(d) return sensorDistNoisy
def calc_volume_trilinic(a, b, c, alpha, beta, gamma): alpha = math.pi * alpha / 180.0 beta = math.pi * beta / 180.0 gamma = math.pi * gamma / 180.0 ca = math.cos(alpha) cb = math.cos(beta) cg = math.cos(gamma) vol = a * b * c * math.sqrt(1.0 + 2 * ca * cb * cg - ca**2 - cb**2 - cg**2) return vol
def draw_line(self, pos): if self.viewer._ocr and self.x_clicked or self.y_clicked: img_line = cv.line(self.image.copy(), (self.x_clicked, self.y_clicked), (pos.x(), pos.y()), (0, 0, 0), 2) image_height, image_width, image_depth = img_line.shape QIm = cv.cvtColor(img_line, cv.COLOR_BGR2RGB) QIm = QImage(QIm.data, image_width, image_height, image_width * image_depth, QImage.Format_RGB888) self.viewer.setPhoto(QPixmap.fromImage(QIm)) # 终止画线 if self.x_released or self.y_released: self.choosePoints = [] # 初始化存储点组 inf = float("inf") if self.x_released or self.y_released: if (self.x_released - self.x_clicked) == 0: slope = inf else: slope = (self.y_released - self.y_clicked) / ( self.x_released - self.x_clicked) siteLenth = 0.5 * math.sqrt( square(self.y_released - self.y_clicked) + square(self.x_released - self.x_clicked)) mySiteLenth = 2 * siteLenth self.siteLenth = ("%.2f" % mySiteLenth) self.editSiteLenth.setText(self.siteLenth) radian = math.atan(slope) self.siteSlope = ("%.2f" % radian) self.editSiteSlope.setText(self.siteSlope) x_bas = math.ceil(math.fabs(0.5 * siteLenth * math.sin(radian))) y_bas = math.ceil(math.fabs(0.5 * siteLenth * math.cos(radian))) if slope <= 0: self.choosePoints.append([(self.x_clicked - x_bas), (self.y_clicked - y_bas)]) self.choosePoints.append([(self.x_clicked + x_bas), (self.y_clicked + y_bas)]) self.choosePoints.append([(self.x_released + x_bas), (self.y_released + y_bas)]) self.choosePoints.append([(self.x_released - x_bas), (self.y_released - y_bas)]) elif slope > 0: self.choosePoints.append([(self.x_clicked + x_bas), (self.y_clicked - y_bas)]) self.choosePoints.append([(self.x_clicked - x_bas), (self.y_clicked + y_bas)]) self.choosePoints.append([(self.x_released - x_bas), (self.y_released + y_bas)]) self.choosePoints.append([(self.x_released + x_bas), (self.y_released - y_bas)]) self.viewer._ocr = False
def forward(self, src): if self.src_mask is None or self.src_mask.size(0) != len(src): device = src.device mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask src = self.encoder(src) * math.sqrt(self.ninp) src = self.pos_encoder(src) output = self.transformer_encoder(src, self.src_mask) output = self.decoder(output) return output
def straightDriveTruePose(robot, v, l): if v == 0: return truePoseBefore = robot.getRobotPose() trueL = 0 while trueL < (l - v * robot._T): robot.move([v, 0]) truePoseAfter = robot.getRobotPose() trueL = math.sqrt((truePoseAfter[0] - truePoseBefore[0]) ** 2 + (truePoseAfter[1] - truePoseBefore[1]) ** 2) v = (l - trueL) / robot._T robot.move([v, 0])
def GS_based_DPLSL (self, FirstVisitVector, countXVec, myMDP, featuresMatrix, gamma, epsilon, delta, regCoef, numTrajectories, rho, pi="uniform"): dim=len(featuresMatrix.T) Rho=numpy.reshape(rho,(len(rho),1)) thetaTil_X= self.LSL(FirstVisitVector, myMDP, featuresMatrix, regCoef, numTrajectories,countXVec) normPhi=numpy.linalg.norm(featuresMatrix) maxRho=numpy.linalg.norm(Rho,Inf) l2Rho=numpy.linalg.norm(Rho) alpha=(5.0*numpy.sqrt(2*numpy.math.log(2.0/delta)))/epsilon sigma_X=float(2*alpha*myMDP.getMaxReward()*normPhi/((1-myMDP.getGamma())*(regCoef-maxRho*numpy.math.pow(normPhi, 2)))) varphi_lamda=normPhi*maxRho*math.sqrt(numTrajectories)/(math.sqrt(2*regCoef))+l2Rho sigma_X=sigma_X*varphi_lamda cov_X=math.pow(sigma_X,2)*numpy.identity(dim) mean=numpy.zeros(dim) ethaX=numpy.random.multivariate_normal(mean,cov_X) #thetaTil_X=numpy.squeeze(numpy.asarray(thetaTil_X)) #ethaX=numpy.squeeze(numpy.asarray(ethaX)) thetaTil_X_priv=thetaTil_X+numpy.reshape(ethaX, (dim,1)) return [thetaTil_X_priv, thetaTil_X,math.pow(sigma_X,2)]
def fixedPositon(img): corners = findCorners(img) center = (sum(c[0] for c in corners) / 4, sum(c[1] for c in corners) / 4) p1 = np.float32((corners[0][0] + corners[3][0], corners[0][1] + corners[3][1])) p2 = np.float32((corners[1][0] + corners[2][0], corners[1][1] + corners[2][1])) p3 = np.float32((corners[0][0] + corners[1][0], corners[0][1] + corners[1][1])) p4 = np.float32((corners[2][0] + corners[3][0], corners[2][1] + corners[3][1])) width = math.sqrt((p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1])) / 2 height = math.sqrt((p3[0] - p4[0]) * (p3[0] - p4[0]) + (p3[1] - p4[1]) * (p3[1] - p4[1])) / 2 # print corners # print signetCenter cv2.polylines(img, [np.array(corners, np.int32)], True, (0, 0, 0)) wRate = width / 1195 # (560, 1196) hRate = height / 560 # (560, 1196) h, w = img.shape[:2] M = ((corners[1][1] + corners[2][1]) - (corners[0][1] + corners[3][1])) / ((corners[1][0] + corners[2][0]) - (corners[0][0] + corners[3][0])) pi_angle = math.atan(M) ang = pi_angle * 180 / np.pi return center, wRate, hRate, ang raise Exception(_("无法定位发票"))
def Norm_z(p): a0,a1,a2,a3 = 2.5066282, -18.6150006, 41.3911977, -25.4410605 b1,b2,b3,b4 = -8.4735109, 23.0833674, -21.0622410, 3.1308291 c0,c1,c2,c3 = -2.7871893, -2.2979648, 4.8501413, 2.3212128 d1,d2,r,z = 3.5438892, 1.6370678, None, None if (p>0.42): r=math.sqrt(-math.log(0.5-p)); z=(((c3*r+c2)*r+c1)*r+c0)/((d2*r+d1)*r+1) else: r=p*p z=p*(((a3*r+a2)*r+a1)*r+a0)/((((b4*r+b3)*r+b2)*r+b1)*r+1) return z
def senseLandmarks(self, landmarks): angles = [] distances = [] (posX, posY, _) = self._world.getTrueRobotPose() for (landX, landY) in landmarks: distance = math.sqrt((landX - posX) ** 2 + (landY - posY) ** 2) distance += random.gauss(0, self._sensorNoise) angle = math.atan2(posY - landY, posX - landX) # angle += random.gauss(0, self._sensorNoise) angles.append(angle) distances.append(distance) return (distances, angles)
def FindBusinessBasedOnLocation(categoriesToSearch, myLocation, maxDistance, saveLocation2, collection): temp = [] for i in categoriesToSearch: temp.append(i.title()); abc = collection.find({"categories": {"$all": temp}}) latit = float (myLocation[0]) longi = float (myLocation[1]) source_lat = radians(latit) source_long = radians(longi) R=3959 file=open(saveLocation2,"w") for i in abc: dest_lat = radians(i['latitude']) dest_long = radians(i['longitude']) dist_lat = (dest_lat - source_lat) dist_long = (dest_long - source_long) a = math.sin(dist_lat / 2) * math.sin(dist_lat / 2) + math.cos(source_lat) * math.cos(dest_lat) * math.sin(dist_long / 2) * math.sin(dist_long / 2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) distance = R * c if (distance <= maxDistance): file.write(i['name'].encode("utf-8").upper() + "\n") file.close()
def gotoTurnFirst(robot, v, p, tol): # get the actual position of robot [x, y, theta] = robot.getRobotPose(); # calculate the distance between robot and target point distance = math.sqrt(((x - p.getX()) ** 2) + ((y - p.getY()) ** 2)) delta_theta = GeometryHelper.diffDegree(math.atan2(p.getY() - y, p.getX() - x), theta) # point not reached? if(distance > tol): # drive missing distance robot.curveDriveTruePose(0.5, 0, delta_theta) robot.straightDriveTruePose(v, distance); # call goto again. robot.goto(v, p, tol)
def gotoWithObstacleAvoidance(self, v, p, tol, sensorsToUse=9, distanceTol=1, minSpeed=0.2): while True: [x, y, theta] = self.getRobotPose(); distance = math.sqrt(((x - p.getX()) ** 2) + ((y - p.getY()) ** 2)) delta_theta = GeometryHelper.diffDegree(math.atan2(p.getY() - y, p.getX() - x), theta) if (distance < tol): return True if self.isObstacleInWay(sensorsToUse, distanceTol): return False if not self.move([ v * max(minSpeed, (1 - abs(delta_theta * 5) / math.pi) * min(1, distance)), delta_theta]): for _ in range(1, 5): self.move([-1, 0])
def getCentral(xyzA, xyzB, xyzC): Radius = 6371000 central = blh = zeros(3) central[0] = (xyzA[0] + xyzB[0] + xyzC[0]) / 3.0 central[1] = (xyzA[1] + xyzB[1] + xyzC[1]) / 3.0 central[2] = (xyzA[2] + xyzB[2] + xyzC[2]) / 3.0 tlen = math.sqrt(central[0] * central[0] + central[1] * central[1] + central[2] * central[2]) central[0] = central[0] / tlen * Radius central[1] = central[1] / tlen * Radius central[2] = central[2] / tlen * Radius return central
def update_creature_properties(self, creature: Creature, creature_actions: CreatureActions) -> None: """ Updates the creature properties according to its actions. """ # The more the creature moves, the higher its fitness. distance = math.sqrt(math.pow(creature_actions.x, 2) + math.pow(creature_actions.y, 2)) creature.fitness += distance creature.distance_travelled += distance creature.age += 1 if int(creature.distance_travelled) % 30 == 0: creature.age -= 5 if creature.age >= MAX_AGE: self.dead_creatures.append(creature)
def calculate_s_score(linePoints): regression = line_regress(linePoints) xVctr, yVctr = _pointsToVectors(linePoints) MSE = _MSE(regression["slope"], regression["intercept"], linePoints) xMean = mean(xVctr) xMeanDiffArray = [] for x in xVctr: xDiff = x - xMean xDiffSq = xDiff * xDiff xMeanDiffArray.append(xDiffSq) xDiffSum = sum(xMeanDiffArray) sSqVal = old_div(MSE, xDiffSum) sVal = math.sqrt(sSqVal) return sVal
def CohenEffectSize(group1, group2): """ Determine Effect size Cohen's d statistic : compare the difference between groups to the variability within groups """ diff = group1.var() var1 = group1.var() var2 = group2.var() n1, n2 = len(group1), len(group2) pooled_var = (n1 * var1 + n2 * var2) / (n1 + n2) d = diff / math.sqrt(pooled_var) return d
def myQE( fileout, # Given image for comparision filein, # output image of my canny algorithm s, # standard deviation size, # kernel size Th, # high threshold Tl, # low threshold noise # with/without noise? ): J = array(Image.open(fileout).convert('L')) if (noise == 0): I = p1(s, size, filein, Th, Tl, 0, 1) # calling my canny algorithm from problem 1 elif (noise == 1): # decides if noise is required to be added or not I = p1(s, size, filein, Th, Tl, 1, 1) # calling my canny algorithm from problem 1 tp, tn, fp, fn = (0.0, 0.0, 0.0, 0.0 ) # initializing the true/false positives/negatives e = 1.6 for i in range(len(I[:, 0])): for j in range(len(I[0, :])): if ((I[i, j] > 0) & (J[i, j] > 0)): # implementing true positive tp += 1 elif ( (I[i, j] == 0) & (J[i, j] == 0)): # implementing true negetive tn += 1 elif ( (I[i, j] > 0) & (J[i, j] == 0)): # implementing false positive fp += 1 elif ( (I[i, j] == 0) & (J[i, j] > 0)): # implementing false negetive fn += 1 sen = tp / (tp + fn) # Sensitivity spe = tn / (tn + fp) # Specificity pr = tp / (tp + fp) # Precision npv = tn / (tn + fn) # Negative Predictive Value fot = fp / (fp + tn) # Fall Out fnr = fn / (fn + tp) # False Negative Rate FNR fdr = fp / (fp + tp) # False Discovery Rate FDR acc = (tp + tn) / (tp + fn + tn + fp) # Accuracy fsc = (2 * tp) / ((2 * tp) + fp + fn) # F-score mcc = ((tp * tn) - (fp * fn)) / math.sqrt( (tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) # Matthew’s Correlation Coefficient print "Finished quantitative evaluation of edge detection\nSensitivity = %f\nSpecificity = %f\nPrecision = %f\nNegative Predictive Value = %f\nFall-out = %f\nFalse Negative Rate = %f\nFalse Discovery Rate = %f\nAccuracy = %f\nF-score = %f\nMatthew’s Correlation Coefficient = %f\n" % ( sen, spe, pr * e, npv, fot, fnr, fdr, acc, fsc, mcc)
def __init__(self, filename=None, verbose=False, **kwargs): self.file_name = filename try: with rasterio.drivers(): with rasterio.open(self.file_name, 'r') as ds: self.affine = ds.meta['affine'] self.ncol = ds.meta['width'] self.nrow = ds.meta['height'] self.geo_transform = ds.meta['transform'] self.no_data_value = ds.meta['nodata'] self.crs = ds.crs self.crs_wkt = ds.crs_wkt self.meta = ds.meta if verbose is True: print(ds.crs) print(ds.crs_wkt) print("Metadata:{}".format(self.img.meta)) except: raise Exception("Error opening file with Rasterio") sys.exit(1) # todo: is this necessary? spheroid_start = self.crs_wkt.find("SPHEROID[") + len("SPHEROID") spheroid_end = self.crs_wkt.find("AUTHORITY", spheroid_start) self.spheroid = str(self.crs_wkt)[spheroid_start:spheroid_end].strip('[]').split(',') # todo: perhaps these ought to be properties, calculated lazily w/ most recent spheroid/geotransform self.semimajor = float(self.spheroid[1]) self.inverse_flattening = float(self.spheroid[2]) self.flattening = float(1 / self.inverse_flattening) self.semiminor = float(self.semimajor * (1 - self.flattening)) self.eccentricity = math.sqrt(2 * self.flattening - self.flattening * self.flattening) self.rotation = self.geo_transform[2] # rotation, 0 if image is 'north-up' self.originX = self.geo_transform[0] # top-left x self.originY = self.geo_transform[3] # top-left y self.pixelWidth = self.geo_transform[1] # w/e pixel resoluton self.pixelHeight = self.geo_transform[5] # n/s pixel resolution self.graph = Graph() # Graph object used for planning and controller logic. # Each vehicle will probably alo need to carry arodun an instance of Graph or Path # to keep track of it's path self.__units = 'degrees' self.__x = 'lon' self.__y = 'lat' self.__name = 'Coord'
def DPLSW(self, FirstVisitVector, countXVec, myMDP, featuresMatrix, gamma, epsilon, delta,batchSize, initStateDist="uniform", pi="uniform"): dim = len(featuresMatrix.T) alpha = (5.0*numpy.sqrt(2*numpy.math.log(2.0/delta)))/epsilon beta = (epsilon/4)/(dim+numpy.math.log(2.0/delta)) Gamma_w = myMDP.getGammaMatrix() # for i in range(len(countXVec)): # Gamma_w[i][i] = Gamma_w[i][i]*countXVec[i]/batchSize GammaSqrt = Gamma_w for i in range(len(GammaSqrt)): GammaSqrt[i][i] = math.sqrt(Gamma_w[i][i]) GammaSqrt = GammaSqrt * numpy.mat(featuresMatrix) if self.is_invertible(GammaSqrt): GammaSqrtPhiInv = linalg.inv(GammaSqrt) else: GammaSqrtPhiInv = linalg.pinv(GammaSqrt) GammaTemp = numpy.mat(featuresMatrix).T * Gamma_w * numpy.mat(featuresMatrix) #GammaSqrtPhi = numpy.mat(GammaSqrt) * numpy.mat(featuresMatrix) if self.is_invertible(GammaTemp): GammaTempPhiInv = linalg.inv(GammaTemp) else: GammaTempPhiInv = linalg.pinv(GammaTemp) FirstVisitVector = numpy.reshape(FirstVisitVector, (len(FirstVisitVector), 1)) thetaTild = GammaTempPhiInv * numpy.mat(featuresMatrix.T) thetaTild = thetaTild * numpy.mat(Gamma_w) * numpy.mat(FirstVisitVector) PsiBetaX = self.SmootBound_LSW(myMDP, Gamma_w, countXVec, beta, myMDP.startStateDistribution()) sigmmaX = (alpha*myMDP.getMaxReward())/(1-self.gamma_factor) sigmmaX = sigmmaX*numpy.linalg.norm(GammaSqrtPhiInv,2) sigmmaX = sigmmaX*math.pow(PsiBetaX, 0.5) cov_X = math.pow(sigmmaX,2)*numpy.identity(dim) mean = numpy.zeros(dim) ethaX = numpy.random.multivariate_normal(mean, cov_X) thetaTild = numpy.squeeze(numpy.asarray(thetaTild)) ethaX = numpy.squeeze(numpy.asarray(ethaX)) thetaTild_priv = thetaTild + ethaX return [thetaTild_priv, thetaTild, math.pow(sigmmaX,2)]
def XYZ2BL(x, y, z): blh = zeros(2) t = math.sqrt(x * x + y * y) eps = 1.0E-10 if math.fabs(t) < eps: if z > 0: blh[0] = 90.0 blh[1] = 0.0 elif z < 0: blh[0] = -90 blh[1] = 0.0 else: blh[0] = math.atan(z / t) * 180.0 / math.pi # -90 to 90 # 0-360 blh[1] = math.atan2(y, x) * 180.0 / math.pi if blh[1] < 0.0: blh[1] = blh[1] + 360.0 return blh
def __init__(self, filename, verbose=False): """ :param filename: path to the raster file to be opened :param verbose: indicate whether we would like to print out certain metrics regarding the file opened """ self.file = filename try: self.img = rasterio.open(self.file) except RuntimeError as e: print('Unable to open {}'.format(str(self.file))) print(e) sys.exit(1) self.crs_wkt = self.img.crs_wkt spheroid_start = self.crs_wkt.find("SPHEROID[") + len("SPHEROID") spheroid_end = self.crs_wkt.find("AUTHORITY", spheroid_start) self.spheroid = str(self.crs_wkt)[spheroid_start:spheroid_end] self.spheroid = self.spheroid.strip('[]').split(',') self.semimajor = float(self.spheroid[1]) self.inverse_flattening = float(self.spheroid[2]) self.flattening = float(1 / self.inverse_flattening) self.semiminor = float(self.semimajor * (1 - self.flattening)) self.eccentricity = math.sqrt(2 * self.flattening - self.flattening * self.flattening) self.geotransform = self.img.meta['transform'] self.nodatavalue, self.data = None, None self.nodatavalue = self.img.meta['nodata'] self.ncol = self.img.meta['width'] self.nrow = self.img.meta['height'] self.rotation = self.geotransform[2] # rotation, 0 if image is 'north-up' self.originX = self.geotransform[0] # top-left x self.originY = self.geotransform[3] # top-left y self.pixelWidth = self.geotransform[1] # w/e pixel resoluton self.pixelHeight = self.geotransform[5] # n/s pixel resolution if verbose is True: print("GeoT:{}".format(self.geotransform)) print("Metadata:{}".format(self.img.meta))
def getPrivateKey(publicKey): # Second nummer in the given public key n = publicKey[1] e = publicKey[0] # Generate primes primes = PrimeGen(math.sqrt(n)) p = 0 q = 0 for i in primes: for k in primes: if (i * k == n): p = i q = k # Phi is the totient of n phi = (p - 1) * (q - 1) # Use Extended Euclid's Algorithm to generate the private key d = multiplicative_inverse(e, phi) # Return public and private keypair # Public key is (e, n) and private key is (d, n) return ((e, n), (d, n))
def LSW_subSampleAggregate(self, batch, s, numberOfsubSamples,myMDP,featuresMatrix,numTrajectories,FirstVisitVector,epsilon,delta,distUB): dim=len(featuresMatrix.T) alpha=(5.0*numpy.sqrt(2*numpy.math.log(2.0/delta)))/epsilon beta= (epsilon/4)*(dim+numpy.math.log(2.0/delta)) subSamples=self.subSampleGen(batch, numberOfsubSamples) z=numpy.zeros((len(subSamples),len(featuresMatrix))) for i in range(len(subSamples)): FVMC=self.FVMCPE(myMDP, featuresMatrix, subSamples[i]) z[i]= ravel(numpy.mat(featuresMatrix)*numpy.mat(FVMC[0]))#this is LSW partitionPoint=int((numberOfsubSamples+math.sqrt(numberOfsubSamples))/2)+1 #g= self.generalized_median(myMDP,z,partitionPoint,distUB) g=self.geometric_median(z) #g= self.aggregate_median(myMDP,z) #To check the following block S_z=self.computeAggregateSmoothBound(z, beta, s,myMDP,distUB) cov_X=(S_z/alpha)*numpy.identity(len(featuresMatrix)) ethaX=numpy.random.multivariate_normal(numpy.zeros(len(featuresMatrix)),cov_X) #print(S_z) #noise=(S_z/alpha)*ethaX #return [g[1]+ethaX,g[1]] return [g+ethaX,g]
def pyt(self, a, b): return math.sqrt(a * a + b * b)
def f(x): f = (math.exp(-x*x/2))/math.sqrt(2.0*math.pi) return f
def getLineData(pixels, x1, y1, x2, y2, lineW=2, theZ=0, theC=0, theT=0): """ Grabs pixel data covering the specified line, and rotates it horizontally so that x1,y1 is to the left, Returning a numpy 2d array. Used by Kymograph.py script. Uses PIL to handle rotating and interpolating the data. Converts to numpy to PIL and back (may change dtype.) @param pixels: PixelsWrapper object @param x1, y1, x2, y2: Coordinates of line @param lineW: Width of the line we want @param theZ: Z index within pixels @param theC: Channel index @param theT: Time index """ from numpy import asarray sizeX = pixels.getSizeX() sizeY = pixels.getSizeY() lineX = x2-x1 lineY = 1 if y2-y1 == 0 else y2-y1 rads = math.atan(float(lineX) / lineY) # How much extra Height do we need, top and bottom? extraH = abs(math.sin(rads) * lineW) bottom = int(max(y1, y2) + extraH/2) top = int(min(y1, y2) - extraH/2) # How much extra width do we need, left and right? extraW = abs(math.cos(rads) * lineW) left = int(min(x1, x2) - extraW) right = int(max(x1, x2) + extraW) # What's the larger area we need? - Are we outside the image? pad_left, pad_right, pad_top, pad_bottom = 0, 0, 0, 0 if left < 0: pad_left = abs(left) left = 0 x = left if top < 0: pad_top = abs(top) top = 0 y = top if right > sizeX: pad_right = right - sizeX right = sizeX w = int(right - left) if bottom > sizeY: pad_bottom = bottom - sizeY bottom = sizeY h = int(bottom - top) tile = (x, y, w, h) # get the Tile plane = pixels.getTile(theZ, theC, theT, tile) # pad if we wanted a bigger region if pad_left > 0: data_h, data_w = plane.shape pad_data = zeros((data_h, pad_left), dtype=plane.dtype) plane = hstack((pad_data, plane)) if pad_right > 0: data_h, data_w = plane.shape pad_data = zeros((data_h, pad_right), dtype=plane.dtype) plane = hstack((plane, pad_data)) if pad_top > 0: data_h, data_w = plane.shape pad_data = zeros((pad_top, data_w), dtype=plane.dtype) plane = vstack((pad_data, plane)) if pad_bottom > 0: data_h, data_w = plane.shape pad_data = zeros((pad_bottom, data_w), dtype=plane.dtype) plane = vstack((plane, pad_data)) pil = numpyToImage(plane) # pil.show() # Now need to rotate so that x1,y1 is horizontally to the left of x2,y2 toRotate = 90 - math.degrees(rads) if x1 > x2: toRotate += 180 # filter=Image.BICUBIC see # http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2172449/ rotated = pil.rotate(toRotate, expand=True) # rotated.show() # finally we need to crop to the length of the line length = int(math.sqrt(math.pow(lineX, 2) + math.pow(lineY, 2))) rotW, rotH = rotated.size cropX = (rotW - length)/2 cropX2 = cropX + length cropY = (rotH - lineW)/2 cropY2 = cropY + lineW cropped = rotated.crop((cropX, cropY, cropX2, cropY2)) # cropped.show() return asarray(cropped)
def _calculate_euclides_distance(self, traning_element, test_element, feature_first, feature_second): return math.sqrt((traning_element[feature_first] - test_element[feature_second])**2 + (traning_element[feature_first] - test_element[feature_second])**2)
def get_line_data(pixels, x1, y1, x2, y2, line_w=2, the_z=0, the_c=0, the_t=0): """ Grabs pixel data covering the specified line, and rotates it horizontally so that x1,y1 is to the left, Returning a numpy 2d array. Used by Kymograph.py script. Uses PIL to handle rotating and interpolating the data. Converts to numpy to PIL and back (may change dtype.) @param pixels: PixelsWrapper object @param x1, y1, x2, y2: Coordinates of line @param line_w: Width of the line we want @param the_z: Z index within pixels @param the_c: Channel index @param the_t: Time index """ size_x = pixels.getSizeX() size_y = pixels.getSizeY() line_x = x2 - x1 line_y = y2 - y1 rads = math.atan(float(line_x) / line_y) # How much extra Height do we need, top and bottom? extra_h = abs(math.sin(rads) * line_w) bottom = int(max(y1, y2) + extra_h / 2) top = int(min(y1, y2) - extra_h / 2) # How much extra width do we need, left and right? extra_w = abs(math.cos(rads) * line_w) left = int(min(x1, x2) - extra_w) right = int(max(x1, x2) + extra_w) # What's the larger area we need? - Are we outside the image? pad_left, pad_right, pad_top, pad_bottom = 0, 0, 0, 0 if left < 0: pad_left = abs(left) left = 0 x = left if top < 0: pad_top = abs(top) top = 0 y = top if right > size_x: pad_right = right - size_x right = size_x w = int(right - left) if bottom > size_y: pad_bottom = bottom - size_y bottom = size_y h = int(bottom - top) tile = (x, y, w, h) # get the Tile plane = pixels.getTile(the_z, the_c, the_t, tile) # pad if we wanted a bigger region if pad_left > 0: data_h, data_w = plane.shape pad_data = zeros((data_h, pad_left), dtype=plane.dtype) plane = hstack((pad_data, plane)) if pad_right > 0: data_h, data_w = plane.shape pad_data = zeros((data_h, pad_right), dtype=plane.dtype) plane = hstack((plane, pad_data)) if pad_top > 0: data_h, data_w = plane.shape pad_data = zeros((pad_top, data_w), dtype=plane.dtype) plane = vstack((pad_data, plane)) if pad_bottom > 0: data_h, data_w = plane.shape pad_data = zeros((pad_bottom, data_w), dtype=plane.dtype) plane = vstack((plane, pad_data)) pil = script_utils.numpy_to_image(plane, (plane.min(), plane.max()), int32) # Now need to rotate so that x1,y1 is horizontally to the left of x2,y2 to_rotate = 90 - math.degrees(rads) if x1 > x2: to_rotate += 180 # filter=Image.BICUBIC see # http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2172449/ rotated = pil.rotate(to_rotate, expand=True) # rotated.show() # finally we need to crop to the length of the line length = int(math.sqrt(math.pow(line_x, 2) + math.pow(line_y, 2))) rot_w, rot_h = rotated.size crop_x = (rot_w - length) / 2 crop_x2 = crop_x + length crop_y = (rot_h - line_w) / 2 crop_y2 = crop_y + line_w cropped = rotated.crop((crop_x, crop_y, crop_x2, crop_y2)) return asarray(cropped)
def get_line_data(image, x1, y1, x2, y2, line_w=2, the_z=0, the_c=0, the_t=0): """ Grab pixel data covering the specified line, and rotates it horizontally. Uses current rendering settings and returns 8-bit data. Rotates it so that x1,y1 is to the left, Returning a numpy 2d array. Used by Kymograph.py script. Uses PIL to handle rotating and interpolating the data. Converts to numpy to PIL and back (may change dtype.) @param pixels: PixelsWrapper object @param x1, y1, x2, y2: Coordinates of line @param line_w: Width of the line we want @param the_z: Z index within pixels @param the_c: Channel index @param the_t: Time index """ size_x = image.getSizeX() size_y = image.getSizeY() line_x = x2 - x1 line_y = y2 - y1 rads = math.atan2(line_y, line_x) # How much extra Height do we need, top and bottom? extra_h = abs(math.sin(rads) * line_w) bottom = int(max(y1, y2) + extra_h / 2) top = int(min(y1, y2) - extra_h / 2) # How much extra width do we need, left and right? extra_w = abs(math.cos(rads) * line_w) left = int(min(x1, x2) - extra_w) right = int(max(x1, x2) + extra_w) # What's the larger area we need? - Are we outside the image? pad_left, pad_right, pad_top, pad_bottom = 0, 0, 0, 0 if left < 0: pad_left = abs(left) left = 0 x = left if top < 0: pad_top = abs(top) top = 0 y = top if right > size_x: pad_right = right - size_x right = size_x w = int(right - left) if bottom > size_y: pad_bottom = bottom - size_y bottom = size_y h = int(bottom - top) # get the Tile - render single channel white image.set_active_channels([the_c + 1], None, ['FFFFFF']) jpeg_data = image.renderJpegRegion(the_z, the_t, x, y, w, h) pil = Image.open(StringIO(jpeg_data)) # pad if we wanted a bigger region if pad_left > 0 or pad_right > 0 or pad_top > 0 or pad_bottom > 0: img_w, img_h = pil.size new_w = img_w + pad_left + pad_right new_h = img_h + pad_top + pad_bottom canvas = Image.new('RGB', (new_w, new_h), '#ff0000') canvas.paste(pil, (pad_left, pad_top)) pil = canvas # Now need to rotate so that x1,y1 is horizontally to the left of x2,y2 to_rotate = math.degrees(rads) # filter=Image.BICUBIC see # http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2172449/ rotated = pil.rotate(to_rotate, expand=True) # finally we need to crop to the length of the line length = int(math.sqrt(math.pow(line_x, 2) + math.pow(line_y, 2))) rot_w, rot_h = rotated.size crop_x = (rot_w - length) / 2 crop_x2 = crop_x + length crop_y = (rot_h - line_w) / 2 crop_y2 = crop_y + line_w cropped = rotated.crop((crop_x, crop_y, crop_x2, crop_y2)) # return numpy array rgb_plane = asarray(cropped) # greyscale image. r, g, b all same. Just use first return rgb_plane[::, ::, 0]
def normalize(self, vec): a = vec[0] b = vec[1] mag = math.sqrt(a * a + b * b) return vec / mag
# This just quickly does some calculations for the prices of masks for MMIRS from numpy import math price_file = "mask_costs" f = open(price_file) prices = [] for line in f.readlines(): if line[0] != "#": prices.append(float(line.strip(""))) N = len(prices) mean = sum(prices) / N variance = 1.0 / (N - 1) * sum([(price - mean) ** 2 for price in prices]) std_dev = math.sqrt(variance) print("%s +/- %s" % (mean, std_dev))