Beispiel #1
0
def points_between_points(point1, point2, delta):
    """Creates an array of points between two points given a delta

    :param point1: The first point
    :type point1: numpy.ndarray

    :param point2: The second point
    :type point2: numpy.ndarray

    :param delta: The increment between inserted points
    :type delta: float

    :returns: Array of points.
    :rtype: numpy.ndarray

    Note:
        u = (x1-x0, y1-y0)/L, where
        L=sqrt( (x1-x0)^2 + (y1-y0)^2).
        If r is the resolution, then the
        points will be given by
        (x0, y0) + u * n * r for n = 1, 2, ....
        while len(n*u*r) < L
    """
    x0, y0 = point1
    x1, y1 = point2
    L = math.sqrt(math.pow((x1 - x0), 2) + math.pow((y1 - y0), 2))
    pieces = int(L / delta)
    uu = numpy.array([x1 - x0, y1 - y0]) / L
    points = [point1]
    for nn in range(pieces):
        point = point1 + uu * (nn + 1) * delta
        points.append(point)
    return numpy.array(points)
Beispiel #2
0
	def countStatParams(self, u, N, label):
		if N:
			m = 0
			for u1 in u:
				m += u1
			m = (m  + 0.0) / N
			sigma_2 = 0
			gamma = 0
			kapa = 0
			for u1 in u:
				sigma_2 += math.pow(u1 - m, 2)
				gamma += math.pow(u1 - m, 3)
				kapa += math.pow(u1 - m, 4)
				
			sigma_2 = sigma_2 / (N - 1.0)
			sigma = math.sqrt(sigma_2)
			try:
				r = sigma / m
			except:
				r = 'inf'
			try:
				gamma = gamma / N / math.pow(sigma, 3)
				kapa = kapa / N / math.pow(sigma_2, 2) - 3
			except:
				gamma = 'inf'
				kapa = 'inf'
			label.setText(u' Среднее: %s,\n Дисперсия: %s,\n Среднеквадратичное отклонение: %s,\n Коэффициент вариации: %s,\n Коээффициента асимметрии: %s,\n Коэффициент эксцесса: %s' % (
				m, sigma_2, sigma, r, gamma, kapa))
		self.analyzedSignal.emit()		
def getCylinderCylinderIntersectionVolume(cylinderOneRadius, cylinderTwoRadius, angleInDegrees, pointsToGenerate = 10**5):
	angleInRadians = angleInDegrees * math.pi / 180

	if angleInDegrees == 90:
		boundLength = cylinderOneRadius * 2.0
	else:
		boundLength = (cylinderOneRadius * 2.0 / math.sin(angleInRadians)) + (cylinderTwoRadius * 2.0 / math.tan(angleInRadians))

	cylinderOneRadiusSquared = math.pow(cylinderOneRadius, 2)
	cylinderTwoRadiusSquared = math.pow(cylinderTwoRadius, 2)

	points = pointsToGenerate = int(pointsToGenerate)
	pointsInIntersection = 0

	while points > 0:
		points -= 1

		randomPointInBound = Point.getRandomPointInCylinder(cylinderOneRadius, boundLength)
		rotatedPointInBound = Point((randomPointInBound.coordinates[0], randomPointInBound.coordinates[2])).rotate(angleInRadians)

		# Check intersection
		if math.pow(randomPointInBound.coordinates[1], 2) + math.pow(rotatedPointInBound.coordinates[1], 2) <= cylinderTwoRadiusSquared:
			pointsInIntersection += 1

	cylinderOneVolume = math.pi * cylinderOneRadiusSquared * boundLength
	return pointsInIntersection * cylinderOneVolume / pointsToGenerate
Beispiel #4
0
def draw_car(x,y,th,canv):    
    r = math.sqrt(math.pow(ROBOT_LENGTH,2) + math.pow(ROBOT_WIDTH,2))/2    
    x = x + 300.0/cm_to_pixels
    y = y + 300.0/cm_to_pixels
    
    # top left
    phi = th + math.pi/2+ math.atan2(ROBOT_LENGTH,ROBOT_WIDTH)
    topleft  = (x + r*math.cos(phi),y+r*math.sin(phi))
    
    #top right
    phi = th + math.atan2(ROBOT_WIDTH,ROBOT_LENGTH) 
    topright = (x + r*math.cos(phi),y+r*math.sin(phi))

    # bottom left
    phi = th + math.pi + math.atan2(ROBOT_WIDTH,ROBOT_LENGTH)
    bottomleft =  (x + r*math.cos(phi),y+r*math.sin(phi))
    
    # bottom right
    phi = th + 3*math.pi/2 + math.atan2(ROBOT_LENGTH,ROBOT_WIDTH)
    bottomright =  (x + r*math.cos(phi),y+r*math.sin(phi))
    
    canv.create_polygon(topleft[0]*cm_to_pixels,600 - topleft[1]*cm_to_pixels,
                        bottomleft[0]*cm_to_pixels,600 - bottomleft[1]*cm_to_pixels,
                        bottomright[0]*cm_to_pixels,600 - bottomright[1]*cm_to_pixels,
                        topright[0]*cm_to_pixels,600 - topright[1]*cm_to_pixels,
                        width = 1, outline = 'blue',fill = '')
    x1 = x*cm_to_pixels
    y1 = y*cm_to_pixels
    canv.create_oval(x1-1,600-(y1-1),x1+1,600-(y1+1),outline = 'green',fill = 'green')
Beispiel #5
0
def GetSpindownStuff(tc, age, l0, b0, emax0, n0):

  t = np.logspace(0,math.log10(1000.*age),300)
  lumt = []
  emaxt = []
  bt = []
  nt = []
  n = 0
  for i in t:
    l = l0/math.pow(1.+i/tc,2.)
    btt = b0*math.sqrt(l/l0)*(1.+0.5*math.sin(0.1*n*3.14))
    lumtt = l*(1.+0.5*math.cos(0.1*n*3.14))
    emaxtt = emax0*math.pow(l/l0,0.25)*(1.+0.5*math.sin(0.05*n*3.14))
    ntt = n0*math.pow(l/l0,0.25)*(1.+0.5*math.cos(0.05*n*3.14))

    bt.append([])
    bt[n].append(i)
    bt[n].append(btt)
    lumt.append([])
    lumt[n].append(i)
    lumt[n].append(lumtt)
    emaxt.append([])
    emaxt[n].append(i)
    emaxt[n].append(emaxtt)
    nt.append([])
    nt[n].append(i)
    nt[n].append(ntt)

    n = n+1
  return lumt,bt,emaxt,nt
Beispiel #6
0
def AgeIndividual(particle, fieldset, time, dt):
    #print("Ageing")
    particle.age += dt
    if (particle.age - (particle.monthly_age*30*24*60*60)) > (30*24*60*60):
        particle.monthly_age += 1
        a=2.225841100458143# 0.7343607395421234 old parameters
        b=0.8348850216641774# 0.5006692114850767 old parameters
        Alengths = [3.00, 4.51, 6.02, 11.65, 16.91, 21.83, 26.43, 30.72, 34.73, 38.49,
                   41.99, 45.27, 48.33, 51.19, 53.86, 56.36, 58.70, 60.88, 62.92, 64.83,
                   66.61, 68.27, 69.83, 71.28, 72.64, 73.91, 75.10, 76.21, 77.25, 78.22,
                   79.12, 79.97, 80.76, 81.50, 82.19, 82.83, 83.44, 84.00, 84.53, 85.02,
                   85.48, 85.91, 86.31, 86.69, 87.04, 87.37, 87.68, 87.96, 89.42, 89.42, 89.42, 89.42,
                   89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42,
                   89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42,
                   89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42, 89.42]
        L = lengths[(particle.monthly_age-1)]/100  #L = GetLengthFromAge(monthly_age)
        vmax = a * math.pow(L, b)
        particle.Vmax = vmax
        MPmax=0.3
        MPexp=0.1008314958945224
        MSmax=0.006109001382111822
        MSslope=0.8158285706493162
        Mrange=0.00001430156
        Mnat = MPmax*math.exp(-1*MPexp*particle.age) + MSmax*math.pow(particle.age, MSslope)
        Hexp = 1-fieldset.H[time, particle.lon, particle.lat, particle.depth]/2
        Mvar = Mnat * math.pow((1 - Mrange), Hexp)#(1-fieldset.H[time, lon, lat, particle.depth]))#/2))
        if random.uniform(0, 1) > Mvar:
            particle.active = 0
            particle.release_time = 100000000*100000000 #Particle will not be reactivated
            particle.lon = 0
            particle.lat = 0
    def compute_euc_distance(self, point1, point2):
        x_distance = point1[0] - point2[0]
        x_distance = math.pow(x_distance, 2)
        y_distance = point1[1] - point2[1]
        y_distance = math.pow(y_distance, 2)

        return math.sqrt(x_distance + y_distance)
def main():
    filename = time.strftime('%A-%Y%m%d-%H-%M-%S') + '.txt'  # filename with system date time format
    f = open(filename , 'w') # opening the file with write 'w' permission
    
    f.write('+++++++++++++++++++++++++++++++++\n') # decoration with +++
    print('+++++++++++++++++++++++++++++++++')
            #To add the characters/decorating output
    days = int(input("Please enter number of days: ") )   #Asking user input
    f.write('days:  %s'%days)                             # Writing the user input 'days' to the text file
    if ( days > 0 and days <= 366 ):                      #condition to check valid days in a year
        n = math.pow(2, days-1)                           #power function ...2^n-1
        m = n / 100                                       #Converting cents to dollars
        f.write('\n+++++++++++++++++++++++++++++++++\n')
        print('+++++++++++++++++++++++++++++++++')
        f.write(' Day   Today\'s Salary \n------  -----------------\n %s    $%s'%(days,m))   #%s-substitution %(days,m) using variable to display output
        print(' Day   Today\'s Salary \n------  -----------------\n %s    $%s'%(days,m))    #%s-substitution %(days,m) using variable to display output 
    else:
        while True:                                                    #looping to check whether user has entered valid data
            f.write("\nInvalid number of days\n")               # Writing invalid number of days to text file
            print("Invalid number of days\n")
            f.write('+++++++++++++++++++++++++++++++++\n')      # decoration with +++ in the text file
            print('+++++++++++++++++++++++++++++++++\n')
            days = int(input("Please enter number of days: ") ) #Asking user input
            f.write('days:  %s'%days)
            #print ('------------------------------')  
            if ( days > 0 and days <= 366 ):
                n = int(math.pow(2, days-1))
                m = n / 100
                print ('+++++++++++++++++++++++++++++++++\n')
                f.write('\n+++++++++++++++++++++++++++++++++\n')
                f.write(' Day   Today\'s Salary\n------  -------------------\n %s    $%s'%(days,m))
                print(' Day   Today\'s Salary\n------  -------------------\n %s    $%s'%(days,m))
                break                                                      #breaking the loop
Beispiel #9
0
 async def fetch_currencies(self, params={}):
     response = await self.publicGetCurrencyList(params)
     currencies = response['response']['entities']
     precision = self.precision['amount']
     result = {}
     for i in range(0, len(currencies)):
         currency = currencies[i]
         id = currency['currency_id']
         code = self.common_currency_code(currency['iso'].upper())
         result[code] = {
             'id': id,
             'code': code,
             'name': currency['name'],
             'active': True,
             'status': 'ok',
             'precision': precision,
             'limits': {
                 'amount': {
                     'min': None,
                     'max': math.pow(10, precision),
                 },
                 'price': {
                     'min': math.pow(10, -precision),
                     'max': math.pow(10, precision),
                 },
                 'cost': {
                     'min': None,
                     'max': None,
                 },
             },
             'info': currency,
         }
     return result
Beispiel #10
0
def isInCircle(x,y, circle):
	dist = math.sqrt((math.pow(x-circle[0],2))+(math.pow(y-circle[1],2)))
	if dist <= int(100):
		return True
	else:
		cv2.circle(original,(x,y),1,(255,255,255))
		return False
Beispiel #11
0
def evaluateLogLikelihood(params, D, N, M_min, M_max):
      alpha = params[0]  # extract alpha
      # Compute normalisation constant.
      c = (1.0 - alpha)/(math.pow(M_max, 1.0-alpha) 
                          - math.pow(M_min, 1.0-alpha))
      # return log likelihood.
      return N*math.log(c) - alpha*D
Beispiel #12
0
def convert_to_polar(mag):
    hmag = mag[0]
    vmag = mag[1]
    angle = math.atan2(float(vmag), float(hmag))
    distance = math.sqrt(math.pow(mag[0], 2) + math.pow(mag[1], 2))
    angle = 180 - math.degrees(angle)
    return (angle, distance)
def costFunctionGaussianResponses(datapoints, params, nClasses):
	responses = np.zeros((nClasses,len(datapoints)))

	var = []
	for j in range(nClasses):
		var.append(getGaussianPdf(params[j][0], params[j][1]))

	for j in range(len(datapoints)):
		p = [datapoints[j][0], datapoints[j][1]]
		for i in range(nClasses):
			responses[i,j] = (1/float(nClasses)) * var[i].pdf(p)

	responses = responses / np.sum(responses,axis=0)

	sum = 0
	for i in range(nClasses):
		withinVariance = 0
		for j in range(0, len(datapoints)-1):
			difference = responses[i,j+1] - responses[i,j]
			differenceSquared = math.pow(difference, 2)
			withinVariance += differenceSquared

		v = math.pow(np.std(responses[i]), 2)
		betweenVariance = math.pow(v,2)

		sum += (withinVariance/float(betweenVariance))

	return sum
Beispiel #14
0
 def get_nearest(eye, at, up, phis, thetas):
     """ returns phi and theta settings that most closely match current view """
     #todo: derive it instead of this brute force search
     best_phi = None
     best_theta = None
     best_dist = None
     best_up = None
     dist1 = math.sqrt(sum(math.pow(eye[x]-at[x],2) for x in [0,1,2]))
     for t,p in ((x,y) for x in thetas for y in phis):
         theta_rad = (float(t)) / 180.0 * math.pi
         phi_rad = float(p) / 180.0 * math.pi
         pos = [
             float(at[0]) - math.cos(phi_rad)   * dist1 * math.cos(theta_rad),
             float(at[1]) + math.sin(phi_rad)   * dist1 * math.cos(theta_rad),
             float(at[2]) + math.sin(theta_rad) * dist1
         ]
         nup = [
             + math.cos(phi_rad) * math.sin(theta_rad),
             - math.sin(phi_rad) * math.sin(theta_rad),
             + math.cos(theta_rad)
         ]
         dist = math.sqrt(sum(math.pow(eye[x]-pos[x],2) for x in [0,1,2]))
         updiff = math.sqrt(sum(math.pow(up[x]-nup[x],2) for x in [0,1,2]))
         if best_dist == None or (dist<best_dist and updiff<1.0):
             best_phi = p
             best_theta = t
             best_dist = dist
             best_up = updiff
     return best_phi, best_theta
Beispiel #15
0
    def distances_per_degree(lat, a=SEMI_MAJOR_AXIS, inverse_flattening=INVERSE_FLATTENING):
        """ Returns a tuple containing arc distances in the units of the semi-major axis. 
        The first is the distance along an arc of one degree at a constant latitude (lat).
        The second is the distance along an arc of one degree at a constant lng centered on the given lat.

        Arguments:
            lat - the latitude at which the distances apply
            a - the semi-major axis of the ellipsoid for the coordinate reference system
            inverse_flattening - the inverse of the ellipsoid's flattening parameter 
        """

        f = 1.0 / inverse_flattening    
        e_squared = f * (2.0 - f) # e^2 = 2f - f^2

        # N - radius of curvature in the prime vertical, (tangent to ellipsoid at latitude)
        # N(lat) = a/(1-e^2*sin^2(lat))^0.5
        N = a / math.sqrt(1.0 - e_squared * (math.pow(math.sin(lat * math.pi / 180.0), 2.0))) 

        # M - radius of curvature in the prime meridian, (tangent to ellipsoid at latitude)
        # M(lat) = a(1-e^2)/(1-e^2*sin^2(lat))^1.5
        M = a * (1.0 - e_squared) / math.pow(1.0 - e_squared * math.pow(math.sin(lat * math.pi / 180.0), 2.0), 1.5)

        # longitude is irrelevant for the calculations to follow so simplify by using longitude = 0, so Y = 0
        # X = Ncos(lat)cos(long). long = 0, so cos(long) = 1.0
        X = N * math.cos(lat * math.pi / 180.0) * 1.0 
        lngdistanceperdegree = math.pi * X / 180.0 
        latdistanceperdegree = math.pi * M / 180.0
        return (lngdistanceperdegree, latdistanceperdegree)
def simulate():
    error_sum = 0
    for i in range(0, 10000):
        X = np.random.normal(loc=0, scale=1)
        Y = np.random.normal(loc=0, scale=1)
        error_sum += math.sqrt(math.pow(X, 2) + math.pow(Y, 2))
    print('Average Distance is:', error_sum / 10000)
Beispiel #17
0
def DeltaVz(z):
    """Calculates the density contrast of a virialised region S{Delta}V(z),
    assuming a S{Lambda}CDM-type flat cosmology. See, e.g., Bryan & Norman
    1998 (ApJ, 495, 80).

    @type z: float
    @param z: redshift
    @rtype: float
    @return: density contrast of a virialised region at redshift z

    @note: If OMEGA_M0+OMEGA_L0 is not equal to 1, this routine exits and
    prints an error
    message to the console.

    """

    OMEGA_K = 1.0 - OMEGA_M0 - OMEGA_L0

    if OMEGA_K == 0.0:
        Omega_Mz = OmegaMz(z)
        deltaVz = (18.0 * math.pow(math.pi, 2) + 82.0 *
                   (Omega_Mz - 1.0) - 39.0 * math.pow(Omega_Mz - 1, 2))
        return deltaVz
    else:
        raise Exception("cosmology is NOT flat.")
Beispiel #18
0
def trajectoire_rotation(t, dcfg_traj, rotation_type, deriv) :
    t1 = dcfg_traj['t1']
    if rotation_type == 'r1' :
        x_r = dcfg_traj['x_cr1']
        y_r = dcfg_traj['y_cr1']
        R = 1.0 / dcfg_traj['Rinv_sp3_1']
        theta0 = dcfg_traj['theta0_r1']
        angle = dcfg_traj['angle_r1']
    if rotation_type == 'r2' :
        x_r = dcfg_traj['x_cr2']
        y_r = dcfg_traj['y_cr2']
        R = 1.0 / dcfg_traj['Rinv_sp3_2']
        theta0 = dcfg_traj['theta0_r2']
        angle = dcfg_traj['angle_r2']
        
    theta = theta0 + (t * angle) / t1
    if (deriv == 0) :
        x = x_r + R * cos(theta)
        y = y_r + R * sin(theta)
    if angle < (dcfg_traj['angle_step'] / 2.0) :
        angle = angle + dcfg_traj['angle_step'] * 0.1
    if (deriv == 1) :
        x = R * (angle/t1)*(-sin(theta))
        y = R * (angle/t1)*cos(theta)
    if (deriv == 2) :
        x = R * pow(angle/t1, 2)*(-cos(theta))
        y = R * pow(angle/t1, 2)*(-sin(theta))
    
    return [x, y]
Beispiel #19
0
def _compute_sse(screen, clusters, weights):
    idx_map = {}
    for i,v in enumerate(clusters):
        idx_map[v] = idx_map.get(v, [])
        idx_map[v].append(i)

    wss = 0
    bss = 0
    means = {}
    for cl, rec in idx_map.iteritems():
        m = len(rec)
        if m > 1:
            dm = np.zeros((m * (m - 1)) // 2, dtype=np.double)
            k = 0
            for i in xrange(0, m - 1):
                for j in xrange(i + 1, m):
                    i_idx = rec[i]
                    j_idx = rec[j]
                    dm[k] = cockatoo.metric.distance(screen.cocktails[i_idx], screen.cocktails[j_idx], weights=weights)
                    k = k + 1

            mean = dm.mean()
            means[cl] = mean
            for i in xrange(0, k):
                wss += math.pow(dm[i] - mean, 2)

    mean_arr = np.array(means.values())
    mean = mean_arr.mean()
    for cl, rec in idx_map.iteritems():
        m = len(rec)
        if cl in means:
            c_mean = means[cl]
            bss += m * math.pow(c_mean-mean, 2)

    return (len(idx_map), wss, bss)
def RMSE(mat_predict, mat_true):
	
	sha_predict = mat_predict.shape
	sha_true = mat_true.shape

	if sha_true != sha_predict:
		print('error! yay!')
		return 0

	summy = float(0.0)
	count = float(0.0)

	# set up the data frame for outputting
	predict_out = np.matrix([[0,0,0]])

	# you only care about the non-null values of mat_true
	for i in xrange(0,numusers):
		for j in xrange(0,nummovies):
			if mat_true[i,j] != 0:
				count = count + 1
				summy = summy + math.pow((mat_true[i,j] - mat_predict[i,j]),2)

				# add to the output matrix
				predict_out = np.vstack((predict_out,np.matrix([i+1,j+1,mat_predict.item(i,j)])))

	# complete the equation
	RSME_value = math.pow(summy/count,0.5)

	# return it after deleting the first rwo etc
	predict_out = np.delete(predict_out,(0),axis = 0)
	
	return RSME_value, predict_out
def lpnorm(vec,p):

	# convert p to a double regardless
	p = p + 0.0

	# get the dimensions of the vector
	j = vec.shape

	# we want 1xn, so if it's nx1, change it to 1xn
	vec = vec.flatten()

	# print(vec)
	# create a variable to sum up the elements
	summy = 0
	
	# get loop stuff
	loopmax = max(j)
	# print('loopmax:')
	# print(loopmax)

	# loop through and sum
	for i in range(0,loopmax):
		# print('inloop:')
		jeff = vec.item(i)
		# print(jeff)
		summy = summy + math.pow(jeff,p)
		# print(summy)

	summy = math.pow(summy,(1/p))
	return summy
def gradient(image, mask_type='sobel'):
    indice_mascara = {
        "sobelx":[[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]],
        "sobely":[[1.0, 2.0, 1.0], [0.0, 0.0, 0.0], [-1.0, -2.0, -1.0]],
        "prewittx":[[-1.0, 0.0, 1.0], [-1.0, 0.0, 1.0], [-1.0, 0.0, 1.0]],
        "prewitty":[[1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [-1.0, -1.0, -1.0]]
        }

    pic_copy = (image.copy()).load()
    pic = image.load()
    kernelx = indice_mascara[mask_type+'x']
    kernely = indice_mascara[mask_type+'y']
    max_value = 0
    for i in range(image.size[0]):
        for j in range(image.size[1]):

            gx, gy = (0.0, 0.0)
            kernel_len = len(kernelx[0])
            kernel_pos = 0
            for h in range(i-1, i+2):
                for l in range(j-1, j+2):
                    if h >= 0 and l >= 0 and h < image.size[0] and l < image.size[1]:
                        pixel = pic_copy[h, l]
                        pixel = max(pixel)/len(pixel)
                        gx += pixel*kernelx[int(kernel_pos/3)][kernel_pos%3]
                        gy += pixel*kernely[int(kernel_pos/3)][kernel_pos%3]
                        kernel_pos += 1

            gradiente = int(math.sqrt(math.pow(gx, 2) + math.pow(gy, 2)))
            pic[i, j] = tuple([gradiente]*3)
            if gradiente > max_value:
                max_value = gradiente
    return max_value
    def gridToGeodetic(self, north, east):
        """
        Transformation from grid coordinates to geodetic coordinates.
        @param north (corresponds to X in RT 90 and N in SWEREF 99.)
        @param east (corresponds to Y in RT 90 and E in SWEREF 99.)
        @return (latitude, longitude)
        """
        if (self._initialized == False):
            return None

        deg_to_rad = math.pi / 180
        lambda_zero = self._central_meridian * deg_to_rad
        xi = (north - self._false_northing) / (self._scale * self._a_roof)        
        eta = (east - self._false_easting) / (self._scale * self._a_roof)
        xi_prim = xi - \
                self._delta1*math.sin(2.0*xi) * math.cosh(2.0*eta) - \
                self._delta2*math.sin(4.0*xi) * math.cosh(4.0*eta) - \
                self._delta3*math.sin(6.0*xi) * math.cosh(6.0*eta) - \
                self._delta4*math.sin(8.0*xi) * math.cosh(8.0*eta)
        eta_prim = eta - \
                self._delta1*math.cos(2.0*xi) * math.sinh(2.0*eta) - \
                self._delta2*math.cos(4.0*xi) * math.sinh(4.0*eta) - \
                self._delta3*math.cos(6.0*xi) * math.sinh(6.0*eta) - \
                self._delta4*math.cos(8.0*xi) * math.sinh(8.0*eta)
        phi_star = math.asin(math.sin(xi_prim) / math.cosh(eta_prim))
        delta_lambda = math.atan(math.sinh(eta_prim) / math.cos(xi_prim))
        lon_radian = lambda_zero + delta_lambda
        lat_radian = phi_star + math.sin(phi_star) * math.cos(phi_star) * \
                (self._Astar + \
                 self._Bstar*math.pow(math.sin(phi_star), 2) + \
                 self._Cstar*math.pow(math.sin(phi_star), 4) + \
                 self._Dstar*math.pow(math.sin(phi_star), 6))      
        lat = lat_radian * 180.0 / math.pi
        lon = lon_radian * 180.0 / math.pi
        return (lat, lon)
def pythag_pos_diff(objPosArray1,objPosArray2):
    
    #calculates the pythagorian position difference between two n-dimensional position arrays
    pythagSum=0
    for l in range(len(objPosArray1)):
        pythagSum+=math.pow(objPosArray1[l]-objPosArray2[l],2)
    return math.pow(pythagSum,1.0/2.0)
  def testFixedNonUniform(self):
    """Sets up the quantile summary op test as follows.

    Creates array dividing range [0, 1] to 1<<16 elements equally spaced
    with weight same as the value.
    """
    dense_float_tensor_0 = constant_op.constant(
        [(1.0 * i) / math.pow(2.0, 16)
         for i in range(0, int(math.pow(2, 16)) + 1)])
    example_weights = constant_op.constant(
        [(1.0 * i) / math.pow(2.0, 16)
         for i in range(0, int(math.pow(2, 16)) + 1)])

    config = self._gen_config(0.1, 10)

    with self.test_session():
      dense_buckets, _ = quantile_ops.quantile_buckets(
          [dense_float_tensor_0], [], [], [],
          example_weights=example_weights,
          dense_config=[config],
          sparse_config=[])
      self.assertAllClose(
          [0] + [math.sqrt((i + 1.0) / 10) for i in range(0, 10)],
          dense_buckets[0].eval(),
          atol=0.1)
Beispiel #26
0
def get_close_matches(term, fields, fuzziness=0.4, key=None):
    import math
    import difflib

    def _ratio(a, b):
        return difflib.SequenceMatcher(None, a, b).ratio()

    term = term.lower()
    matches = []

    for field in fields:
        fld = field if key is None else key(field)
        if term == fld:
            matches.append((field, 1.0))
        else:
            name = fld.lower()
            r = _ratio(term, name)
            if name.startswith(term):
                r = math.pow(r, 0.3)
            elif term in name:
                r = math.pow(r, 0.5)
            if r >= (1.0 - fuzziness):
                matches.append((field, min(r, 0.99)))

    return sorted(matches, key=lambda x: -x[1])
Beispiel #27
0
 def getPointDist(self, pt):
     
     assert(self.face is not None)
     
     # fist, get my position
     p = PoseStamped()
     
     p.header.frame_id = "base_link"
     p.header.stamp = rospy.Time.now() - rospy.Duration(0.5)
     
     p.pose.position.x = 0
     p.pose.position.y = 0
     p.pose.position.z = 0
     p.pose.orientation.x = 0
     p.pose.orientation.y = 0
     p.pose.orientation.z = 0
     p.pose.orientation.w = 1
     
     try:
         
         self._tf.waitForTransform(p.header.frame_id, self._robot_frame, p.header.stamp, rospy.Duration(2))
         p = self._tf.transformPose(self._robot_frame, p)
         
     except:
         
         rospy.logerr("TF error!")
         return None
     
     return sqrt(pow(p.pose.position.x - pt.point.x, 2) + pow(p.pose.position.y - pt.point.y, 2) + pow(p.pose.position.z - pt.point.z, 2))
Beispiel #28
0
    def test_math_functions(self):
        df = self.sc.parallelize([Row(a=i, b=2 * i) for i in range(10)]).toDF()
        from pyspark.sql import functions
        import math

        def get_values(l):
            return [j[0] for j in l]

        def assert_close(a, b):
            c = get_values(b)
            diff = [abs(v - c[k]) < 1e-6 for k, v in enumerate(a)]
            return sum(diff) == len(a)
        assert_close([math.cos(i) for i in range(10)],
                     df.select(functions.cos(df.a)).collect())
        assert_close([math.cos(i) for i in range(10)],
                     df.select(functions.cos("a")).collect())
        assert_close([math.sin(i) for i in range(10)],
                     df.select(functions.sin(df.a)).collect())
        assert_close([math.sin(i) for i in range(10)],
                     df.select(functions.sin(df['a'])).collect())
        assert_close([math.pow(i, 2 * i) for i in range(10)],
                     df.select(functions.pow(df.a, df.b)).collect())
        assert_close([math.pow(i, 2) for i in range(10)],
                     df.select(functions.pow(df.a, 2)).collect())
        assert_close([math.pow(i, 2) for i in range(10)],
                     df.select(functions.pow(df.a, 2.0)).collect())
        assert_close([math.hypot(i, 2 * i) for i in range(10)],
                     df.select(functions.hypot(df.a, df.b)).collect())
Beispiel #29
0
def checkio(strdata):
	strdata = strdata.lower()
	alpha = [ chr(x) for x in range( ord('a'), ord('z')+1) ]
	
	for i in range(2, 36):
		radix = i
		bPassCheck1 = True
		for j in range(0, len(strdata)):
			if strdata[j].isdigit() and int( strdata[j] ) < radix:
				continue
			elif strdata[j].isalpha() and (10 + ord(strdata[j]) -ord('a') )< radix:
				continue
			else:
				bPassCheck1 = False
				continue
		if bPassCheck1 == True:
			mysum = 0
			for k in range(0,len(strdata)):
				if strdata[k].isdigit():
					mysum = mysum + math.pow( radix,  len(strdata)-k-1)*int(strdata[k])
				elif strdata[k].isalpha():
					mysum = mysum + math.pow( radix,  len(strdata)-k-1)*int(ord(strdata[k])-ord('a')+10)
			if mysum%(radix-1) == 0:
				print(radix)
				return radix
	print(0)
	return 0
Beispiel #30
0
 def update(self,tNow,lon_int,lat_int,t,vel,h):
     # Compute how long it's been since the system updated
     dtReal = tNow - self.tLast
     # rejection criteria
     if self.gpsState.ready and (abs( 1.0e-7*float(lon_int)-self.gpsState.lon ) > 0.01 or abs( 1.0e-7*float(lat_int)-self.gpsState.lat ) > 0.01):
         self.tLast = tNow
         return
     if self.gpsState.ready==False:
         self.gpsState.update(lon_int,lat_int,t,vel,h)
         # initialize the filter
         xk0 = np.array([self.gpsState.x,self.gpsState.y,0.0,0.0,0.0,0.0]) # initial state
         Pk0 = np.diag([math.pow(filter_dynamics.sigma_gps,2.0),math.pow(filter_dynamics.sigma_gps,2.0),1.0,1.0,1.0,1.0]) # initial covariance
         self.EKF.init_P(xk0,Pk0,t)
     else:
         # update the raw GPS object
         self.gpsState.update(lon_int,lat_int,t,vel,h)
         # test that dt is not negative
         dt = t-self.EKF.t
         if dt>0 and dt<10.0*max([dtReal,1.0]):
             # propagate the filter to the current time
             self.EKF.propagateOde(dt)
             # update the filter
             self.EKF.update(t,np.array([self.gpsState.x,self.gpsState.y]),filter_dynamics.measurement,filter_dynamics.measurementGradient,filter_dynamics.Rkin)
         else:
             print("Reject for back in time: dt = %g, dtReal=%g" % (dt,dtReal))
             pass
     # if the filter state matches the reading well enough, use it
     '''
     if math.sqrt( np.sum(np.power(self.EKF.xhat[0:2]-np.array([self.gpsState.x,self.gpsState.y]),2.0)) ) < 10.0:
         # copy the filter state to local
         self.filterState[0:2] = self.EKF.xhat[0:2].copy()
         self.filterState[2] = np.sqrt( np.sum(np.power(self.EKF.xhat[2:4],2.0)) )
         # If we're moving, use the velocity to approximate the heading; else, use the GPS heading
         if self.filterState[2] > 1.0:
             self.filterState[3] = np.arctan2( self.EKF.xhat[3],self.EKF.xhat[2] )
         else:
             self.filterState[3] = self.gpsState.hdg
     else:
         self.filterState[0] = self.gpsState.x
         self.filterState[1] = self.gpsState.y
         self.filterState[2] = self.gpsState.v
         self.filterState[3] = self.gpsState.hdg
     '''
     self.filterState[0] = self.gpsState.x
     self.filterState[1] = self.gpsState.y
     self.filterState[2] = self.gpsState.v
     self.filterState[3] = self.gpsState.hdg
     # Debug test print of state
     #print("%12.7g,%8.4g,%8.4g" % (tNow,self.filterState[2],self.filterState[3]))
     # reset the filter if things look bad
     # are the covariance diagonals zero or nan?
     if (self.EKF.Pk[0,0]==0.0) or (self.EKF.Pk[1,1]==0.0) or (self.EKF.Pk[2,2]==0.0) or (self.EKF.Pk[3,3]==0.0) or (self.EKF.Pk[4,4]==0.0) or (self.EKF.Pk[5,5]==0.0) or (np.any(np.isnan(np.diag(self.EKF.Pk)))):
         # initialize the filter
         xk0 = np.array([self.gpsState.x,self.gpsState.y,0.0,0.0,0.0,0.0]) # initial state
         Pk0 = np.diag([math.pow(filter_dynamics.sigma_gps,2.0),math.pow(filter_dynamics.sigma_gps,2.0),1.0,1.0,1.0,1.0]) # initial covariance
         self.EKF.init_P(xk0,Pk0,t)
     # call the log
     self.logFun(t,tNow)
     # update the time tracker
     self.tLast = tNow
Beispiel #31
0
 def vect(_x, _y, _z):
     return int(
         math.sqrt(
             math.pow(_x - cX, 2 * x_mult) + math.pow(_y - cY, 2 * y_mult) +
             math.pow(_z - cZ, 2 * z_mult)))
Beispiel #32
0
# Введіть з клавіатури п'ять цілочисельних елементів масиву X. Виведіть на
# кран значення коріння і квадратів кожного з елементів масиву.
#licherep Artem
import math
import numpy as np

a = []
for i in range(5):
    b = []
    b.append(int(input("input: ")))  #ввод
    a.append(b)
c = np.array(a)
for i in range(5):
    print("квадратний корінь з числа: ", a[i], "буде:", math.sqrt(c[i]))
print(" ")
for i in range(5):
    print("квадоат з числа:", a[i], "буде:", math.pow(c[i], 2))
Beispiel #33
0
 def euclidean_distance(self, goal_pose):
     """Euclidean distance between current pose and the goal."""
     return sqrt(pow((goal_pose.x - self.pose.x), 2) +
                 pow((goal_pose.y - self.pose.y), 2))
Beispiel #34
0
def isCollision(enemyX, enemyY, bulletX, bulletY):
    distance = math.sqrt((math.pow(enemyX - bulletX, 2)) + (math.pow(enemyY - bulletY, 2)))
    if distance < 27:
        return True
    else:
        return False
Beispiel #35
0
def load_data(path="../data/transfer/", dataset="chn", preserve_order=1):
    """Load citation network dataset (cora only for now)"""

    print('Loading {} dataset...'.format(dataset))

    idx_features_labels = np.genfromtxt("{}{}.content".format(path, dataset),
                                        dtype=np.dtype(str))
    features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)
    labels = encode_onehot(
        idx_features_labels[:, -1])  # labels are at the end of each line
    #f = open("{}{}.multilabel".format(path, dataset))
    #multilabels =np.genfromtxt("{}{}.multilabel".format(path, dataset),
    #                           dtype=np.dtype(str))

    # build graph
    idx = np.array(idx_features_labels[:, 0], dtype=np.int32)
    idx_map = {j: i for i, j in enumerate(idx)}
    edges_unordered = np.genfromtxt("{}{}.cites".format(path, dataset),
                                    dtype=np.int32)
    edges = np.array(list(map(idx_map.get, edges_unordered.flatten())),
                     dtype=np.int32).reshape(edges_unordered.shape)
    adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),
                        shape=(labels.shape[0], labels.shape[0]),
                        dtype=np.float32)

    # build symmetric adjacency matrix
    adj = sp.coo_matrix(adj + adj.T.multiply(adj.T > adj) -
                        adj.multiply(adj.T > adj))
    for item in adj.__dict__.items():
        print(item)
    print(adj.col)

    edge_ret = []

    edge_weight = []

    node_weight = [0.0 for i in range(0, len(idx))]

    if preserve_order == 1:
        adj_pres = adj
    else:
        adj_pres = sp.coo_matrix(adj**2)

    # sampling weight
    for i in range(0, len(adj.data)):
        edge_ret.append((adj_pres.row[i], adj_pres.col[i]))
        edge_weight.append(float(adj_pres.data[i]))
        node_weight[adj.row[i]] += adj.data[i]

    features = normalize(features)
    adj = adj + sp.eye(adj.shape[0])
    D = sp.coo_matrix([[
        1.0 / math.sqrt(node_weight[j]) if j == i else 0
        for j in range(len(idx))
    ] for i in range(len(idx))])
    adj = D * adj * D

    idx_train = range(140)
    idx_val = range(200, 500)
    idx_test = range(500, 1500)

    features = torch.FloatTensor(np.array(features.todense()))
    labels = torch.LongTensor(np.where(labels)[1])
    adj = sparse_mx_to_torch_sparse_tensor(adj)

    idx_train = torch.LongTensor(idx_train)
    idx_val = torch.LongTensor(idx_val)
    idx_test = torch.LongTensor(idx_test)

    for i in range(0, len(node_weight)):
        node_weight[i] = math.pow(node_weight[i], 0.75)

    return adj, features, labels, idx_train, idx_val, idx_test, edge_ret, torch.tensor(
        edge_weight), torch.tensor(node_weight)  #, multilabels
Beispiel #36
0
 def parse_order(self, order, market=None):
     zeroExOrder = self.safe_value(order, 'zeroExOrder')
     id = self.safe_string(order, 'orderHash')
     if (id is None) and(zeroExOrder is not None):
         id = self.safe_string(zeroExOrder, 'orderHash')
     side = self.safe_string(order, 'side')
     type = self.safe_string(order, 'type')  # injected from outside
     timestamp = self.safe_integer(order, 'creationTimestamp')
     if timestamp != 'None':
         timestamp = int(timestamp / 1000)
     symbol = None
     baseId = self.safe_string(order, 'baseTokenAddress')
     quoteId = self.safe_string(order, 'quoteTokenAddress')
     marketId = None
     if baseId is not None and quoteId is not None:
         marketId = baseId + '/' + quoteId
     market = self.safe_value(self.markets_by_id, marketId, market)
     base = None
     if market is not None:
         symbol = market['symbol']
         base = market['base']
     baseDecimals = self.safe_integer(self.options['decimals'], base, 18)
     price = self.safe_float(order, 'price')
     filledAmount = self.fromWei(self.safe_string(order, 'filledAmount'), 'ether', baseDecimals)
     settledAmount = self.fromWei(self.safe_string(order, 'settledAmount'), 'ether', baseDecimals)
     confirmedAmount = self.fromWei(self.safe_string(order, 'confirmedAmount'), 'ether', baseDecimals)
     failedAmount = self.fromWei(self.safe_string(order, 'failedAmount'), 'ether', baseDecimals)
     deadAmount = self.fromWei(self.safe_string(order, 'deadAmount'), 'ether', baseDecimals)
     prunedAmount = self.fromWei(self.safe_string(order, 'prunedAmount'), 'ether', baseDecimals)
     amount = self.fromWei(self.safe_string(order, 'initialAmount'), 'ether', baseDecimals)
     filled = self.sum(filledAmount, settledAmount, confirmedAmount)
     remaining = None
     lastTradeTimestamp = None
     timeline = self.safe_value(order, 'timeline')
     trades = None
     status = None
     if timeline is not None:
         numEvents = len(timeline)
         if numEvents > 0:
             timelineEventsGroupedByAction = self.group_by(timeline, 'action')
             if 'error' in timelineEventsGroupedByAction:
                 status = 'failed'
             if 'filled' in timelineEventsGroupedByAction:
                 fillEvents = self.safe_value(timelineEventsGroupedByAction, 'filled')
                 numFillEvents = len(fillEvents)
                 lastTradeTimestamp = self.safe_integer(fillEvents[numFillEvents - 1], 'timestamp')
                 lastTradeTimestamp = lastTradeTimestamp if (lastTradeTimestamp is not None) else lastTradeTimestamp
                 trades = []
                 for i in range(0, numFillEvents):
                     trade = self.parse_trade(self.extend(fillEvents[i], {
                         'price': price,
                     }), market)
                     trades.append(self.extend(trade, {
                         'order': id,
                         'type': type,
                         'side': side,
                     }))
     cost = None
     if filled is not None:
         if remaining is None:
             if amount is not None:
                 remaining = amount - filled
         if price is not None:
             cost = filled * price
     fee = None
     feeCost = self.safe_string(order, 'feeAmount')
     if feeCost is not None:
         feeOption = self.safe_string(order, 'feeOption')
         feeCurrency = None
         if feeOption == 'feeInNative':
             if market is not None:
                 feeCurrency = market['base']
         elif feeOption == 'feeInZRX':
             feeCurrency = 'ZRX'
         else:
             raise NotSupported(self.id + ' encountered an unsupported order fee option: ' + feeOption)
         feeDecimals = self.safe_integer(self.options['decimals'], feeCurrency, 18)
         fee = {
             'cost': self.fromWei(feeCost, 'ether', feeDecimals),
             'currency': feeCurrency,
         }
     amountPrecision = market['precision']['amount'] if market else 8
     if remaining is not None:
         if status is None:
             status = 'open'
             rest = remaining - failedAmount - deadAmount - prunedAmount
             if rest < math.pow(10, -amountPrecision):
                 status = 'canceled' if (filled < amount) else 'closed'
     result = {
         'info': order,
         'id': id,
         'symbol': symbol,
         'timestamp': timestamp,
         'datetime': self.iso8601(timestamp),
         'lastTradeTimestamp': lastTradeTimestamp,
         'type': type,
         'side': side,
         'price': price,
         'cost': cost,
         'amount': amount,
         'remaining': remaining,
         'filled': filled,
         'status': status,
         'fee': fee,
         'trades': trades,
     }
     return result
Beispiel #37
0
 def iscollision(gloveX, gloveY, ballX, ballY):
     distance = math.sqrt((math.pow(gloveX - ballX, 2)) + (math.pow(gloveY - ballY, 2)))
     if distance < 32:
         return True
     else:
         return False
    data_s = de.Demode(QAM, symbol)  # 초기 심볼 위치

    for snr in range(SNR):

        symbol_y = sym.Addnoise(snr, symbol)  # 초기 심볼 + 노이즈
        # 초기화 부분
        position = np.zeros(symbol_num, int)  # 심볼의 사분면 위치를 담을 배열
        rsc_TakeCenter = [[0] * 4 for i in range(3)]

        start = timeit.default_timer()
        # Dist 부분
        for i in range(symbol_num):

            # dist 거리 재기
            for j in range(4):
                part_Real = math.pow(symbol_y[i].real - init_center[j].real, 2)
                part_Imag = math.pow(symbol_y[i].imag - init_center[j].imag, 2)
                dist[j][i] = math.sqrt(part_Real + part_Imag)
        stop = timeit.default_timer()

        for i in range(symbol_num):
            # mindist 부분 - 사분면을 구함
            temp = 0
            for j in range(4):
                if j == 0:
                    temp = dist[j][i]
                elif temp > dist[j][i]:
                    temp = dist[j][i]
            for k in range(4):
                if dist[k][i] == temp:
                    position[i] = k
Give me details of archival storage
What is the amount of archived data
'''

LEX_RESULT = {
    'dialogAction': {
        'type': 'Close',
        'fulfillmentState': 'Fulfilled',
        'message': {
            'contentType': 'PlainText',
            # 'content': '%s' <--- This is filled in the end
        }
    }
}

TB = math.pow(10, 12)
GB = math.pow(10, 9)
MB = math.pow(10, 6)
PRECISION = 1

ENDPOINT_ARCHIVAL_STORAGE = (
    'https://{0}/api/internal/stats/cloud_storage'
)

def human_readable_size(bytes):
    tb = None
    gb = None
    mb = None
    bytes = int(bytes)
    tb = round(bytes / TB, PRECISION)
    if not tb:
Beispiel #40
0
def convert_mb(kb, unit):
    UNITS = {"B": -2, "KB": -1, "MB": 0, "GB": 1, "TB": 2}
    assert unit in UNITS, ("%s not a valid unit, valid units are %s." %
                           (unit, list(UNITS.keys())))
    return int(old_div(float(kb), float(math.pow(1024, UNITS[unit]))))
Beispiel #41
0
def binomial_phi_inv(d, p, x):
    return (math.pow(x, 1/d) + p-1) / p
Beispiel #42
0
def d2(c1, vec):
    #get distance
    return math.pow(euclidean_distances([c1], [vec]),2)
Beispiel #43
0
def isCollison(enemyx, enemyy, bulletx, bullety):
    res = math.sqrt(math.pow(bulletx - enemyx, 2) + math.pow(bullety - enemyy, 2))
    if res < 27:
        return True
    else:
        return False
Beispiel #44
0
 def Ri(anchorNode):
     addsum = 0
     for i in range(len(anchorNode)):
         addsum += math.pow(anchorNode.coordinate[i], 2)
     return addsum
def isCollision(obstacleX, obstacleY, playerX, playerY):
    distance = math.sqrt((math.pow(obstacleX - playerX, 2)) + (math.pow(obstacleY - playerY, 2)))
    if distance < 28:
        return True
    else:
        return False
Beispiel #46
0
# -*- coding: utf-8 -*-
#Faça um programa que leia o comprimento do cateto oposto e do cateto adjacente de um triângulo,
# calcule e mostre o comprimento da hipotenusa
from math import sqrt, pow
print("     Calculo de Hipotenusa")
print("-----------------------------------")
a = float(input("Digite a medida do lado triângulo Retangulo: "))
b = float(input("Digite a medida do lado triângulo Retangulo: "))
hipotenusa = pow(a, 2) + pow(b, 2)
hipotenusa = float(sqrt(hipotenusa))
input("A hipotenusa é {:.2f}".format(hipotenusa))
Beispiel #47
0
def euclideanDistance(vect1, vect2):
    sum = 0
    for cont in vect1:
        sum += math.pow((vect1[cont] - vect2[cont]), 2)
    sum = math.sqrt(sum)
    return sum
Beispiel #48
0
import math
Numero = int(input("Digite  "))

if Numero > 0:
    print("Esse numero é PAR: {:.2f} ".format(math.sqrt(Numero)))
else:
    print("Numero Negativo: {:.2f}".format(math.pow(Numero,2)))

def rgb2hsi(image):
    img = np.copy(image).astype(np.float)
    img = img/255
    red = img[:,:,0]
    green = img[:,:,1]
    blue = img[:,:,2]
    
    theta = np.zeros((img.shape[0], img.shape[1]))
    H = np.zeros((img.shape[0], img.shape[1]))
    for y in range(img.shape[0]):
        for x in range(img.shape[1]):
            if(red[y, x] == green[y, x] == blue[y, x]):
                theta[y, x] = 0
                H[y, x] = theta[y, x]
            else:
                theta[y, x] = math.acos((0.5 * ((red[y, x] - green[y, x]) + (red[y, x] - blue[y, x]))) / math.pow((math.pow((red[y, x] - green[y, x]), 2) + ((red[y, x] - blue[y, x]) * (green[y, x] - blue[y, x]))), 0.5))
                theta[y, x] = np.degrees(theta[y, x])
                if blue[y, x] > green[y, x]:
                    H[y, x] = 360 - theta[y, x]
                else:
                    H[y, x] = theta[y, x]
    
    S = np.zeros((img.shape[0], img.shape[1]))
    for y in range(img.shape[0]):
        for x in range(img.shape[1]):
            if(red[y, x] == green[y, x] == blue[y, x] == 0):
                S[y, x] = 1
            else:
                S[y, x] = 1 - ((3/(red[y, x] + green[y, x] + blue[y, x])) * min(red[y, x], min(green[y, x], blue[y, x])))
    
    I = (red + green + blue)/3
      
    return np.dstack((H, S, I))
Beispiel #50
0
def CalcX(lista):
    x = 0
    for j in range(len(lista)):
        x += lista[j] * math.pow(2, -j - 1)
    return x
 def f(self, count):
     if count < 100:
         ratio = count / 100.0
         return math.pow(ratio, 0.75)
     return 1.0
def bin2dec(bin_list):
    return sum([bin_list[i]*pow(2,len(bin_list)-i-1) for i in range(len(bin_list)-1,-1,-1)])
Beispiel #53
0
def varianza(lista):
    sum = 0.0
    for i in range(0, len(lista)):
        sum = sum + math.pow((lista[i] - media(lista)), 2)
    return sum / (len(lista))
Beispiel #54
0
    def getSize(self):
        size = self.end - self.start

        return optivis.geometry.Coordinates(
            math.sqrt(math.pow(size.x, 2) + math.pow(size.y, 2)), 0)
def pack_texture(self, context):
    obj = bpy.context.active_object
    name = material_prefix + obj.name

    if obj.mode != 'OBJECT':
        bpy.ops.object.mode_set(mode='OBJECT')

    # Determine size
    size_pixel = 8
    size_square = math.ceil(
        math.sqrt(context.scene.texToolsSettings.color_ID_count))
    size_image = size_square * size_pixel
    size_image_pow = int(math.pow(2, math.ceil(math.log(size_image, 2))))

    # Maximize pixel size
    size_pixel = math.floor(size_image_pow / size_square)

    print("{0} colors = {1} x {1} = ({2}pix)  {3} x {3}  | {4} x {4}".format(
        context.scene.texToolsSettings.color_ID_count, size_square, size_pixel,
        size_image, size_image_pow))

    # Create image
    image = bpy.data.images.new(name,
                                width=size_image_pow,
                                height=size_image_pow)
    pixels = [None] * size_image_pow * size_image_pow

    # Black pixels
    for x in range(size_image_pow):
        for y in range(size_image_pow):
            pixels[(y * size_image_pow) + x] = [0, 0, 0, 1]

    # Pixels
    for c in range(context.scene.texToolsSettings.color_ID_count):
        x = c % size_square
        y = math.floor(c / size_square)
        color = utilities_color.get_color(c).copy()
        for i in range(3):
            color[i] = pow(color[i], 1.0 / gamma)

        for sx in range(size_pixel):
            for sy in range(size_pixel):
                _x = x * size_pixel + sx
                _y = y * size_pixel + sy
                pixels[(_y * size_image_pow) +
                       _x] = [color[0], color[1], color[2], 1]

    # flatten list & assign pixels
    pixels = [chan for px in pixels for chan in px]
    image.pixels = pixels

    # Set background image
    for area in bpy.context.screen.areas:
        if area.type == 'IMAGE_EDITOR':
            area.spaces[0].image = image

    # Edit mesh
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.mesh.select_mode(use_extend=False, use_expand=False, type='FACE')
    bpy.ops.mesh.select_all(action='SELECT')
    # bpy.ops.uv.smart_project(angle_limit=1)
    bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=0.0078)

    bm = bmesh.from_edit_mesh(bpy.context.active_object.data)
    uv_layers = bm.loops.layers.uv.verify()

    for face in bm.faces:
        index = face.material_index

        # Get UV coordinates for index
        x = index % size_square
        y = math.floor(index / size_square)

        x *= (size_pixel / size_image_pow)
        y *= (size_pixel / size_image_pow)
        x += size_pixel / size_image_pow / 2
        y += size_pixel / size_image_pow / 2

        for loop in face.loops:
            loop[uv_layers].uv = (x, y)

    # Remove Slots & add one
    bpy.ops.object.mode_set(mode='OBJECT')
    bpy.ops.uv.textools_color_clear()
    bpy.ops.object.material_slot_add()

    #Create material with image
    obj.material_slots[0].material = utilities_bake.get_image_material(image)

    #Display UVs
    bpy.ops.object.mode_set(mode='EDIT')

    # Switch textured shading
    for area in bpy.context.screen.areas:
        if area.type == 'VIEW_3D':
            for space in area.spaces:
                if space.type == 'VIEW_3D':
                    space.shading.type = 'MATERIAL'

    bpy.ops.ui.textools_popup(
        'INVOKE_DEFAULT',
        message="Packed texture with {} color IDs".format(
            context.scene.texToolsSettings.color_ID_count))
Beispiel #56
0
def calc_distance(a, b):
        return math.sqrt(math.pow(b.x - a.x, 2) + math.pow(b.y - a.y, 2) + math.pow(b.z - a.z, 2))
def mint(filename, contract, w3):
    url = "https://api.pinata.cloud/pinning/pinFileToIPFS"
    headers = {
        "pinata_api_key": os.getenv("PINATA_API_KEY"),
        "pinata_secret_api_key": os.getenv("PINATA_SECRET_API_KEY"),
    }
    files = {"file": open(filename, "rb")}
    response = requests.post(url, files=files, headers=headers, verify=False)

    asset_ipfs_hash = json.loads(response.content)["IpfsHash"]

    token_meta = {
        "asset_ipfs_hash": asset_ipfs_hash,
        "convenience_asset_url": f"https://ipfs.io/ipfs/{asset_ipfs_hash}",
    }
    token_meta_bytes = json.dumps(token_meta, indent=2).encode("utf-8")
    files = {"file": token_meta_bytes}
    response = requests.post(url, files=files, headers=headers, verify=False)
    json_ipfs_hash = json.loads(response.content)["IpfsHash"]

    token_uri = f"https://ipfs.io/ipfs/{asset_ipfs_hash}"
    metadata_uri = f"https://ipfs.io/ipfs/{json_ipfs_hash}"

    BLOCK_SIZE = 65536

    content_sha = sha256()
    with open(filename, "rb") as f:
        fb = f.read(BLOCK_SIZE)
        while len(fb) > 0:
            content_sha.update(fb)
            fb = f.read(BLOCK_SIZE)

    content_sha = content_sha.digest()
    metadata_sha = sha256(json.dumps(token_meta).encode("utf-8")).digest()

    st.text(content_sha)
    st.text("\n")
    st.text(metadata_sha)

    share = math.pow(10, 18)
    share = int(share * 100)
    zora_data = {
        "tokenURI": token_uri,
        "metadataURI": metadata_uri,
        "contentHash": content_sha,
        "metadataHash": metadata_sha,
    }
    zora_bidshares = {
        "prevOwner": {
            "value": 0
        },
        "creator": {
            "value": 0
        },
        "owner": {
            "value": share
        },
    }

    gas_estimate = contract.functions.mint(
        data=zora_data, bidShares=zora_bidshares).estimateGas()
    tx_hash = contract.functions.mint(data=zora_data,
                                      bidShares=zora_bidshares).transact()
    receipt = w3.eth.waitForTransactionReceipt(tx_hash)

    st.text(token_uri)
    st.text("\n")
    st.text(metadata_uri)

    st.text(zora_data)
    st.text("\n")
    st.text(zora_bidshares)

    st.text(gas_estimate)
    st.text("\n")
    st.text(tx_hash)
    st.text("\n")
    st.text(receipt)
Beispiel #58
0
          if level==3 or level ==4:
            virusX[i] += virusX_change[i]
            virusY[i] += virusY_change[i]
            if virusX[i] <= -20:
              virusX_change[i] = 4
            elif virusX[i] >= 736:
              virusX_change[i] = -4
            if virusY[i] <= 0:
              virusY_change[i] = 2
            elif virusY[i] >= 480:
              virusY[i] = 0
            virus(virusX[i],virusY[i],i)

      #level 3 boss fight
      if level == 3 and in_boss_fight == True:
        if (math.sqrt(math.pow(virus_bossX+270 - bullet2X, 2) + (math.pow(virus_bossY+240 - bullet2Y, 2))))< 120:
              score_value += 1
              bullet2Y = 480
              bullet2_state = "ready"  
        if (math.sqrt(math.pow(virus_bossX+270 - playerX, 2) + (math.pow(virus_bossY+240 - playerY, 2))))< 120:
              life_count -= 1
              if life_count == 0:
                gameover()
              playerY = playerY+100
        for i in range(num_of_enemies):
          #移動迷你病毒
          mini_virusX[i] += mini_virusX_change[i]
          mini_virusY[i] += mini_virusY_change[i]
          if mini_virusX[i] <= -50:
              mini_virusX_change[i] = random.randint(0, 11)
              mini_virusY_change[i] = 4
Beispiel #59
0
def run_first_length(img, row):
    global is_slope_1_bigger
    global is_slope_2_bigger
    global steps_delta
    global bright_pixels_delta

    global dark_pixels_delta
    global pixels_delta
    global img_size
    global extant_val
    global distance_ratio
    global image_mean
    # image1=io.imread(image_path)
    # plt.imshow(image1)
    # df=pd.read_csv(csv_path)
    # df_new=df[df.name_id.eq(int(image_number))]
    # table = df_new.drop(columns=['name_id']).to_numpy()
    # #print(table)
    # # list=list(df_new)
    # # print(list)
    # i=0
    # for row in table:
    #print(row)
    x1_vals = [row[0], row[2]]
    #print(x1_vals)
    y1_vals = [row[1], row[3]]
    x2_vals = [row[2], row[4]]
    y2_vals = [row[3], row[5]]
    x3_vals = [row[4], row[6]]
    y3_vals = [row[5], row[7]]
    x4_vals = [row[6], row[0]]
    y4_vals = [row[7], row[1]]

    # plt.plot(row[0], row[1], 'r.')
    # plt.plot(row[2], row[3], 'b.')
    # plt.plot(row[6], row[7], 'g.')
    # plt.plot(row[4], row[5], 'c.')
    dy1 = row[7] - row[1]
    dx1 = row[6] - row[0]
    dy2 = row[3] - row[1]
    dx2 = row[2] - row[0]
    distance1 = math.sqrt(math.pow(dx1, 2) + math.pow(dy1, 2))
    try:
        angle1 = dy1 / dx1
    except:
        return (45, 45)
    distance2 = math.sqrt(math.pow(dx2, 2) + math.pow(dy2, 2))
    try:
        angle2 = dy2 / dx2
    except:
        return (45, 45)
    if distance1 > distance2:
        car_len_slope = angle1
        car_width_slope = angle2
        car_len = distance1
        car_width = distance2
    else:
        car_len_slope = angle2
        car_width_slope = angle1
        car_len = distance2
        car_width = distance1

    middlex = row[8]
    middley = row[9]
    # plt.plot(middlex, middley , 'g.')
    #image = Image.open(image_path)
    image = img.convert('L')
    pixels = image.load()
    # print("pixels matrix is: ", pixels)
    reference_pixel = pixels_mean(pixels, middlex, middley, car_width_slope)

    stats = ImageStat.Stat(image).mean
    stats2 = ImageStat.Stat(image).median
    image_mean = stats2
    #
    # print("function mean return value: ", mean(pixels, middlex, middley, 10))
    # # img = np.array(image)
    # # img =  img_as_float(img)
    # print("the average value of all pixels is: ", stats)
    # print("the median value of all pixels is: ", stats2)
    #print("the width slop is: ", car_width_slope, " the len slope is: ", car_len_slope)
    # print("the middle pixel value is: ", reference_pixel)

    length_edges, pass_bbox_l = find_roof_edges(middlex, middley,
                                                reference_pixel, car_len_slope,
                                                car_width_slope, pixels, row)

    # print("the values after going through the length is: ", length_edges)

    tmp_y = (length_edges[0][1] + length_edges[1][1]) / 2
    tmp_x = (length_edges[0][0] + length_edges[1][0]) / 2
    # plt.plot(tmp_x, tmp_y, 'r.')

    if (length_edges[0][2] > reference_pixel
            and length_edges[1][2] < reference_pixel):
        if not pass_bbox_l[0]:
            repeat1, pass_bbox = find_roof_edges(length_edges[0][0],
                                                 length_edges[0][1],
                                                 length_edges[0][2],
                                                 car_len_slope,
                                                 car_width_slope, pixels, row)
        else:
            repeat1 = length_edges
        if not pass_bbox_l[1]:
            repeat2, pass_bbox = find_roof_edges(length_edges[1][0],
                                                 length_edges[1][1],
                                                 length_edges[1][2] + 13,
                                                 car_len_slope,
                                                 car_width_slope, pixels, row)
        else:
            repeat2 = length_edges

        if repeat1[0][2] > reference_pixel + 45:
            repeat3, pass_bbox = find_roof_edges(repeat1[0][0], repeat1[0][1],
                                                 repeat1[0][2], car_len_slope,
                                                 car_width_slope, pixels, row)

            tmp_y = (repeat3[0][1] + repeat2[1][1]) / 2
            tmp_x = (repeat3[0][0] + repeat2[1][0]) / 2
            # print("values after fixing the length repeat3: ", repeat3)
        else:
            tmp_y = (repeat1[0][1] + repeat2[1][1]) / 2
            tmp_x = (repeat1[0][0] + repeat2[1][0]) / 2

    elif length_edges[0][2] < reference_pixel and length_edges[1][
            2] > reference_pixel:
        if not pass_bbox_l[0]:
            repeat1, pass_bbox = find_roof_edges(length_edges[0][0],
                                                 length_edges[0][1],
                                                 length_edges[0][2],
                                                 car_len_slope,
                                                 car_width_slope, pixels, row)
        else:
            repeat1 = length_edges
        if not pass_bbox_l[1]:
            repeat2, pass_bbox = find_roof_edges(length_edges[1][0],
                                                 length_edges[1][1],
                                                 length_edges[1][2],
                                                 car_len_slope,
                                                 car_width_slope, pixels, row)
        else:
            repeat2 = length_edges

        if repeat2[1][2] > reference_pixel + 45:
            repeat3, _ = find_roof_edges(repeat2[1][0], repeat2[1][1],
                                         repeat2[1][2], car_len_slope,
                                         car_width_slope, pixels, row)
            # print("12222312312312312321321312", repeat3[1][1])
            tmp_y = (repeat3[1][1] + repeat1[0][1]) / 2
            tmp_x = (repeat3[1][0] + repeat1[0][0]) / 2
            # print("values after fixing the length repeat3: ", repeat3)
            # print("the tmp points are ", (tmp_x, tmp_y))
        else:
            tmp_y = (repeat1[0][1] + repeat2[1][1]) / 2
            tmp_x = (repeat1[0][0] + repeat2[1][0]) / 2
        # print("values after fixing the length repeat1: ", repeat1)
        # print("values after fixing the length repeat2: ", repeat2)


#===========================================================================================
# elif length_edges[0][2] > reference_pixel and length_edges[1][2] > reference_pixel:
#     if not pass_bbox_l[0]: repeat1, pass_bbox = find_roof_edges(length_edges[0][0], length_edges[0][1], length_edges[0][2], car_len_slope, car_width_slope)
#     else: repeat1 = length_edges
#     if not pass_bbox_l[1]: repeat2, pass_bbox = find_roof_edges(length_edges[1][0], length_edges[1][1], length_edges[1][2], car_len_slope, car_width_slope)
#     else: repeat2 = length_edges
#
#     tmp_y = (repeat1[0][1] + repeat2[1][1]) / 2
#     tmp_x = (repeat1[0][0] + repeat2[1][0]) / 2
#
#     print("values after fixing the length repeat1: ", repeat1)
#     print("values after fixing the length repeat2: ", repeat2)

#==============================================================
# print ("the points now are ", (tmp_x, tmp_y))
    new_ref_pixel = pixels_mean(pixels, tmp_x, tmp_y, car_len_slope)
    width_edges, pass_bbox_w = find_roof_edges(tmp_x, tmp_y, new_ref_pixel,
                                               car_width_slope, car_len_slope,
                                               pixels, row)
    # print(
    #     "======================================================================================="
    # )
    # print("values after going on the width of the car: ", width_edges, pass_bbox_w)
    # print("======================================================================================")

    # final_slope = (width_edges[1][1]-row[1])/(width_edges[1][0]-row[0])
    # print("the final slope is: ", final_slope)
    # print(row[0],row[1])
    # print(row[2],row[3])
    # print(row[6],row[7])
    if width_edges[0][2] > new_ref_pixel and width_edges[1][2] < new_ref_pixel:
        if pass_bbox_w[0] == 0:
            repeat1, pass_bbox = find_roof_edges(width_edges[0][0],
                                                 width_edges[0][1],
                                                 width_edges[0][2],
                                                 car_width_slope,
                                                 car_len_slope, pixels, row)
        else:
            repeat1 = width_edges
        if pass_bbox_w[1] == 0:
            repeat2, pass_bbox = find_roof_edges(width_edges[1][0],
                                                 width_edges[1][1],
                                                 width_edges[1][2],
                                                 car_width_slope,
                                                 car_len_slope, pixels, row)
        else:
            repeat2 = width_edges

        desired_y = (repeat1[0][1] + repeat2[1][1]) / 2
        desired_x = (repeat1[0][0] + repeat2[1][0]) / 2

        # print("after fixing the width: ", repeat1, pass_bbox_w)
        # print("after fixing the width: ", repeat2, pass_bbox_w)
        if repeat1[0][2] > new_ref_pixel + 45:
            repeat3, pass_bbox = find_roof_edges(repeat1[0][0], repeat1[0][1],
                                                 repeat1[0][2],
                                                 car_width_slope,
                                                 car_len_slope, pixels, row)

            desired_y = (repeat3[0][1] + repeat2[1][1]) / 2
            desired_x = (repeat3[0][0] + repeat2[1][0]) / 2
            # print("values after fixing the width repeat3: ", repeat3)
        else:
            desired_y = (repeat1[0][1] + repeat2[1][1]) / 2
            desired_x = (repeat1[0][0] + repeat2[1][0]) / 2
        # print("values after fixing the width repeat1: ", repeat1)
        # print("values after fixing the width repeat2: ", repeat2)

    elif (width_edges[0][2] < new_ref_pixel
          and width_edges[1][2] > new_ref_pixel):
        if pass_bbox_w[0] == 0:
            repeat1, pass_bbox = find_roof_edges(width_edges[0][0],
                                                 width_edges[0][1],
                                                 width_edges[0][2],
                                                 car_width_slope,
                                                 car_len_slope, pixels, row)
        else:
            repeat1 = width_edges
        if pass_bbox_w[1] == 0:
            repeat2, pass_bbox = find_roof_edges(width_edges[1][0],
                                                 width_edges[1][1],
                                                 width_edges[1][2],
                                                 car_width_slope,
                                                 car_len_slope, pixels, row)
        else:
            repeat2 = width_edges

        if repeat2[1][2] > new_ref_pixel + 45:
            repeat3, pass_bbox = find_roof_edges(repeat2[1][0], repeat2[1][1],
                                                 repeat2[1][2],
                                                 car_width_slope,
                                                 car_len_slope, pixels, row)

            desired_y = (repeat3[1][1] + repeat1[0][1]) / 2
            desired_x = (repeat3[1][0] + repeat1[0][0]) / 2
            # print("values after fixing the width repeat3: ", repeat3)
        else:
            desired_y = (repeat1[0][1] + repeat2[1][1]) / 2
            desired_x = (repeat1[0][0] + repeat2[1][0]) / 2
        # print("values after fixing the width repeat1: ", repeat1)
        # print("values after fixing the width repeat2: ", repeat2)
    else:
        desired_x = (width_edges[0][0] + width_edges[1][0]) / 2
        desired_y = (width_edges[0][1] + width_edges[1][1]) / 2

    # print(desired_x, desired_y)
    # plt.plot(desired_x, desired_y, 'y.')
    #plt.imshow(image, cmap='gray')
    #plt.show()
    return desired_x, desired_y
Beispiel #60
0
    def generateCity(self, *args):
        map_file = cmds.textField(self.widgets["osmFileTextField"], q = True, fi = True)
        winds_file = cmds.textField(self.widgets["wrfFileTextField"], q = True, fi = True)
        heights_file = cmds.textField(self.widgets["demFileTextField"], q = True, fi = True)
        jams_file = cmds.textField(self.widgets["jamsFileTextField"], q = True, fi = True)

        raw_wrf = cmds.checkBox(self.widgets["wrfCheckBox"], q=True, v=True)
        raw_dem = cmds.checkBox(self.widgets["demCheckBox"], q=True, v=True)

        if raw_wrf:
            if platform.system() == 'Windows':
                s = subprocess.check_output(["where", "python"], shell=True)
            else:
                s = subprocess.check_output(["which", "python"], shell=False)
            python_path = s.splitlines()[-1]
            script_dir = os.path.dirname(os.path.realpath(__file__))
            winds_file = subprocess.check_output([python_path, script_dir + "\NetCDF_converter.py", map_file, winds_file], shell=False).rstrip()

        if raw_dem:
            if platform.system() == 'Windows':
                s = subprocess.check_output(["where", "python"], shell=True)
            else:
                s = subprocess.check_output(["which", "python"], shell=False)
            python_path = s.splitlines()[-1]
            script_dir = os.path.dirname(os.path.realpath(__file__))
            heights_file = subprocess.check_output([python_path, script_dir + "\DEM_converter.py", map_file, heights_file], shell=False).rstrip()


        if cmds.objExists('city'):
            cmds.delete('city')

        def calc_emmiter_level(waypoints):
            if (jams_file == ""):
                return 0

            jams_data = open(jams_file, 'r')
            sum_jams_level = 0
            jams_points = 0

            shift_lat = -0.00766
            shift_lon = 0.006868

            for waypoint in waypoints:
                for line in jams_data:
                    tmp = line.split(' ')
                    lon = float(tmp[0]) - shift_lon
                    lat = float(tmp[1]) - shift_lat
                    if lat < minlat or lat > maxlat or lon < minlon or lon > maxlon:
                        continue
                    data = float(tmp[2])
                    jams_point = convert_coordinates(lon, lat)
                    dist = math.sqrt(math.pow(waypoint[0]-jams_point[0], 2)+math.pow(waypoint[2]-jams_point[2], 2))
                    if dist < (25.0/size_multiplier):
                        sum_jams_level += data
                        jams_points += 1

            if jams_points >= (len(waypoints) * 0.5):
                return 1.0*sum_jams_level/jams_points
            else:
                return 0

            jams_data.close()


        def convert_coordinates(lon, lat):
            centered_lat = (lat-minlat) - (maxlat-minlat)/2
            centered_lon = (lon-minlon) - (maxlon-minlon)/2
            normalized_lat = centered_lat * norm_lat
            normalized_lon = centered_lon * norm_lon
            return [normalized_lon, 0, -normalized_lat]

        #meters
        size_multiplier = float(cmds.textField(self.widgets["sizeMultTextField"], q = True, tx = True))
        emit_multiplier = float(cmds.textField(self.widgets["emitMultTextField"], q = True, tx = True))
        hasl = float(cmds.textField(self.widgets["haslTextField"], q = True, tx = True))

        xmlData = xml.dom.minidom.parse(map_file)

        points_ids = []
        points = []
        heights = []

        bounds = xmlData.getElementsByTagName("bounds")[0]
        minlat = float(bounds.getAttribute('minlat'))
        maxlat = float(bounds.getAttribute('maxlat'))
        minlon = float(bounds.getAttribute('minlon'))
        maxlon = float(bounds.getAttribute('maxlon'))

        dist_lon = self.coordinates_dist(minlon, minlat, maxlon, minlat)
        dist_lat = self.coordinates_dist(minlon, minlat, minlon, maxlat)

        norm_lat = (dist_lat/size_multiplier)/(maxlat-minlat)
        norm_lon = (dist_lon/size_multiplier)/(maxlon-minlon)

        #============================Get heights===================================
        heights_data = open(heights_file, 'r')

        rows = 0
        cols = 0
        start_lon = 0
        start_lat = 0
        delta_lon = 0
        delta_lat = 0

        heights_matrix = []

        for line in heights_data:
            tmp = line.strip().split(' ')

            if rows == 0:
                rows = float(tmp[0])
                cols = float(tmp[1])
            elif start_lon == 0:
                start_lon = float(tmp[0])
                start_lat = float(tmp[1])
            elif delta_lon == 0:
                delta_lon = float(tmp[0])
                delta_lat = float(tmp[1])
            else:
                row = []
                for cell in tmp:
                    row.append(int(cell)-hasl)
                heights_matrix.append(row)

        #==========================================================================

        maxprogress = 0
        ways = xmlData.getElementsByTagName('way')
        for way in ways:
            tags = way.getElementsByTagName('tag')
            for tag in tags:
                tag_type = str(tag.getAttribute('k'))
                if (tag_type == 'highway'):
                    subtype = str(tag.getAttribute('v'))
                    if not(subtype == 'pedestrian') and not(subtype == 'steps') and not(subtype == 'footway') and not(subtype == 'cycleway'):
                        maxprogress += 1
                if (tag_type == 'building'):
                    maxprogress += 1

        progress = 0
        cmds.progressWindow(title='Generating city', min = 0, max = maxprogress,  progress = progress, status = 'Processing nodes', isInterruptable = False)

        #============================Handle nodes==================================
        nodes = xmlData.getElementsByTagName('node')
        for node in nodes:
            lat = float(node.getAttribute('lat'))
            lon = float(node.getAttribute('lon'))

            if lat < minlat or lat > maxlat or lon < minlon or lon > maxlon:
                continue

            point = convert_coordinates(lon, lat)

            points_ids.append(int(node.getAttribute('id')))
            points.append(point)
            heights.append(heights_matrix[int(math.floor((lon-start_lon)/delta_lon))][int(math.floor((lat-start_lat)/delta_lat))])
        #==========================================================================

        #=============================Handle ways==================================
        roads = 0
        buildings = 0
        emitter = 0

        cmds.particle(n='nParticle')
        cmds.particle('nParticle', e=True, at='mass', order=0, fv=1e-5)
        cmds.setAttr('nParticleShape.lifespanMode', 2)
        cmds.setAttr('nParticleShape.lifespan', 6)
        cmds.setAttr('nParticleShape.lifespanRandom', 2)

        cmds.select('nParticleShape', r=True)
        cmds.addAttr(longName='betterIllumination', at='bool', defaultValue=False )
        cmds.addAttr(longName='surfaceShading', at='float', defaultValue=0, minValue=0, maxValue=1)
        cmds.addAttr(longName='threshold', at='float', defaultValue=0, minValue=0, maxValue=10)
        cmds.addAttr(longName='radius', at='float', defaultValue=1, minValue=0, maxValue=20)
        cmds.addAttr(longName='flatShaded', at='bool', defaultValue=False)

        cmds.setAttr('nParticleShape.particleRenderType', 8)
        cmds.setAttr('nParticleShape.radius', 0.06)

        cmds.setAttr('particleCloud1.transparency', 0.53, 0.53, 0.53, type='double3')
        cmds.setAttr('particleCloud1.color', 1.0, 0.0, 0.483, type='double3')
        cmds.setAttr('particleCloud1.incandescence', 1.0, 0.0, 0.850, type='double3')
        cmds.setAttr('particleCloud1.glowIntensity', 0.111)


        ways = xmlData.getElementsByTagName('way')
        for way in ways:
            waypoints = []
            heights_sum = 0
            nodes = way.getElementsByTagName('nd')
            tags = way.getElementsByTagName('tag')

            for node in nodes:
                ref = int(node.getAttribute('ref'))
                try:
                    index = points_ids.index(ref)
                except ValueError:
                    index = -1

                if index != -1:
                    waypoints.append(points[index])
                    heights_sum += heights[index]

            for tag in tags:
                tag_type = str(tag.getAttribute('k'))
                if tag_type == 'highway':
                    subtype = str(tag.getAttribute('v'))
                    if not(subtype == 'pedestrian') and not(subtype == 'steps') and not(subtype == 'footway') and not(subtype == 'cycleway'):
                        roads += 1
                        progress += 1
                        cmds.progressWindow(edit=True, progress = progress, status='Generating road: ' + str(roads))

                        lanes = 2
                        for tag in tags:
                            tag_type = str(tag.getAttribute('k'))
                            if tag_type == 'lanes':
                                lanes = float(str(tag.getAttribute('v')))

                        if len(waypoints) >= 2:
                            cmds.curve(n='pathcurve_' + str(roads), p=waypoints, d=1)
                            sx = waypoints[0][0]
                            sz = waypoints[0][2]
                            dx = waypoints[0][2]-waypoints[1][2]
                            dz = waypoints[1][0]-waypoints[0][0]
                            ln = math.sqrt(math.pow(2*dx, 2) + math.pow(2*dz, 2))
                            dx /= (ln*size_multiplier)/(3*lanes)
                            dz /= (ln*size_multiplier)/(3*lanes)
                            ln = 0

                            for i in range(0, len(waypoints)-2):
                                ln += math.trunc(math.sqrt(math.pow(waypoints[i+1][0]-waypoints[i][0], 2) + math.pow(waypoints[i+1][2]-waypoints[i][2], 2))) + 1
                            cmds.curve(n='extrudecurve_' + str(roads), p=[(sx-dx, 0, sz-dz), (sx+dx, 0, sz+dz)], d=1)
                            cmds.rebuildCurve('pathcurve_' + str(roads), rt=0, s=200)
                            cmds.nurbsToPolygonsPref(f=2, pt=1, ut=1, un=2, vt=1, vn=ln * 5 + 30)
                            cmds.extrude('extrudecurve_' + str(roads), 'pathcurve_' + str(roads), n='road_' + str(roads), et=2, po=1)
                            cmds.delete('extrudecurve_' + str(roads),)


                            emitter_level = calc_emmiter_level(waypoints)
                            if emitter_level > 0:
                                emitter += 1
                                cmds.select('pathcurve_' + str(roads), r=True)
                                cmds.move(0, 0.03, 0)
                                cmds.emitter(n='emitter_' + str(emitter), type='omni', r=emit_multiplier*emitter_level, spd=0.1, srn=0, sp=0)
                                cmds.connectDynamic('nParticle', em='emitter_' + str(emitter))


                            cmds.select('road_' + str(roads), r=True)
                            cmds.move(0, 0.004, 0)


                elif tag_type == 'building':
                    temp = str(tag.getAttribute('v'))
                    if temp == 'yes':
                        buildings += 1
                        progress += 1
                        cmds.progressWindow(edit=True, progress = progress, status='Generating building: ' + str(buildings))

                        if len(waypoints) >= 3:
                            cmds.polyCreateFacet(n='building_' + str(buildings), p=waypoints)
                            cmds.select('building_' + str(buildings), r=True)
                            normal = cmds.polyInfo(fn=True)[0].partition('0: ')[2].split(' ')[1]
                            if float(normal) < 0:
                                cmds.polyMirrorFace(direction=2, p=(0, 0, 0), mergeMode=0, worldSpace=1)
                                cmds.polyDelFacet('building_' + str(buildings) + '.f[0]')

                            avg_height = heights_sum / len(waypoints)

                            cmds.polyExtrudeFacet('building_' + str(buildings) + '.f[0]',  ltz=(1.0 * avg_height/size_multiplier))

                            cmds.select('building_' + str(buildings), r=True)

                            cmds.collision('building_' + str(buildings), 'nParticle')

        #==========================================================================

        #============================Handle winds==================================
        winds_data = open(winds_file, 'r')
        winds = 0
        cmds.progressWindow(edit=True, progress = progress, status='Setting winds')
        for line in winds_data:
            winds += 1

            tmp = line.split(' ')
            lon = float(tmp[0])
            lat = float(tmp[1])
            x = float(tmp[2])
            y = float(tmp[3])
            z = float(tmp[4])

            magn = math.sqrt(math.pow(x, 2) + math.pow(y, 2) + math.pow(z, 2))
            max_dist = self.coordinates_dist(0, 0, 0.006364, 0.006364)/size_multiplier
            volume_size = self.coordinates_dist(0, 0, 0.0045, 0.0045)/size_multiplier
            position = convert_coordinates(lon, lat)

            cmds.air(n='wind_' + str(winds), pos=position, wns=True, dx=x, dy=y, dz=z, m=magn, s=1, mxd=max_dist)
            cmds.setAttr('wind_' + str(winds) + '.volumeShape', 1)
            cmds.setAttr('wind_' + str(winds) + '.volumeOffsetY', 1)
            cmds.scale(volume_size, volume_size/2, volume_size, 'wind_' + str(winds))
            cmds.connectDynamic('nParticle', f='wind_' + str(winds))
            cmds.select(cl=True)
        #==========================================================================

        cmds.gravity(n='gravity', m=9.8*1e-5)
        cmds.connectDynamic('nParticle', f='gravity')
        cmds.polyPlane(n='ground', sx=(maxlon-minlon), sy=(maxlat-minlat), w=(maxlon-minlon)*norm_lon, h=(maxlat-minlat)*norm_lat)
        cmds.collision('ground', 'nParticle')

        cmds.select('building_*', r=True)
        cmds.select('road_*', tgl=True)
        cmds.select('ground', tgl=True)
        cmds.select('nParticle', tgl=True)
        cmds.editRenderLayerGlobals(currentRenderLayer='AOLayer')
        cmds.editRenderLayerMembers('AOLayer')

        cmds.select('road_*', r=True)
        cmds.group(n='roads')

        cmds.select('building_*', r=True)
        cmds.group(n='buildings')

        cmds.select('pathcurve_*', r=True)
        cmds.group(n='emitters')

        cmds.select('roads', r=True)
        cmds.select('buildings', tgl=True)
        cmds.select('emitters', tgl=True)
        cmds.select('nParticle', tgl=True)
        cmds.select('gravity', tgl=True)
        cmds.select('ground', tgl=True)
        cmds.select('wind_1', tgl=True)
        cmds.group(n='city')

        xmlData.unlink()
        winds_data.close()
        heights_data.close()

        if raw_wrf:
            os.remove(winds_file)

        if raw_dem:
            os.remove(heights_file)

        cmds.progressWindow(endProgress = True)