def get_alpha(radius, dec): if abs(dec) + radius > 89.9: return 180 return math.degrees( abs( math.atan( math.sin(math.radians(radius)) / np.sqrt( abs( math.cos(math.radians(dec - radius)) * math.cos(math.radians(dec + radius)))))))
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 _get_alpha(self): if abs(self.dec) + self.radius > 89.9: return 180 return math.degrees( abs( math.atan( math.sin(math.radians(self.radius)) / np.sqrt( abs( math.cos(math.radians(self.dec - self.radius)) * math.cos(math.radians(self.dec + self.radius)))))))
def distance_on_unit_sphere(self, coord1, coord2, lat_lon=None): # todo: need to make this work with ellipsoid earth models for more accurate distance calculations # todo: """ Calculate the distance on a spherical earth model with radius hard-coded. :param coord1: start coordinates :param coord2: end coordinates :param lat_lon: Optional: give either 'lat' or 'lon' to get just the lateral or longitudinal distances by themselves :return: return the distance in km """ if lat_lon is not None: if lat_lon is 'lat': lat1, lon1 = coord1.lat, coord1.lon lat2, lon2 = coord1.lat, coord2.lon elif lat_lon is 'lon': lat1, lon1 = coord1.lat, coord1.lon lat2, lon2 = coord2.lat, coord1.lon else: raise Exception("lat or lon not specified") else: lat1, lon1 = coord1.lat, coord1.lon lat2, lon2 = coord2.lat, coord2.lon # Convert latitude and longitude to # spherical coordinates in radians degrees_to_radians = math.pi / 180.0 # phi = 90 - latitude phi1 = (90.0 - lat1) * degrees_to_radians phi2 = (90.0 - lat2) * degrees_to_radians # theta = longitude theta1 = lon1 * degrees_to_radians theta2 = lon2 * degrees_to_radians # Compute spherical distance from spherical coordinates. # For two locations in spherical coordinates # (1, theta, phi) and (1, theta', phi') # cosine( arc length ) = # sin phi sin phi' cos(theta-theta') + cos phi cos phi' # distance = rho * arc length cos = (math.sin(phi1) * math.sin(phi2) * math.cos(theta1 - theta2) + math.cos(phi1) * math.cos(phi2)) """ @todo: need to implement domain check""" arc = math.acos(cos) return arc * self.semimajor # scale to return in km
def affine_registration(source, target, pyramidDepth, minLevel=0, downscale=2, debug=False): ''' Find affine transformation that registers source image to the target image. This function computes the image pyramid for source and target and calculates the transformation that minimizes the least-square error between images (starting at the lowest resolution). Args: source (np.ndarray): source image, the one that will be transformed. target (np.ndarray): target image, the one that will not move. pyramidDepth (int): number of pyramid levels, in addition to the original. minLevel (int): 0 for original level, >0 for coarser resolution. Return: tfrm (np.ndarray): (3,3) best transformation ''' sourcePyramid = tuple( skimage.transform.pyramid_gaussian(source, max_layer=pyramidDepth, downscale=downscale)) targetPyramid = tuple( skimage.transform.pyramid_gaussian(target, max_layer=pyramidDepth, downscale=downscale)) # -- compute small scale rigid body transformation to provide the initial guess for the affine transformation -- rtfrm = imreg.rigid_body_registration(sourcePyramid[minLevel], targetPyramid[minLevel], pyramidDepth - minLevel) rotmatrix = np.array([[math.cos(rtfrm[0]), -math.sin(rtfrm[0])], [math.sin(rtfrm[0]), math.cos(rtfrm[0])]]) tfrm = np.append(rotmatrix, [[rtfrm[1]], [rtfrm[2]]], 1) tfrm[:, -1] /= pow(downscale, pyramidDepth - minLevel) tfrm = np.vstack((tfrm, [0, 0, 1])) #tfrm = np.array([[1,0,0],[0,1,0],[0,0,1]]) for layer in range(pyramidDepth, minLevel - 1, -1): tfrm[:2, -1] *= downscale # Scale translation for next level in pyramid tfrm = affine_least_squares(sourcePyramid[layer], targetPyramid[layer], tfrm, 10 * 2**(layer - 1)) toptfrm = np.concatenate( (tfrm[:2, 0:2], tfrm[:2, -1:] * pow(downscale, layer)), axis=1) toptfrm = np.vstack((toptfrm, np.array([0, 0, 1]))) if debug: pass #some debugging stuff Santiago was using #print 'Layer {0}: {1}x{2}'.format(layer, *targetPyramid[layer].shape) #print 'th={0:0.4}, x={1:0.1f} , y={2:0.1f}'.format(*toptfrm) ### DEBUG return toptfrm
def _plotLayout(self): # Plot the cell with the nucleus, and the limits of the simulation xc = list(); yc = list() xe = list(); ye = list() for ii in range(0, 365): rangle = to_radian(ii) xc.append(self.nucleus.x + self.r * math.cos(rangle)) yc.append(self.nucleus.y + self.r * math.sin(rangle)) xe.append(self.nucleus.x + self.R * math.cos(rangle)) ye.append(self.nucleus.y + self.R * math.sin(rangle)) plot(xc, yc, "-k") plot(xe, ye, "--k")
def _plotLayout(self): # Plot the cell with the nucleus, and the limits of the simulation xc = list() yc = list() xe = list() ye = list() for ii in range(0, 365): rangle = to_radian(ii) xc.append(self.nucleus.x + self.r * math.cos(rangle)) yc.append(self.nucleus.y + self.r * math.sin(rangle)) xe.append(self.nucleus.x + self.R * math.cos(rangle)) ye.append(self.nucleus.y + self.R * math.sin(rangle)) plot(xc, yc, "-k") plot(xe, ye, "--k")
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 combo(A, strX, strY, ang, shiftX, shiftY): c, s = math.cos(ang), math.sin(ang) strec = np.array([[strX, 0.], [0., strY]]) rotat = np.array([[c, -s], [s, c]]) shift = np.array([[shiftX], [shiftY]]) newA = rotat.dot(strec).dot(A)+shift return newA
def distance_on_unit_sphere(coord1, coord2, units='km'): # todo: need to make this work with ellipsoid earth models for more accurate distance calculations # todo: """ Calculate the distance on a spherical earth model with radius hard-coded. :param coord1: start coordinates :param coord2: end coordinates :param units: choose whether to return in km or feet :return: return the distance in km """ lat1, lon1 = coord1.lat, coord1.lon lat2, lon2 = coord2.lat, coord2.lon # Convert latitude and longitude to # spherical coordinates in radians degrees_to_radians = math.pi / 180.0 # phi = 90 - latitude phi1 = (90.0 - lat1) * degrees_to_radians phi2 = (90.0 - lat2) * degrees_to_radians # theta = longitude theta1 = lon1 * degrees_to_radians theta2 = lon2 * degrees_to_radians # Compute spherical distance from spherical coordinates. # For two locations in spherical coordinates # (1, theta, phi) and (1, theta', phi') # cosine( arc length ) = # sin phi sin phi' cos(theta-theta') + cos phi cos phi' # distance = rho * arc length cos = (math.sin(phi1) * math.sin(phi2) * math.cos(theta1 - theta2) + math.cos(phi1) * math.cos(phi2)) """ @todo: need to implement domain check""" arc = math.acos(cos) if units is 'km': return arc * 6373 else: return arc * 3960
def reset_heading(sensor, freq, delay, Mat11, Mat21, Mat31, Mat12, Mat22, Mat32, Mat13, Mat23, Mat33): if sensor == 'Xsens': rotmat = [[Mat11[0], Mat12[0], Mat13[0]], [Mat21[0], Mat22[0], Mat23[0]], [Mat31[0], Mat32[0], Mat33[0]]] if sensor == 'Vicon': rotmat = [ [Mat11[delay * freq], Mat12[delay * freq], Mat13[delay * freq]], [Mat21[delay * freq], Mat22[delay * freq], Mat23[delay * freq]], [Mat31[delay * freq], Mat32[delay * freq], Mat33[delay * freq]] ] # decomposition yaw = math.atan2(-rotmat[0][1], rotmat[0][0]) print(' yaw correction = {} [rad]'.format(-yaw)) Ryaw_reset = [[math.cos(-yaw), -math.sin(-yaw), 0], [math.sin(-yaw), math.cos(-yaw), 0], [0, 0, 1]] length = len(Mat11) Mat11new, Mat21new, Mat31new, Mat12new, Mat22new, Mat32new, Mat13new, Mat23new, Mat33new = [ 0 ] * length, [0] * length, [0] * length, [0] * length, [0] * length, [ 0 ] * length, [0] * length, [0] * length, [0] * length count = 0 for x in Mat11: rotmat = [[Mat11[count], Mat12[count], Mat13[count]], [Mat21[count], Mat22[count], Mat23[count]], [Mat31[count], Mat32[count], Mat33[count]]] rotmat_new = np.dot(Ryaw_reset, rotmat) Mat11new[count] = rotmat_new[0][0] Mat12new[count] = rotmat_new[0][1] Mat13new[count] = rotmat_new[0][2] Mat21new[count] = rotmat_new[1][0] Mat22new[count] = rotmat_new[1][1] Mat23new[count] = rotmat_new[1][2] Mat31new[count] = rotmat_new[2][0] Mat32new[count] = rotmat_new[2][1] Mat33new[count] = rotmat_new[2][2] count += 1 return (Mat11new, Mat21new, Mat31new, Mat12new, Mat22new, Mat32new, Mat13new, Mat23new, Mat33new)
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 lat_lon_distance_on_unit_sphere(coord1, coord2, lat_lon, units='km'): """ Compute either the lateral or longitudinal distance from on point to another; This corresponds to finding the length of one of the legs of the right triangle between the two points. :param coord1: start coordinates :param coord2: end coordinates :param units: choose whether to return in km or miles :return: distance in units specified by 'units' param """ if lat_lon is 'lat': lat1, lon1 = coord1.lat, coord1.lon lat2, lon2 = coord1.lat, coord2.lon elif lat_lon is 'lon': lat1, lon1 = coord1.lat, coord1.lon lat2, lon2 = coord2.lat, coord1.lon else: raise Exception("lat or lon not specified") # Convert latitude and longitude to # spherical coordinates in radians degrees_to_radians = math.pi / 180.0 # phi = 90 - latitude phi1 = (90.0 - lat1) * degrees_to_radians phi2 = (90.0 - lat2) * degrees_to_radians # theta = longitude theta1 = lon1 * degrees_to_radians theta2 = lon2 * degrees_to_radians cos = (math.sin(phi1) * math.sin(phi2) * math.cos(theta1 - theta2) + math.cos(phi1) * math.cos(phi2)) arc = math.acos(cos) # Remember to multiply arc by the radius of the earth # in your favorite set of units to get length. if units is 'km': return arc * 6373 else: return arc * 3960
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 BL2XYZ(lat, lon): R = 6371000.0 #6371km eps = 1.0E-10 xyz = zeros(3) if math.fabs(lat - 90) < eps: xyz[0] = 0 xyz[1] = 0 xyz[2] = R elif math.fabs(lat + 90) < eps: xyz[0] = 0 xyz[1] = 0 xyz[2] = -R else: xyz[0] = math.cos(lat * math.pi / 180.0) * math.cos( lon * math.pi / 180.0) * R xyz[1] = math.cos(lat * math.pi / 180.0) * math.sin( lon * math.pi / 180.0) * R xyz[2] = math.sin(lat * math.pi / 180.0) * R return xyz
def imgR(img, ang): m, n = img.shape[:2] c, s = math.cos(ang), math.sin(ang) q = int(max(m, n)*1.5) newImg = np.ones((q, q, 3)) for i in xrange(m): for j in xrange(n): k = int(round((i-m/2)*c+(j-n/2)*-s+q/2)) l = int(round((i-m/2)*s+(j-n/2)*c+q/2)) newImg[k, l,:] = img[i, j,:] plt.imshow(newImg) plt.show()
def imgR(img, ang): m, n = img.shape[:2] c, s = math.cos(ang), math.sin(ang) q = int(max(m, n) * 1.5) newImg = np.ones((q, q, 3)) for i in xrange(m): for j in xrange(n): k = int(round((i - m / 2) * c + (j - n / 2) * -s + q / 2)) l = int(round((i - m / 2) * s + (j - n / 2) * c + q / 2)) newImg[k, l, :] = img[i, j, :] plt.imshow(newImg) plt.show()
def rotate(A, ang): c, s = math.cos(ang), math.sin(ang) rotat = np.array([[c, -s], [s, c]]) newA = np.dot(rotat, A) plt.subplot(2, 1, 1) plt.plot(A[0], A[1], '.') plt.xlim(-5, 5) plt.ylim(-5, 5) plt.subplot(2, 1, 2) plt.plot(newA[0], newA[1], '.') plt.xlim(-5, 5) plt.ylim(-5, 5) plt.show()
def combo(A, strX, strY, ang, shiftX, shiftY): c, s = math.cos(ang), math.sin(ang) strec = np.array([[strX, 0.], [0., strY]]) rotat = np.array([[c, -s], [s, c]]) shift = np.array([[shiftX], [shiftY]]) newA = rotat.dot(strec).dot(A)+shift plt.subplot(2, 1, 1) plt.plot(A[0], A[1], '.') plt.xlim(-8, 8) plt.ylim(-8, 8) plt.subplot(2, 1, 2) plt.plot(newA[0], newA[1], '.') plt.xlim(-8, 8) plt.ylim(-8, 8) plt.show()
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 combo(A, strX, strY, ang, shiftX, shiftY): c, s = math.cos(ang), math.sin(ang) strec = np.array([[strX, 0.], [0., strY]]) rotat = np.array([[c, -s], [s, c]]) shift = np.array([[shiftX], [shiftY]]) newA = rotat.dot(strec).dot(A) + shift plt.subplot(2, 1, 1) plt.plot(A[0], A[1], '.') plt.xlim(-8, 8) plt.ylim(-8, 8) plt.subplot(2, 1, 2) plt.plot(newA[0], newA[1], '.') plt.xlim(-8, 8) plt.ylim(-8, 8) plt.show()
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 rotate(pitch, roll, yaw): p = np.array([[ 1, 0, 0], [ 0, math.cos(pitch), -math.sin(pitch)], [ 0, math.sin(pitch), math.cos(pitch)]]) r = np.array([[ math.cos(roll), 0, math.sin(roll)], [ 0, 1, 0 ], [-math.sin(roll), 0, math.cos(roll)]]) y = np.array([[ math.cos(yaw), -math.sin(yaw), 0], [ math.sin(yaw), math.cos(yaw), 0], [ 0, 0, 1]]) ro = np.dot(p, np.dot(r, y)) return ro
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 cylindricalWarpImage(img1, K, savefig=False): f = K[0,0] im_h,im_w = img1.shape # go inverse from cylindrical coord to the image # (this way there are no gaps) cyl = np.zeros_like(img1) cyl_mask = np.zeros_like(img1) cyl_h,cyl_w = cyl.shape x_c = float(cyl_w) / 2.0 y_c = float(cyl_h) / 2.0 for x_cyl in np.arange(0,cyl_w): for y_cyl in np.arange(0,cyl_h): theta = (x_cyl - x_c) / f h = (y_cyl - y_c) / f X = np.array([math.sin(theta), h, math.cos(theta)]) X = np.dot(K,X) x_im = X[0] / X[2] if x_im < 0 or x_im >= im_w: continue y_im = X[1] / X[2] if y_im < 0 or y_im >= im_h: continue cyl[int(y_cyl),int(x_cyl)] = img1[int(y_im),int(x_im)] cyl_mask[int(y_cyl),int(x_cyl)] = 255 if savefig: plt.imshow(cyl, cmap='gray') plt.savefig("cyl.png",bbox_inches='tight') return (cyl,cyl_mask)
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)
@author: Benjamín Castro Pohl """ from numpy import math from matplotlib import pyplot import numpy as np n = 4 #Cantidad de triángulos que parten circunferencia de radio 1 listarea = [ ] #Lista de las áreas desde la partición n hasta una partición de 2 triángulos listaerror = [] #Lista de errores entre área n y área n-1 listaerror1 = [] #Lista de errores entre área n y área n-1 a = [] while n > 2: theta = math.pi * 2 / n #Ángulo según partición area = n * (math.sin(theta / 2) * math.cos(theta / 2) ) #Suma de las áreas de todos los triángulos listarea.append(area) n -= 1 la32 = np.asarray( listarea, dtype=np.float32) #La lista de áreas se convierte en un arreglo float32 la64 = np.asarray( listarea, dtype=np.float64) #La lista de áreas se convierte en un arreglo float64 for i in range(len(la32) - 1): listaerror.append( -la32[i + 1] + la32[i]) #Se agrega la diferencia de áreas consecutivas a una lista
def calculateMSBR(hull_points_2d): #print "Input convex hull points: " #print hull_points_2d # Compute edges (x2-x1,y2-y1) edges = zeros( (len(hull_points_2d)-1,2) ) # empty 2 column array for i in range( len(edges) ): edge_x = hull_points_2d[i+1][0] - hull_points_2d[i][0] edge_y = hull_points_2d[i+1][1] - hull_points_2d[i][1] edges[i] = [edge_x,edge_y] # Calculate edge angles atan2(y/x) edge_angles = zeros( (len(edges)) ) # empty 1 column array for i in range( len(edge_angles) ): edge_angles[i] = math.atan2( edges[i][1], edges[i][0] ) # Check for angles in 1st quadrant for i in range( len(edge_angles) ): edge_angles[i] = abs( edge_angles[i] % (math.pi/2) ) # want strictly positive answers # Remove duplicate angles edge_angles = unique(edge_angles) # Test each angle to find bounding box with smallest area min_bbox = (0, float("inf"), 0, 0, 0, 0, 0, 0) # rot_angle, area, width, height, min_x, max_x, min_y, max_y for i in range( len(edge_angles) ): # Create rotation matrix to shift points to baseline # R = [ cos(theta) , cos(theta-PI/2) # cos(theta+PI/2) , cos(theta) ] R = array([ [ math.cos(edge_angles[i]), math.cos(edge_angles[i]-(math.pi/2)) ], [ math.cos(edge_angles[i]+(math.pi/2)), math.cos(edge_angles[i]) ] ]) # Apply this rotation to convex hull points rot_points = dot(R, transpose(hull_points_2d) ) # 2x2 * 2xn # Find min/max x,y points min_x = nanmin(rot_points[0], axis=0) max_x = nanmax(rot_points[0], axis=0) min_y = nanmin(rot_points[1], axis=0) max_y = nanmax(rot_points[1], axis=0) # Calculate height/width/area of this bounding rectangle width = max_x - min_x height = max_y - min_y area = width*height # Store the smallest rect found first (a simple convex hull might have 2 answers with same area) if (area < min_bbox[1]): min_bbox = ( edge_angles[i], area, width, height, min_x, max_x, min_y, max_y ) # Bypass, return the last found rect #min_bbox = ( edge_angles[i], area, width, height, min_x, max_x, min_y, max_y ) # Re-create rotation matrix for smallest rect angle = min_bbox[0] R = array([ [ math.cos(angle), math.cos(angle-(math.pi/2)) ], [ math.cos(angle+(math.pi/2)), math.cos(angle) ] ]) # Project convex hull points onto rotated frame #proj_points = dot(R, transpose(hull_points_2d) ) # 2x2 * 2xn # min/max x,y points are against baseline min_x = min_bbox[4] max_x = min_bbox[5] min_y = min_bbox[6] max_y = min_bbox[7] # Calculate center point and project onto rotated frame center_x = (min_x + max_x)/2 center_y = (min_y + max_y)/2 center_point = dot( [ center_x, center_y ], R ) # Calculate corner points and project onto rotated frame corner_points = zeros( (4,2) ) # empty 2 column array corner_points[0] = dot( [ max_x, min_y ], R ) corner_points[1] = dot( [ min_x, min_y ], R ) corner_points[2] = dot( [ min_x, max_y ], R ) corner_points[3] = dot( [ max_x, max_y ], R ) return (angle, min_bbox[1], min_bbox[2], min_bbox[3], center_point, corner_points)
def vinc_inv(f, a, coordinate_a, coordinate_b): """ Returns the distance between two geographic points on the ellipsoid and the forward and reverse azimuths between these points. lats, longs and azimuths are in radians, distance in metres :param f: flattening of the geodesic :param a: the semimajor axis of the geodesic :param coordinate_a: decimal coordinate given as named tuple coordinate :param coordinate_b: decimal coordinate given as named tuple coordinate Note: The problem calculates forward and reverse azimuths as: coordinate_a -> coordinate_b """ phi1 = math.radians(coordinate_a.lat) lembda1 = math.radians(coordinate_a.lon) phi2 = math.radians(coordinate_b.lat) lembda2 = math.radians(coordinate_b.lon) if (abs(phi2 - phi1) < 1e-8) and (abs(lembda2 - lembda1) < 1e-8): return {'distance': 0.0, 'forward_azimuth': 0.0, 'reverse_azimuth': 0.0} two_pi = 2.0 * math.pi b = a * (1 - f) TanU1 = (1 - f) * math.tan(phi1) TanU2 = (1 - f) * math.tan(phi2) U1 = math.atan(TanU1) U2 = math.atan(TanU2) lembda = lembda2 - lembda1 last_lembda = -4000000.0 # an impossibe value omega = lembda # Iterate the following equations, # until there is no significant change in lembda while (last_lembda < -3000000.0 or lembda != 0 and abs((last_lembda - lembda) / lembda) > 1.0e-9): sqr_sin_sigma = pow(math.cos(U2) * math.sin(lembda), 2) + \ pow((math.cos(U1) * math.sin(U2) - math.sin(U1) * math.cos(U2) * math.cos(lembda)), 2) Sin_sigma = math.sqrt(sqr_sin_sigma) Cos_sigma = math.sin(U1) * math.sin(U2) + math.cos(U1) * math.cos(U2) * math.cos(lembda) sigma = math.atan2(Sin_sigma, Cos_sigma) Sin_alpha = math.cos(U1) * math.cos(U2) * math.sin(lembda) / math.sin(sigma) alpha = math.asin(Sin_alpha) Cos2sigma_m = math.cos(sigma) - (2 * math.sin(U1) * math.sin(U2) / pow(math.cos(alpha), 2)) C = (f / 16) * pow(math.cos(alpha), 2) * (4 + f * (4 - 3 * pow(math.cos(alpha), 2))) last_lembda = lembda lembda = omega + (1 - C) * f * math.sin(alpha) * (sigma + C * math.sin(sigma) * \ (Cos2sigma_m + C * math.cos(sigma) * ( -1 + 2 * pow(Cos2sigma_m, 2)))) u2 = pow(math.cos(alpha), 2) * (a * a - b * b) / (b * b) A = 1 + (u2 / 16384) * (4096 + u2 * (-768 + u2 * (320 - 175 * u2))) B = (u2 / 1024) * (256 + u2 * (-128 + u2 * (74 - 47 * u2))) delta_sigma = B * Sin_sigma * (Cos2sigma_m + (B / 4) * \ (Cos_sigma * (-1 + 2 * pow(Cos2sigma_m, 2)) - \ (B / 6) * Cos2sigma_m * (-3 + 4 * sqr_sin_sigma) * \ (-3 + 4 * pow(Cos2sigma_m, 2)))) s = b * A * (sigma - delta_sigma) alpha12 = math.atan2((math.cos(U2) * math.sin(lembda)), \ (math.cos(U1) * math.sin(U2) - math.sin(U1) * math.cos(U2) * math.cos(lembda))) alpha21 = math.atan2((math.cos(U1) * math.sin(lembda)), \ (-math.sin(U1) * math.cos(U2) + math.cos(U1) * math.sin(U2) * math.cos(lembda))) if (alpha12 < 0.0): alpha12 += two_pi if (alpha12 > two_pi): alpha12 -= two_pi alpha21 += two_pi / 2.0 if alpha21 < 0.0: alpha21 += alpha21 + two_pi if alpha21 > two_pi: alpha21 -= two_pi return {"distance": s, "forward_azimuth": alpha12, "reverse_azimuth": alpha21}
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 zturnangle(a): #sin and cos of the turning matrix of angle a print("ztunangle") s = math.sin(a) c = math.cos(a) print([c,s]) return [c,s]
def Evolvent(self): '''Расчет эвольвенты зуба ''' #Расчет эвольветы зуба # Читаем данные из полей формы # z = Количество зубьев z = self.doubleSpinBox_Z.value() # m = Модуль зуба m = self.doubleSpinBox_m.value() # a = Угол главного профиля a = self.doubleSpinBox_a.value() #b = Угол наклона зубьев b = self.doubleSpinBox_b.value() #ha = Коэффициент высоты головки ha = self.doubleSpinBox_ha.value() #pf = К-т радиуса кривизны переходной кривой pf = self.doubleSpinBox_pf.value() #c = Коэффициент радиального зазора c = self.doubleSpinBox_c.value() #x = К-т смещения исходного контура x = self.doubleSpinBox_x.value() #y =Коэффициент уравнительного смещения y = self.doubleSpinBox_y.value() # n= Количество точек (точность построения) #n=int(self.doubleSpinBox_n.value()) n=100 # заполня переменные # Делительный диаметр d = z * m # Высота зуба h= h = 2.25 * m # Высота головки ha = hav = m # Высота ножки hf= hf = 1.25 * m #Диаметр вершин зубьев #da = d + (2 * m)*(ha+x+y) da = d + 2 * (ha + x - y) * m #Диаметр впадин (справочно) #df = d -(2 * hf) df = d -2 * (ha + c - x) * m #Окружной шаг зубьев или Шаг зацепления по дуге делительной окружности: Pt или p pt = math.pi * m #Окружная толщина зуба или Толщина зуба по дуге делительной окружности: St или S #Суммарный коэффициент смещений: XΣ X = 0.60 + 0.12 # St = 0.5 * pf # St = 0.5 * pt St = 0.5 * pt + 2 * x * m * math.tan(math.radians(a)) #inv a inva=math.tan(math.radians(a))-math.radians(a) #Угол зацепления invαw invaw= (2 * X - math.tan(math.radians(a))) / (10+26) + inva #Угол профиля at = math.ceil(math.degrees(math.atan(math.tan(math.radians(a)) /math.cos( math.radians(b))))) # Диаметр основной окружности db = d * math.cos(math.radians(at)) #Диаметр начала выкружки зуба D = 2 * m * ( ( z/( 2 * math.cos(math.radians(b)) )-(1-x)) ** 2 + ((1-x)/math.tan(math.radians(at)))**2)**0.5 #Промежуточные данные yi = math.pi/2-math.radians(at) hy = yi/(n-1) x0 = math.pi/(4*math.cos(math.radians(b)) )+pf*math.cos(math.radians(at))+math.tan(math.radians(at)) y0 = 1-pf*math.sin(math.radians(at))-x C = (math.pi/2+2*x*math.tan(math.radians(a)) )/z+math.tan(math.radians(at))-math.radians(at) #Расчетный шаг точек эвольвенты hdy = (da-D)/(n-1) dyi = da fi = 2*math.cos(math.radians(b))/z*(x0+y0*math.tan(yi)) #Заполняем текстовые поля в форме # Делительный диаметр # self.lineEdit_d.setText(str(d)) # Высота зуба h= # self.lineEdit_h.setText(str(h)) # Высота головки ha = # self.lineEdit_ha.setText(str(hav)) # Высота ножки hf= # self.lineEdit_hf.setText(str(hf)) # Диаметр вершин зубьев # self.lineEdit_da.setText(str(da)) # Диаметр впадин (справочно) # self.lineEdit_df.setText(str(df)) # Окружной шаг зубьев Pt= # self.lineEdit_Pt.setText(str(math.ceil(pt))) # Окружная толщина зуба St= # self.lineEdit_St.setText(str(math.ceil(St))) # Угол профиля # self.lineEdit_at.setText(str(at)) # Диаметр основной окружности # self.lineEdit_db.setText(str(math.ceil(db))) # Создаем списки List_dyi=[] List_Di=[] List_Yei=[] List_Xei=[] List_Minus_Xei=[] List_Xdai=[] List_Ydai=[] List_yi=[] List_Ai=[] List_Bi=[] List_fi=[] List_Ypki=[] List_Xpki=[] List_Minus_Xpki=[] # Заполняем нуливой (первый )индекс списка значениями List_dyi.append(dyi) List_Di.append( math.acos( db/ List_dyi[0] ) - math.tan( math.acos( db / List_dyi[0] ) ) + C ) List_Yei.append(dyi / 2*math.cos( List_Di[0])) List_Xei.append(List_Yei[0]*math.tan(List_Di[0])) List_Minus_Xei.append(-List_Xei[0]) List_Xdai.append(-List_Xei[0]) List_Ydai.append(((da/2)**2-List_Xdai[0]**2)**0.5) hda=(List_Xei[0]-List_Minus_Xei[0])/(n-1) # Заполняем первый (второй по счету )индекс списка значениями List_dyi.append(dyi-hdy) List_Di.append( math.acos(db/List_dyi[1])-math.tan(math.acos(db/List_dyi[1]))+C) List_Yei.append( List_dyi[1]/2*math.cos(List_Di[1])) List_Xei.append( List_Yei[1]* math.tan(List_Di[1])) List_Minus_Xei.append(-List_Xei[1]) List_Xdai.append(List_Xdai[0]+hda) List_Ydai.append(((da/2)**2-List_Xdai[1]**2)**0.5) Xdai=List_Xdai[1] dyi=dyi-hdy # Начинаем заполнять списки в цикле i=0 while i < n-2: i=i+1 dyi=dyi-hdy List_Di.append(math.acos(db/dyi)-math.tan(math.acos(db/dyi))+C) Di=math.acos(db/dyi)-math.tan(math.acos(db/dyi))+C Yei=dyi/2*math.cos(Di) Xei=Yei*math.tan(Di) List_dyi.append(dyi) List_Yei.append(dyi/2*math.cos(Di)) List_Xei.append(Yei*math.tan(Di)) List_Minus_Xei.append(-Xei) Xdai=Xdai+hda List_Xdai.append(Xdai) List_Ydai.append(((da/2)**2-Xdai**2)**0.5) #Заполняем последний индекс списка List_dyi[n-1]=D # Заполняем нуливой (первый )индекс списка значениями List_yi.append(yi) List_Ai.append(z/(2*math.cos(math.radians(b)))-y0-pf*math.cos(List_yi[0]) ) List_Bi.append(y0*math.tan(List_yi[0])+pf*math.sin(List_yi[0])) List_fi.append(fi) List_Ypki.append((List_Ai[0] * math.cos(fi)+List_Bi[0] * math.sin(fi)) * m) List_Xpki.append((List_Ai[0] * math.sin(fi)-List_Bi[0] * math.cos(fi)) * m) List_Minus_Xpki.append(-List_Xpki[0]) # Начинаем заполнять списки в цикле i=0 while i < n-2: i=i+1 yi=yi-hy List_yi.append(yi) Ai = z / (2 * math.cos(math.radians(b)))-y0-pf*math.cos(yi) List_Ai.append( z / (2 * math.cos(math.radians(b)))-y0-pf*math.cos(yi)) Bi =y0*math.tan(yi)+pf*math.sin(yi) List_Bi.append(y0*math.tan(yi)+pf*math.sin(yi)) fi = 2*math.cos(math.radians(b))/z*(x0+y0*math.tan(yi)) List_fi.append(2*math.cos(math.radians(b))/z*(x0+y0*math.tan(yi))) List_Ypki.append((Ai*math.cos(fi)+Bi*math.sin(fi))*m) Ypki=(Ai*math.cos(fi)+Bi*math.sin(fi))*m Xpki=(Ai*math.sin(fi)-Bi*math.cos(fi))*m List_Xpki.append((Ai*math.sin(fi)-Bi*math.cos(fi))*m) List_Minus_Xpki.append(-Xpki) #Заполняем последний индекс списка List_yi.append(yi-yi) List_Ai.append(z/(2*math.cos(math.radians(b)))-y0-pf*math.cos(List_yi[n-1]) ) List_Bi.append(y0*math.tan(List_yi[n-1])+pf*math.sin(List_yi[n-1])) List_fi.append(2*math.cos(math.radians(b))/z*(x0+y0*math.tan(List_yi[n-1]))) List_Ypki.append((List_Ai[n-1] * math.cos(fi)+List_Bi[n-1] * math.sin(List_fi[n-1])) * m) List_Xpki.append((List_Ai[n-1] * math.sin(fi)-List_Bi[n-1] * math.cos(List_fi[n-1])) * m) List_Minus_Xpki.append(-List_Xpki[n-1]) # self.WiPfileZub(List_Yei,List_Xei,List_Minus_Xei,List_Ypki,List_Xpki,List_Minus_Xpki,List_Ydai,List_Xdai) self.GragEvolvent(List_Minus_Xei+List_Minus_Xpki,List_Yei+List_Ypki,n) DFreza = self.lineEditDFreza.text() VisotaYAxis = self.lineEditVisota.text() Diametr = self.lineEditDiametr.text() if DFreza and VisotaYAxis: E30 = (int(DFreza)/2) +float(VisotaYAxis) else: E30 = 0 angi_B=0 if ValkosZub: angie_A:float = 90# угол А треугольника по высоте детали angie_B:float = float(b) #угол B треугольника по высоте детали ( угол наклона зуба по чертежу) angie_Y:float = 180 - (angie_A + angie_B) # трерий уго треугольника по высоте детали side_c:float = float(E30)# высота детали первая сторона треугольника side_a = side_c * math.sin(math.radians(angie_A)) / math.sin(math.radians(angie_Y))# вторая сторона треугольника side_b = side_c * math.sin(math.radians(angie_B)) / math.sin(math.radians(angie_Y))# третия сторона треугольника ( ось Х) sid_a:float = float(Diametr)/2 # радиус детали первая и вторая тророны треугольника по торцу # sid_a:float = float(self.lineEdit_da.text())/2 # радиус детали первая и вторая тророны треугольника по торцу sid_c:float = sid_a if sid_c < 10 : sid_a:float = 10 sid_c:float = 10 angi_B = float('{:.3f}'.format(math.degrees(math.acos((sid_a**2+sid_c**2-side_b**2)/(2*sid_a*sid_c))))) QMessageBox.about (self, "Ошибка " , "Диаметр шестерни задан меньше 20 мм. \n Введите риальный диаметр шестерни " ) else: angi_B = float('{:.3f}'.format(math.degrees(math.acos((sid_a**2+sid_c**2-side_b**2)/(2*sid_a*sid_c)))))# результат угол поворота стола self.label_da.setText(str(round(da,1))) self.label_d.setText(str(round(d,1))) self.label_at.setText(str(round(at,1))) self.label_db.setText(str(round(db,1))) self.label_df.setText(str(round(df,1))) self.label_St.setText(str(round(St,1))) self.label_Pt.setText(str(round(pt,1))) self.label_hf.setText(str(round(hf,1))) self.label_ha.setText(str(round(ha,1))) self.label_h.setText(str(round(h,1))) self.lineEditDiametr.setText(str(da)) self.lineEditUgol.setText(str(angi_B))
def zturn(): #sin and cos of the turning matrix pos=client.getPose() s = math.sin(pos.orientation.z_rad) c = math.cos(pos.orientation.z_rad) return [c,s]
def cone_search(ra, dec, radius, time_start, time_end, flag, aws_profile, aws_region, s3_output_location, local_output_location, athena_database, athena_workgroup, query_life=10, wait_time=0.1, single_query=True): def query_athena(query, query_args): query = query.format(*query_args) response = athena_client.start_query_execution( QueryString=query, QueryExecutionContext={'Database': athena_database}, ResultConfiguration={'OutputLocation': s3_output_location}, WorkGroup=athena_workgroup) print('Query submitted:\n{}\n'.format(query)) rsp = athena_client.get_query_execution( QueryExecutionId=response['QueryExecutionId']) succeeded_query = True if rsp['QueryExecution']['Status'][ 'State'] == 'SUCCEEDED' else False num_sec_query_has_been_running = 0 # check to see if the query has succeeded while not succeeded_query: if num_sec_query_has_been_running >= query_life: print( 'QUERY CANCELLED: Query {} has been running for ~{} seconds.' .format(response['QueryExecutionId'], num_sec_query_has_been_running)) _ = athena_client.stop_query_execution( QueryExecutionId=response['QueryExecutionId']) return None if num_sec_query_has_been_running % 60 == 0 and num_sec_query_has_been_running: duration = int(num_sec_query_has_been_running / 60) word = 'minutes' if duration > 1 else 'minute' print('...Query has been running for ~{} {}.'.format( duration, word)) # wait until query has succeeded to start the next query if num_sec_query_has_been_running + wait_time > query_life: sleep_time = query_life - num_sec_query_has_been_running else: sleep_time = wait_time time.sleep(sleep_time) num_sec_query_has_been_running += sleep_time rsp = athena_client.get_query_execution( QueryExecutionId=response['QueryExecutionId']) succeeded_query = True if rsp['QueryExecution']['Status'][ 'State'] == 'SUCCEEDED' else False return response['QueryExecutionId'] sess = boto3.Session(profile_name=aws_profile, region_name=aws_region) athena_client = sess.client('athena') s3_client = sess.client('s3') s3_output_path = s3_output_location.replace('s3://', '').split('/') bucket = s3_output_path[0] additional_s3_path = s3_output_location.replace('s3://{}/'.format(bucket), '') queries = { 'single': ''' SELECT * FROM gPhoton_partitioned WHERE zoneID BETWEEN {} AND {} AND dec BETWEEN {} AND {} AND ra BETWEEN {} AND {} AND ({}*cx + {}*cy + {}*cz) > {} AND time >= {} AND time < {} AND flag = {}; ''', 'multiple': ''' SELECT * FROM gPhoton_partitioned WHERE zoneID = {} AND dec BETWEEN {} AND {} AND ra BETWEEN {} AND {} AND ({}*cx + {}*cy + {}*cz) > {} AND time >= {} AND time < {} AND flag = {}; ''' } cx = math.cos(math.radians(dec)) * math.cos(math.radians(ra)) cy = math.cos(math.radians(dec)) * math.sin(math.radians(ra)) cz = math.sin(math.radians(dec)) alpha = get_alpha(radius, dec) if (ra - alpha) < 0: ra = ra + 360 zoneHeight = 30.0 / 3600.0 min_zoneid = int(np.floor((dec - radius + 90.0) / zoneHeight)) max_zoneid = int(np.floor((dec + radius + 90.0) / zoneHeight)) query_args_collection = { 'non-conditional': [ dec - radius, dec + radius, ra - alpha, ra + alpha, cx, cy, cz, math.cos(math.radians(radius)), time_start, time_end, flag ], 'conditional': [ dec - radius, dec + radius, 0, ra - 360 + alpha, cx, cy, cz, math.cos(math.radians(radius)), time_start, time_end, flag ] } query_collection = '' query_argument_collection = [] for zoneid in range(min_zoneid, max_zoneid + 1): query = queries['single'] if single_query else queries['multiple'] zone_args = [min_zoneid, max_zoneid] if single_query else [zoneid] query_args = zone_args + query_args_collection['non-conditional'] if (ra + alpha) > 360: query = query.replace(';', '') + '\n UNION ALL\n' + query additional_args = [min_zoneid, max_zoneid ] if single_query else [zoneid] query_args = query_args + additional_args + query_args_collection[ 'conditional'] temp_query = query.replace( ';', '' ) + '\n UNION ALL\n' if not single_query and zoneid != max_zoneid else query query_collection += temp_query query_argument_collection.extend(query_args) if single_query: break start_time = time.time() execution_id = query_athena(query_collection, query_argument_collection) print('Time taken to query: ~{:.4f} seconds'.format(time.time() - start_time)) # get single CSV or accumulate the CSVs from the different SELECT statements dfs = [] download_paths = [] if execution_id is not None: path_to_csv = os.path.join(additional_s3_path, execution_id + '.csv') download_path = os.path.join(local_output_location, execution_id + '.csv') start_time = time.time() s3_client.download_file(bucket, path_to_csv, download_path) print('Time taken to download: ~{:.4f} seconds'.format(time.time() - start_time)) dfs.append(pd.read_csv(download_path, engine='python')) download_paths.append(download_path) if len(dfs): df = pd.concat(dfs) output_location = os.path.join(local_output_location, str(uuid4()) + '.csv') df.to_csv(output_location, index=False) print('\nData written to {}\n'.format(output_location)) for download_path in download_paths: os.remove(download_path) print(df.head()) else: print('No CSVs were found.')
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 = 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 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 __init__(self, ra, dec, radius, time_start, time_end, flag, aws_profile, aws_region, s3_output_location, local_output_location, athena_database, athena_workgroup, query_life=10, wait_time=0.1, single_query=True): self.ra = ra self.dec = dec self.radius = radius self.time_start = time_start self.time_end = time_end self.flag = flag self.s3_output_location = s3_output_location self.local_output_location = local_output_location self.athena_database = athena_database self.athena_workgroup = athena_workgroup self.query_life = query_life self.wait_time = wait_time self.single_query = single_query sess = boto3.Session(profile_name=aws_profile, region_name=aws_region) global athena_client, s3_client athena_client = sess.client('athena') s3_client = sess.client('s3') self.s3_output_path = s3_output_location.replace('s3://', '').split('/') self.bucket = self.s3_output_path[0] self.additional_s3_path = s3_output_location.replace( 's3://{}/'.format(self.bucket), '') self.query = ''' SELECT * FROM gPhoton_partitioned WHERE zoneID = {} AND dec BETWEEN {} AND {} AND ra BETWEEN {} AND {} AND ({}*cx + {}*cy + {}*cz) > {} AND time >= {} AND time < {} AND flag = {}; ''' # calculate_query_parameters self.cx = math.cos(math.radians(self.dec)) * math.cos( math.radians(self.ra)) self.cy = math.cos(math.radians(self.dec)) * math.sin( math.radians(self.ra)) self.cz = math.sin(math.radians(self.dec)) self.alpha = self._get_alpha() if (self.ra - self.alpha) < 0: self.ra = self.ra + 360 self.zoneHeight = 30.0 / 3600.0 self.min_zoneid = int( np.floor((self.dec - self.radius + 90.0) / self.zoneHeight)) self.max_zoneid = int( np.floor((self.dec + self.radius + 90.0) / self.zoneHeight)) self.query_args_collection = { 'non-conditional': [ self.dec - self.radius, self.dec + self.radius, self.ra - self.alpha, self.ra + self.alpha, self.cx, self.cy, self.cz, math.cos(math.radians(self.radius)), self.time_start, self.time_end, self.flag ], 'conditional': [ self.dec - self.radius, self.dec + self.radius, 0, self.ra - 360 + self.alpha, self.cx, self.cy, self.cz, math.cos(math.radians(self.radius)), self.time_start, self.time_end, self.flag ] }
def rotate(A, ang): c, s = math.cos(ang), math.sin(ang) L = np.array([[c, -s], [s, c]]) newA = np.dot(L, A) return newA
V[k][i] = Vn # Simulando modelo de onda cinemática (valores en k+1): k = k + 1 dt = dx * NC / Vn # [segundos] Cambio temporal inicial t.append(t[k - 1] + dt) # [segundos] Tiempo en k=1 while t[k] <= 60. * tf: # Inicializando campo para almacenar datos: Q.append(zeros(ni)), y.append(zeros(ni)), A.append(zeros(ni)), V.append( zeros(ni)) # Calculando caudal en i=0 angle = math.pi * t[k] / (60. * 75.) if angle < 2. * math.pi: # Condición causal de la perturbación # [pies^3*s-1] Caudal total durante el evento de perturbación Q[k][0] = Qn + 750. * (1. - math.cos(angle)) / math.pi else: # Final de la perturbación Q[k][0] = Qn # [pies^3/s] Flujo base # Calculando el esténcil: for i in range(ni): # Altura de agua en nodo i [pies]: y[k][i] = ynormal(und, n, S, z, b, Q[k][i]) # Área mojada en nodo i [pies^2]: A[k][i] = y[k][i] * (b + z * y[k][i]) # Velocidad media en nodo i [pies/s]: V[k][i] = Q[k][i] / A[k][i] # Caudal en nodo i+1 [pies^3/s]: if i < ni - 1: Q[k][i + 1] = Q[k][i] - (dx / dt) * (A[k][i] - A[k - 1][i])
def vinc_dir(f, a, coordinate_a, alpha12, s): """ Returns the lat and long of projected point and reverse azimuth given a reference point and a distance and azimuth to project. lats, longs and azimuths are passed in decimal degrees Returns ( phi2, lambda2, alpha21 ) as a tuple """ phi1, lambda1 = coordinate_a.lat, coordinate_a.lon piD4 = math.atan(1.0) two_pi = piD4 * 8.0 phi1 = phi1 * piD4 / 45.0 lambda1 = lambda1 * piD4 / 45.0 alpha12 = alpha12 * piD4 / 45.0 if alpha12 < 0.0: alpha12 += two_pi if alpha12 > two_pi: alpha12 -= two_pi b = a * (1.0 - f) tan_u1 = (1 - f) * math.tan(phi1) u1 = math.atan(tan_u1) sigma1 = math.atan2(tan_u1, math.cos(alpha12)) sin_alpha = math.cos(u1) * math.sin(alpha12) cos_alpha_sq = 1.0 - sin_alpha * sin_alpha u2 = cos_alpha_sq * (a * a - b * b) / (b * b) # @todo: look into replacing A and B with vincenty's amendment, see if speed/accuracy is good A = 1.0 + (u2 / 16384) * (4096 + u2 * (-768 + u2 * (320 - 175 * u2))) B = (u2 / 1024) * (256 + u2 * (-128 + u2 * (74 - 47 * u2))) # Starting with the approx sigma = (s / (b * A)) last_sigma = 2.0 * sigma + 2.0 # something impossible # Iterate the following 3 eqs unitl no sig change in sigma # two_sigma_m , delta_sigma while abs((last_sigma - sigma) / sigma) > 1.0e-9: two_sigma_m = 2 * sigma1 + sigma delta_sigma = B * math.sin(sigma) * (math.cos(two_sigma_m) + (B / 4) * (math.cos(sigma) * (-1 + 2 * math.pow( math.cos(two_sigma_m), 2) - (B / 6) * math.cos(two_sigma_m) * (-3 + 4 * math.pow(math.sin(sigma), 2)) * (-3 + 4 * math.pow( math.cos(two_sigma_m), 2))))) last_sigma = sigma sigma = (s / (b * A)) + delta_sigma phi2 = math.atan2((math.sin(u1) * math.cos(sigma) + math.cos(u1) * math.sin(sigma) * math.cos(alpha12)), ((1 - f) * math.sqrt(math.pow(sin_alpha, 2) + pow(math.sin(u1) * math.sin(sigma) - math.cos(u1) * math.cos( sigma) * math.cos(alpha12), 2)))) lmbda = math.atan2((math.sin(sigma) * math.sin(alpha12)), (math.cos(u1) * math.cos(sigma) - math.sin(u1) * math.sin(sigma) * math.cos(alpha12))) C = (f / 16) * cos_alpha_sq * (4 + f * (4 - 3 * cos_alpha_sq)) omega = lmbda - (1 - C) * f * sin_alpha * (sigma + C * math.sin(sigma) * (math.cos(two_sigma_m) + C * math.cos(sigma) * (-1 + 2 * math.pow(math.cos(two_sigma_m), 2)))) lambda2 = lambda1 + omega alpha21 = math.atan2(sin_alpha, (-math.sin(u1) * math.sin(sigma) + math.cos(u1) * math.cos(sigma) * math.cos(alpha12))) alpha21 += two_pi / 2.0 if alpha21 < 0.0: alpha21 += two_pi if alpha21 > two_pi: alpha21 -= two_pi phi2 = phi2 * 45.0 / piD4 lambda2 = lambda2 * 45.0 / piD4 alpha21 = alpha21 * 45.0 / piD4 return Coordinate(lat=phi2, lon=lambda2), alpha21
def m_to_long(m, lat): return -1.0 / (111320 * math.cos(lat)) * m