def ToDecDeg(self, d=0, m=0, s=0, ustring = False, max=180): """ DecDegrees = ToDecDeg(d=0, m=0, s=0) converts degrees, minutes, seconds to decimal degrees (returned as a Float). """ if m < 0 or s < 0: raise ValueError("Minutes and Seconds have to be positive") if m > 60.0 or s > 60.0: raise ValueError("Minutes and Seconds have to be between -180 and 180") if abs(d) > max: raise ValueError("Degrees have to be between -180 and 180") if signbit(d): Sign = -1 d = abs(d) else: Sign = 1 deg_has_fract = bool(math.modf(d)[0]) min_has_fract = bool(math.modf(m)[0]) if deg_has_fract and (m != 0.0 or s != 0.0): raise ValueError("degrees cannot have fraction unless both minutes" "and seconds are zero") if min_has_fract and s != 0.0: raise ValueError("minutes cannot have fraction unless seconds are zero") DecDegrees = Sign * (d + m/60.0 + s/3600.0) if ustring: return u"%.6f\xb0"%(DecDegrees) else: return DecDegrees
def arrival(self): """Calculates the estimated arrival time based on current speed - run as thread.""" # Loops until routing is turned off while self.route_mode == True: speed = round(self.current_status["speed"], 2) # Make sure we do not divide by zero if speed > 0: time_current = datetime.datetime.now() # Determine time required for whole route time_total = self.total_distance / speed time_total_min, time_total_hour = math.modf(time_total) time_total_min = round(time_total_min * 60) # Create a date/time object for ETA time_total = time_current + datetime.timedelta(hours=time_total_hour, minutes=time_total_min) self.total_eta = time_total.strftime("%Y-%m-%d %H:%M") # Determine time required for next point in route time_point = self.waypoint_calc["distance"] / speed time_point_min, time_point_hour = math.modf(time_point) time_point_min = round(time_point_min * 60) # Add a 0 if minutes are less then 10 if time_point_min < 10: time_point_min = "0" + str(time_point_min) # Remove decimal points self.waypoint_eta["hour"] = int(str(time_point_hour).replace(".0", "")) self.waypoint_eta["min"] = str(time_point_min).replace(".0", "") # Do not estimate times if speed is 0 else: self.total_eta = " --" self.waypoint_eta["hour"] = "--" self.waypoint_eta["min"] = "--" time.sleep(self.sleep_time["arrival"])
def hamilton_allocation(counts, alloc): """ Implements the Hamilton Method (Largest remainder method) to calculate integral ratios. (Like it is used in some elections.) counts -- list of integers ('votes per party') alloc -- total amount to be allocated ('total amount of seats') """ total_counts = sum(counts) quotas = [float(count) * alloc / total_counts for count in counts] fracts = [] for (i, fp) in enumerate(quotas): fracts.append((math.modf(fp)[0], i)) fracts.sort() fracts.reverse() results = [int(math.modf(quota)[1]) for quota in quotas] remainder = alloc - sum(results) for i in range(remainder): results[fracts[i][1]] += 1 return results
def setCoordinate(self, coordinate): self.coordinate = coordinate degree_fraction, degrees = math.modf(coordinate) degrees=int(degrees) decimal_minutes=abs(degree_fraction*60) minute_fraction, minutes = math.modf(decimal_minutes) minutes=int(minutes) decimal_seconds=minute_fraction*60 decString=(u"{0}".format(coordinate)) dmString=(u"{0}\u00b0 {1}'".format(degrees, decimal_minutes)) dmsString=(u"{0}\u00b0 {1}' {2}''".format(degrees, minutes, decimal_seconds)) print '***********************',coordinate,decString,dmString,dmsString if self.displayMode=='DEC': print 'DEC' self.setText(decString) elif self.displayMode=='DM': print 'DM' self.setText(dmString) elif self.displayMode=='DMS': print 'DMS' self.setText(dmsString) self.setToolTip(u"DEC: {0}\nDM: {1}\nDMS: {2}".format(decString,dmString,dmsString))
def __init__(self, degrees='none', sexagesimal='none', latitude=False): if degrees != 'none': # Find out if the angle is negative negative = degrees < 0 # Treat angle as positive degrees = np.abs(degrees) # Decompose angle into degrees, minutes, seconds m, d = math.modf(degrees) s, m = math.modf(m * 60.) s = s * 60. # Express degrees and minutes as integers d, m = int(round(d)), int(round(m)) # Put back minus sign if negative if negative: d, m, s = -d, -m, -s # Set angle to tuple of degrees/minutes/seconds self.angle = (d, m, s) elif sexagesimal != 'none': self.angle = sexagesimal # Whether to keep the angle between 0 and 360 or -90 and 90 self.latitude = latitude self.negative = False self._simplify()
def recalculate_coordinate(val, _as=None): """ Accepts a coordinate as a tuple (degree, minutes, seconds) You can give only one of them (e.g. only minutes as a floating point number) and it will be duly recalculated into degrees, minutes and seconds. Return value can be specified as 'deg', 'min' or 'sec'; default return value is a proper coordinate tuple. """ deg, min, sec = val # pass outstanding values from right to left min = (min or 0) + int(sec) / 60 sec = sec % 60 deg = (deg or 0) + int(min) / 60 min = min % 60 # pass decimal part from left to right dfrac, dint = math.modf(deg) min = min + dfrac * 60 deg = dint mfrac, mint = math.modf(min) sec = sec + mfrac * 60 min = mint if _as: sec = sec + min * 60 + deg * 3600 if _as == 'sec': return sec if _as == 'min': return sec / 60 if _as == 'deg': return sec / 3600 return deg, min, sec
def _resize_image(img, w_in, h_in): """Resize the image to the given height and width.""" imc, imh, imw = img.shape h_in = int(h_in) w_in = int(w_in) part = np.zeros((imc, imh, w_in)) resized = np.zeros((imc, h_in, w_in)) w_scale = (imw - 1) / (w_in - 1) h_scale = (imh - 1) / (h_in - 1) for k in range(imc): for j in range(imh): for c in range(w_in): if c == w_in - 1 or imw == 1: part[k][j][c] = img[k][j][imw - 1] else: fdx, idx = math.modf(c * w_scale) part[k][j][c] = (1 - fdx) * img[k][j][int(idx)] + \ fdx * img[k][j][int(idx) + 1] for k in range(imc): for j in range(h_in): fdy, idy = math.modf(j * h_scale) for c in range(w_in): resized[k][j][c] = (1 - fdy)*part[k][int(idy)][c] if (j == h_in - 1) or (imh == 1): continue for c in range(w_in): resized[k][j][c] += fdy * part[k][int(idy) + 1][c] return resized
def forward(self): """ Moves bullet forward, bounces on walls, deals damage on tank impact """ (vec_x, vec_y) = self.vector (debt_x, debt_y) = self.position_debt (fractional_x, integral_x) = math.modf(vec_x*3+debt_x) (fractional_y, integral_y) = math.modf(vec_y*3+debt_y) self.old_x = self.bullet.rect.x self.old_y = self.bullet.rect.y self.bullet.rect.x -= integral_x self.bullet.rect.y += integral_y tanks_hit = pygame.sprite.spritecollide(self.bullet, GAME_DATA.tanks, False) for tank in tanks_hit: tank.parent.damage(self.damage) self.destroy() walls_hit = pygame.sprite.spritecollide(self.bullet, GAME_DATA.walls, False) if walls_hit: diff_x = walls_hit[0].rect.centerx - self.bullet.rect.centerx diff_y = walls_hit[0].rect.centery - self.bullet.rect.centery if abs(diff_x) > abs(diff_y): self.vector = (lambda x: (-x[0], x[1]))(self.vector) else: self.vector = (lambda x: (x[0], -x[1]))(self.vector) self.bullet.rect.x = self.old_x self.bullet.rect.y = self.old_y self.position_debt = (fractional_x, fractional_y)
def _DateFrom360Day(JD): """ returns a 'datetime-like' object given Julian Day for a calendar where all months have 30 days. Julian Day is a fractional day with a resolution of approximately 0.1 seconds. """ if JD < 0: raise ValueError('Julian Day must be positive') #jd = int(360. * (year + 4716)) + int(30. * (month - 1)) + day (F, Z) = math.modf(JD) year = int((Z - 0.5) / 360.) - 4716 dayofyr = Z - (year + 4716) * 360 month = int((dayofyr - 0.5) / 30) + 1 day = dayofyr - (month - 1) * 30 + F # Convert fractions of a day to time (dfrac, days) = math.modf(day / 1.0) (hfrac, hours) = math.modf(dfrac * 24.0) (mfrac, minutes) = math.modf(hfrac * 60.0) (sfrac, seconds) = math.modf(mfrac * 60.0) microseconds = sfrac*1.e6 return datetime(year, month, int(days), int(hours), int(minutes), int(seconds), int(microseconds), -1, dayofyr)
def test_utime(self): # Test times arg being invalid. for junk in ('a', 1234.1234, (1, 2, 3), (1)): self.assertRaises(TypeError, self.vol.utime, '/path', junk) # Test times = None mock_glfs_utimens = Mock(return_value=1) mock_time = Mock(return_value=12345.6789) with patch("gluster.gfapi.api.glfs_utimens", mock_glfs_utimens): with patch("time.time", mock_time): self.vol.utime('/path', None) self.assertTrue(mock_glfs_utimens.called) self.assertTrue(mock_time.called) # Test times passed as arg mock_glfs_utimens.reset_mock() atime = time.time() mtime = time.time() with patch("gluster.gfapi.api.glfs_utimens", mock_glfs_utimens): self.vol.utime('/path', (atime, mtime)) self.assertTrue(mock_glfs_utimens.called) self.assertEqual(mock_glfs_utimens.call_args[0][1], b'/path') # verify atime and mtime self.assertEqual(mock_glfs_utimens.call_args[0][2][0].tv_sec, int(atime)) self.assertEqual(mock_glfs_utimens.call_args[0][2][0].tv_nsec, int(math.modf(atime)[0] * 1e9)) self.assertEqual(mock_glfs_utimens.call_args[0][2][1].tv_sec, int(mtime)) self.assertEqual(mock_glfs_utimens.call_args[0][2][1].tv_nsec, int(math.modf(mtime)[0] * 1e9))
def backward(self): """ Moves player forward if there is no obstacle ahead. :return: True if succeeded/ False if hit obstacle. """ (vec_x, vec_y) = self.moving['vector'] (debt_x, debt_y) = self.moving['position_debt'] if self.status['speed_bonus']: speed = self.status['speed'] + 1 else: speed = self.status['speed'] (fractional_x, integral_x) = math.modf(vec_x*speed+debt_x) (fractional_y, integral_y) = math.modf(vec_y*speed+debt_y) old_x = self.tank.rect.x old_y = self.tank.rect.y self.tank.rect.x += integral_x self.tank.rect.y -= integral_y obstacles_hit = pygame.sprite.spritecollide(self.tank, GAME_DATA.tanks, False) obstacles_hit += pygame.sprite.spritecollide(self.tank, GAME_DATA.walls, False) self.moving['position_debt'] = (fractional_x, fractional_y) if len(obstacles_hit) > 1: self.tank.rect.x = old_x self.tank.rect.y = old_y return False return True
def simplest_fraction_in_interval(x, y): """ Return the fraction with the lowest denominator in the interval [x, y]. """ # http://stackoverflow.com/questions/4266741/check-if-a-number-is-rational-in-python if x == y: # The algorithm will not terminate if x and y are equal. raise ValueError("Equal arguments.") elif x < 0 and y < 0: # Handle negative arguments by solving positive case and negating. return -simplest_fraction_in_interval(-y, -x) elif x <= 0 or y <= 0: # One argument is 0, or arguments are on opposite sides of 0, so # the simplest fraction in interval is 0 exactly. return Fraction(0) else: # Remainder and Coefficient of continued fractions for x and y. xr, xc = modf(1 / x) yr, yc = modf(1 / y) if xc < yc: return Fraction(1, int(xc) + 1) elif yc < xc: return Fraction(1, int(yc) + 1) else: return 1 / (int(xc) + simplest_fraction_in_interval(xr, yr))
def toDegreesMinutesSeconds(self): self.__NorthString = "" (decimal, integer) = math.modf(self.__North) if self.__North < 0: self.__NorthString += self.__LetterSouth decimal *= -1 integer *= -1 else: self.__NorthString += self.__LetterNorth (mdecimal, minteger) = math.modf(decimal*60.0) self.__NorthString += str(int(integer)) self.__NorthString += "° " self.__NorthString += str(int(minteger)) self.__NorthString += "' " self.__NorthString += str(mdecimal*60.0) self.__NorthString += "\"" self.__EastString = "" (decimal, integer) = math.modf(self.__East) if self.__East < 0: self.__EastString += self.__LetterWest decimal *= -1 integer *= -1 else: self.__EastString += self.__LetterEast (mdecimal, minteger) = math.modf(decimal*60.0) self.__EastString += str(int(integer)) self.__EastString += "° " self.__EastString += str(int(minteger)) self.__EastString += "' " self.__EastString += str(mdecimal*60.0) self.__EastString += "\"" return " ".join([self.__NorthString, self.__EastString])
def arrival(self): '''Calculates the estimated arrival time based on current speed - run as thread.''' #Loops until routing is turned off while self.mode == True: speed = round(self.cache.gps['speed'],2) #Make sure we do not divide by zero if speed > 0: time_current = datetime.datetime.now() #Determine time required for whole route time_total = self.total_distance / speed time_total_min, time_total_hour = math.modf(time_total) time_total_min = round(time_total_min*60) #Create a date/time object for ETA time_total = time_current + datetime.timedelta(hours=time_total_hour, minutes=time_total_min) self.total_eta = time_total.strftime("%Y-%m-%d %H:%M") #Determine time required for next point in route time_point = self.waypoint_calc['distance'] / speed time_point_min, time_point_hour = math.modf(time_point) time_point_min = round(time_point_min*60) #If time is too large to display properly if time_point_hour > 1000: self.waypoint_eta['hour'] = '1000' else: #Add a 0 if minutes are less then 10 if time_point_min < 10: time_point_min = '0' + str(time_point_min) #Remove decimal points self.waypoint_eta['hour'] = int(str(time_point_hour).replace('.0','')) self.waypoint_eta['min'] = str(time_point_min).replace('.0','') time.sleep(4) #Do not estimate times if speed is 0 else: self.total_eta = ' --' self.waypoint_eta['hour'] = '--' self.waypoint_eta['min'] = '--'
def decimal_to_base60(deci, precision=1e-8): """Converts decimal number into sexagesimal number parts. ``deci`` is the decimal number to be converted. ``precision`` is how close the multiple of 60 and 3600, for example minutes and seconds, are to 60.0 before they are rounded to the higher quantity, for example hours and minutes. """ sign = "+" # simple putting sign back at end gives errors for small # deg. This is because -00 is 00 and hence ``format``, # that constructs the delimited string will not add '-' # sign. So, carry it as a character. if deci < 0: deci = abs(deci) sign = "-" frac1, num = math.modf(deci) num = int(num) # hours/degrees is integer valued but type is float frac2, frac1 = math.modf(frac1 * 60.0) frac1 = int(frac1) # minutes is integer valued but type is float frac2 *= 60.0 # number of seconds between 0 and 60 # Keep seconds and minutes in [0 - 60.0000) if abs(frac2 - 60.0) < precision: frac2 = 0.0 frac1 += 1 if abs(frac1 - 60.0) < precision: frac1 = 0.0 num += 1 return (sign, num, frac1, frac2)
def solve(start, finish): """ as soon as you get to 2 different bits, from then on, bits will differ in the range break out of the while loop by setting idx=32 eg. 37 = 100001 63 = 111111 & = 100000 - first bits match, but as soon as they differ, we know there will be 0s in those positions somewhere in our range """ # if start with zero or numbers are different powers of 2, # return 0 if start == 0 or modf(log(start, 2))[1] != modf(log(finish, 2))[1]: return 0 # make a list of bit chars for each start and finish start_bin = dec_to_binary(start) finish_bin = dec_to_binary(finish) # result array holding '0's for now res = ['0' for _ in xrange(INT_LENGTH)] # starting from the first char idx = 0 while idx < INT_LENGTH: # compare if start_bin[idx] == finish_bin[idx]: res[idx] = start_bin[idx] idx += 1 continue else: idx = INT_LENGTH return int(''.join(res), 2)
def _calcNoTicks( self, interval, logdelta ): """Return the number of ticks with spacing interval*10^logdelta. Returns a tuple (noticks, minval, maxval). """ # store these for modification (if we extend bounds) minval = self.minval maxval = self.maxval # calculate tick spacing and maximum extension factor delta = interval * (10**logdelta) maxextend = (maxval - minval) * AxisTicks.max_extend_factor # should we try to extend to nearest interval*10^logdelta? if self.extendmin: # extend minval if possible if math.fabs( math.modf( minval / delta )[0] ) > 1e-8: d = minval - ( math.floor( minval / delta ) * delta ) if d <= maxextend: minval -= d if self.extendmax: # extend maxval if possible if math.fabs( math.modf( maxval / delta)[0] ) > 1e-8: d = ( (math.floor(maxval / delta)+1.) * delta) - maxval if d <= maxextend: maxval += d numticks = self._tickNums(minval, maxval, delta) return (numticks, minval, maxval)
def split_numbers(number): """ Split high precision number(s) into doubles. TODO: Consider the option of using a third number to specify shift. Parameters ---------- number: long double The input high precision number which is to be split Returns ------- number_I: double First part of high precision number number_F: double Second part of high precision number """ if isinstance(number, collections.Iterable): mods = [math.modf(n) for n in number] number_F = [f for f,_ in mods] number_I = [i for _,i in mods] else: number_F, number_I = math.modf(number) return np.double(number_I), np.double(number_F)
def create_speed_seq(file_, int_, frac_): ''' Create int sequence where each number represents count of lines to be added to gnuplot input status: finished return: list raise: None ''' from math import modf file_seq = list() frac_reminder = 0 if frac_ == 0: # If the speed is integer, we could just return the quotient and reminder and not whole list... file_seq = [int_ for i in range(0, int(file_['num_of_lines'] / int_))] if file_['num_of_lines'] % int_ != 0: # ... which would save some time && memory file_seq.append(file_['num_of_lines'] % int_) else: while sum(file_seq) != file_['num_of_lines']: to_append = int_ frac_reminder += frac_ if frac_reminder >= 1: frac_reminder_frac = modf(frac_reminder)[0] frac_reminder_natur = modf(frac_reminder)[1] frac_reminder -= frac_reminder_natur to_append += int(frac_reminder_natur) if sum(file_seq) + to_append <= file_['num_of_lines']: file_seq.append(to_append) else: file_seq.append(file_['num_of_lines'] - sum(file_seq)) return file_seq
def getCoordParts(ppos=[0.0,0.0]): #decompose fract / whole from particle position ppos_parts = [[0.0,0.0],[0.0,0.0]] #[fract,whole] for each x,y comp ppos_parts[0][0] = pm.modf(ppos[0])[0];ppos_parts[0][1] = pm.modf(ppos[0])[1] ppos_parts[1][0] = pm.modf(ppos[1])[0];ppos_parts[1][1] = pm.modf(ppos[1])[1] return ppos_parts
def dd_to_dms(degs): neg = degs < 0 degs = (-1) ** neg * degs degs, d_int = math.modf(degs) mins, m_int = math.modf(60 * degs) secs = 60 * mins return neg, d_int, m_int, secs
def do_lat_lon(self, words): if len(words[0]) == 0 or len(words[1]) == 0: # empty strings? return if words[0][-1] == "N": words[0] = words[0][:-1] words[1] = "N" if words[0][-1] == "S": words[0] = words[0][:-1] words[1] = "S" if words[2][-1] == "E": words[2] = words[2][:-1] words[3] = "E" if words[2][-1] == "W": words[2] = words[2][:-1] words[3] = "W" if len(words[0]): lat = string.atof(words[0]) frac, intpart = math.modf(lat / 100.0) lat = intpart + frac * 100.0 / 60.0 if words[1] == "S": lat = -lat (self.lat, self.LATLON) = self.update(self.lat, lat, self.LATLON) if len(words[2]): lon = string.atof(words[2]) frac, intpart = math.modf(lon / 100.0) lon = intpart + frac * 100.0 / 60.0 if words[3] == "W": lon = -lon (self.lon, self.LATLON) = self.update(self.lon, lon, self.LATLON)
def configcosfire1(img,params,x,y,sig): angle=np.linspace(1,360,360)*(math.pi/180); rho=[2,4,6,8] rho1=[0,2,4,6,8] max1=np.amax(img); asymparams={'sigma':sig,'0':[0,0],'2':[],'4':[],'6':[],'8':[]} for r in rho: for theta in angle: cnt=theta*180/math.pi x1=x+(r*math.cos(theta)) y1=y+(r*math.sin(theta)) x_1=math.modf(x1) y_1=math.modf(y1) #print(img[x_1,y1]) #print(x1,y1) if((x_1[0]==float(0)) & (y_1[0]==float(0))): if((img[x_1[1],y_1[1]]==43)or img[x_1[1],y_1[1]]==45 or img[x_1[1],y_1[1]]==42): asymparams[str(r)].append(theta-(math.pi/2)) asymparams['rho']=rho1 return(asymparams)
def getcolor(value, size): color = None if value == 0: color = scale[0] elif value >= size: color = scale[-1] else: if size > 1: details, low_bound = math.modf(value * len(scale) / float(math.log(size, 2))) else: details, low_bound = math.modf(value * len(scale)) low_bound = int(low_bound) if low_bound >= len(scale) - 1: color = scale[-1] else: min_scale = scale[low_bound] max_scale = scale[low_bound + 1] color = [] for c1, c2 in zip(min_scale, max_scale): if c1 == c2: color.append(c1) elif c1 < c2: color.append(c1 + int(details * (c2 - c1))) else: color.append(c1 - int(details * (c1 - c2))) return tuple(color)
def convertHHMMSSToTotalSeconds(inputTime): # the original input time is in the format hhmmss.xyz seconds = math.modf(inputTime / 100.0) # seconds is now a 2-tuple containing (.ssxyz, hhmm.) minutes = math.modf(seconds[1] / 100.0) # minutes is now a 2-tuple containing (.mm, hh) return (seconds[0] * 100.0) + ((minutes[0] * 100.0) * 60.0) + (minutes[1] * 3600.0)
def PRF2DET(flux,OBJx,OBJy,DATx,DATy,wx,wy,a,splineInterpolation): # trigonometry cosa = cos(radians(a)) sina = sin(radians(a)) # where in the pixel is the source position? PRFfit = zeros((size(DATy),size(DATx))) for i in range(len(flux)): FRCx,INTx = modf(OBJx[i]) FRCy,INTy = modf(OBJy[i]) if FRCx > 0.5: FRCx -= 1.0 INTx += 1.0 if FRCy > 0.5: FRCy -= 1.0 INTy += 1.0 FRCx = -FRCx FRCy = -FRCy # constuct model PRF in detector coordinates for (j,y) in enumerate(DATy): for (k,x) in enumerate(DATx): xx = x - INTx + FRCx yy = y - INTy + FRCy dx = xx * cosa - yy * sina dy = xx * sina + yy * cosa PRFfit[j,k] += PRFfit[j,k] + splineInterpolation(dy*wy,dx*wx) * flux[i] return PRFfit
def on_render(self, target): if self.roof: target.blit( self.roof, (0, 0), area=(target.get_width(), target.get_height() / 2)) if self.floor: target.blit(self.floor, (0, target.get_height() / 2), area=(get_target.width(), target.get_height() / 2)) self.screen_width, self.screen_height = target.get_width(), target.get_height() f = self.create_screen_func() # print(self.screen_width) for k in range(1, self.screen_width + 1, self.column_width): x_cam, y_cam = f(k/self.screen_width) p = self.get_obstacle_in_direction( (self.player.x, self.player.y), (x_cam, y_cam)) if p: x, y = p i, j = int( modf(x / BLOCK_WIDTH)[1]), int(modf(y / BLOCK_HEIGHT)[1]) height = self.calc_column_height((x, y)) if not self.fish_eye: x_base, y_base = self.player.camera_vector() c = ((x_cam - self.player.x) * x_base + (y_cam - self.player.y) * y_base) / (norm(x_base, y_base) * norm((x_cam - self.player.x), (y_cam - self.player.y))) height /= c pygame.draw.rect(target, self.world[j][i][1], (k, (self.screen_height - height) / 2, self.column_width, height))
def PRF2DET2(flux,OBJx,OBJy,DATx,DATy,splineInterpolation): # where in the pixel is the source position? PRFfit = zeros((size(DATy),size(DATx))) for i in range(len(flux)): FRCx,INTx = modf(OBJx[i]) FRCy,INTy = modf(OBJy[i]) if FRCx > 0.5: FRCx -= 1.0 INTx += 1.0 if FRCy > 0.5: FRCy -= 1.0 INTy += 1.0 FRCx = -FRCx FRCy = -FRCy # constuct model PRF in detector coordinates for (j,y) in enumerate(DATy): for (k,x) in enumerate(DATx): dy = y - INTy + FRCy dx = x - INTx + FRCx PRFfit[j,k] = PRFfit[j,k] + splineInterpolation(dy,dx) * flux[i] return PRFfit
def do_lat_lon(self, words): if words[0][-1] == 'N': words[0] = words[0][:-1] words[1] = 'N' if words[0][-1] == 'S': words[0] = words[0][:-1] words[1] = 'S' if words[2][-1] == 'E': words[2] = words[2][:-1] words[3] = 'E' if words[2][-1] == 'W': words[2] = words[2][:-1] words[3] = 'W' if len(words[0]): lat = string.atof(words[0]) frac, intpart = math.modf(lat / 100.0) lat = intpart + frac * 100.0 / 60.0 if words[1] == 'S': lat = -lat (self.lat, self.LATLON) = self.update(self.lat, lat, self.LATLON) if len(words[2]): lon = string.atof(words[2]) frac, intpart = math.modf(lon / 100.0) lon = intpart + frac * 100.0 / 60.0 if words[3] == 'W': lon = -lon (self.lon, self.LATLON) = self.update(self.lon, lon, self.LATLON)
def _format_degree(degree, latitude=True): lit = ["NS", "EW"][0 if latitude else 1][0 if degree > 0 else 1] degree = abs(degree) mint, stop = math.modf(degree) sec, mint = math.modf(mint * 60) return "%d %d' %s'' %s" % (stop, mint, locale.format('%0.2f', sec * 60), lit)
def load_image_file(self, filepath): """ Reads a single image file (e.g. a CBF or MCCD) and returns raw data, experiment information, and an image type (e.g. pickle, raw image, or none) :param img: path to image file :return: data: raw image data and experiment info img_type: which type of image this was, or None if not loaded """ error = None try: with util.Capturing() as junk_output: loaded_img = dxtbx.load(filepath) except Exception as e: error = 'IOTA IMPORTER ERROR: DXTBX failed! {}'.format(e) print(e) loaded_img = None # Extract image information if loaded_img is not None: raw_data = loaded_img.get_raw_data() detector = loaded_img.get_detector()[0] beam = loaded_img.get_beam() scan = loaded_img.get_scan() distance = detector.get_distance() pixel_size = detector.get_pixel_size()[0] overload = detector.get_trusted_range()[1] wavelength = beam.get_wavelength() beam_x = detector.get_beam_centre(beam.get_s0())[0] beam_y = detector.get_beam_centre(beam.get_s0())[1] if scan is None: timestamp = None else: msec, sec = math.modf(scan.get_epochs()[0]) timestamp = evt_timestamp((sec, msec)) # Assemble datapack data = dpack(data=raw_data, distance=distance, pixel_size=pixel_size, wavelength=wavelength, beam_center_x=beam_x, beam_center_y=beam_y, ccd_image_saturation=overload, saturated_value=overload, timestamp=timestamp) if scan is not None: osc_start, osc_range = scan.get_oscillation() if osc_start != osc_range: data['OSC_START'] = 0 #osc_start data['OSC_RANGE'] = 0 #osc_start data['TIME'] = scan.get_exposure_times()[0] # Populate image object information self.img_object.final['pixel_size'] = pixel_size self.img_object.final['img_size'] = (data['SIZE1'], data['SIZE2']) self.img_object.final['beamX'] = beam_x self.img_object.final['beamY'] = beam_y self.img_object.final['gain'] = detector.get_gain() self.img_object.final['distance'] = distance self.img_object.final['wavelength'] = wavelength else: data = None return data, error
def degtodm(self, angle): "Decimal degrees to GPS-style, degrees first followed by minutes." (fraction, integer) = math.modf(angle) return math.floor(angle) * 100 + fraction * 60
def deg_conv(num): mnt, deg = math.modf(float(num)) mnt = mnt * 100 / 60 return str(deg + mnt)
bologna = earth + Topos('43.1479 N', '12.1097 E') ##set the time interval (not used) ---> to be deleted #start_year=2007; #stop_year=2015; #months = 12*(stop_year-start_year) #define the time-structure ts = load.timescale() #set the time range t_start = ts.utc(2009, 1, 1, 0, 0, 0) t_stop = ts.utc(2015, 1, 1, 0, 0, 0) #getting total time to process (in adu - to be investigated) total_time_frac, total_time = math.modf(t_stop.tt - t_start.tt) array_index = 0 step = 3600 / 86400 #note: this is the moon-paper and analysis setting #step = 10 t_cursor = t_start from array import * zen_array = array('d') azi_array = array('d') azicorr_array = array('d') xstereo_array = array('d') ystereo_array = array('d') xlambert_array = array('d')
if (time_ns - t0) > duration * 1e9: break groundtruth = truth(float(row[0])) omega = np.array([row[1:4]], dtype=np.float64).T - groundtruth[-6:-3, None] acc = np.array([row[4:]], dtype=np.float64).T - groundtruth[-3:, None] acc = T_IMU_B.rotation.rotp(acc) omega = T_IMU_B.rotation.rotp(omega) # imu.append(np.vstack((omega, acc)).flatten().tolist()) # Write the IMU message to the bag msg = Imu() msg.header.frame_id = "body" msg.header.stamp = rospy.Time(int(math.modf(time_ns / 1e9)[1]), int(math.modf(time_ns / 1e9)[0] * 1e9)) msg.angular_velocity.x = omega[0, 0] msg.angular_velocity.y = omega[1, 0] msg.angular_velocity.z = omega[2, 0] msg.linear_acceleration.x = acc[0, 0] msg.linear_acceleration.y = acc[1, 0] msg.linear_acceleration.z = acc[2, 0] outbag.write('imu', msg, msg.header.stamp) # # T_NWU_IMU = Transform(Quaternion(np.array([groundtruth[4:8]]).T), np.array([groundtruth[1:4]]).T) # T_I_B = T_I_NWU * T_NWU_IMU * T_IMU_B # if i == 1: # T_I_B0 = Transform(Quaternion.from_euler(0, 0, T_I_B.rotation.euler[2,0]), T_I_B.translation) # # # Write the Associated Truth message to the bag
def float_to_time(float_hour): if float_hour == 24.0: return datetime.time.max return datetime.time( int(math.modf(float_hour)[1]), int(float_round(60 * math.modf(float_hour)[0], precision_digits=0)), 0)
import math a = math.modf(1.432) print(isinstance(a, tuple)) print(a)
def tick(self, dt): # print('########################') _start_t = time() self.root.ids.eps.text = 'EPS\n' self.root.ids.scores.text = 'Scores\n' self.root.ids.territories.text = 'Territories\n' self.root.ids.units.text = 'Units\n' self.root.ids.new_units.text = 'New Units\n' self.root.ids.max_pops.text = 'Max Pop\n' # Update Map _s = time() for (x, y), color in utils.territories_colors_from_updates( self.army_updates, self.players, self.territories, self.armies): i = (self.map_size[0] * (self.map_size[1] - y - 1) + x) * 4 self.map_px[i:i + 4] = array('B', color) self.map.blit_buffer(self.map_px, colorfmt='rgba', bufferfmt='ubyte') # print("Update map took:", time()-_s, "for", len(self.army_updates), "updates and", sum(len(armies) for armies in self.armies)) # Spawn player armies _s = time() for pid, player in enumerate(self.players): if not self.land[pid]: self.root.ids.max_pops.text += f"[color=%02x%02x%02x]0[/color]\n" % player.color self.root.ids.new_units.text += f"[color=%02x%02x%02x]0[/color]\n" % player.color continue land = self.players_scores[pid] armies = len(self.armies[pid]) max_pop = config.POP_BASE + log( 1 + land * config.POP_HEIGHT) * config.POP_WIDTH player.max_pop = max_pop self.root.ids.max_pops.text += f"[color=%02x%02x%02x]{int(max_pop)}[/color]\n" % player.color growth = max((max_pop - armies) * config.POP_GROWTH, 0) self.root.ids.new_units.text += f"[color=%02x%02x%02x]{round(growth, 3)}[/color]\n" % player.color excess, growth = modf(self.players_armies_excess[pid] + growth) self.players_armies_excess[pid] = excess for _ in range(int(growth)): x, y = random.choice(list(self.land[pid])) self.spawn_army(pid, x, y) # print("Spawn player armies took:", time()-_s) # Record History if self.army_updates: updates = [(int(pid), str(aid), origin, target) for pid, aid, origin, target in self.army_updates] self.history['history'].append(updates) _s = time() # Update players and get their movement orders army_updates = tuple(self.army_updates) self.army_updates.clear() total_moves = [] for pid, player in enumerate(self.players): if not self.armies[pid] and not self.land[pid]: self.root.ids.scores.text += f"[color=%02x%02x%02x]-[/color]\n" % player.color self.root.ids.territories.text += f"[color=%02x%02x%02x]-[/color]\n" % player.color self.root.ids.units.text += f"[color=%02x%02x%02x]-[/color]\n" % player.color self.root.ids.eps.text += f"[color=%02x%02x%02x]-[/color]\n" % player.color continue eps_start = time() moves = tuple(player.update(army_updates)) eps = time() - eps_start total_moves.extend([(pid, aid, target) for aid, target in moves]) self.eps[pid].append(1. / eps) eps = round(sum(self.eps[pid]) / len(self.eps[pid])) units_ = round( len(self.armies[pid]) + self.players_armies_excess[pid], 2) self.root.ids.scores.text += f"[color=%02x%02x%02x]{self.players_scores[pid]}[/color]\n" % player.color self.root.ids.territories.text += f"[color=%02x%02x%02x]{len(self.land[pid])}[/color]\n" % player.color self.root.ids.units.text += f"[color=%02x%02x%02x]{units_}[/color]\n" % player.color self.root.ids.eps.text += f"[color=%02x%02x%02x]{eps}[/color]\n" % player.color # print("Update players took:", time()-_s) _s = time() # Process player movement orders random.shuffle(total_moves) while total_moves: pid, aid, target = total_moves.pop(0) try: allied_coord = self.armies[pid][aid] except KeyError: continue # Happens if army was defeated before its move could be executed or player tried to cheat # Check if colonizing if target is None: x, y = allied_coord if self.territories[x, y, 1] == -1: # Colonize self.change_owner(x, y, pid) self.army_updates.append((pid, aid, allied_coord, None)) if config.SUCCESS_COLONIZING_CHANCE >= random.random(): # Colonized without issues, can move again self.army_updates.append( (pid, aid, None, allied_coord)) else: self.armies[pid].pop(aid) continue x, y = target terrain = self.territories[x, y, 0] if self.territories[allied_coord[0], allied_coord[1], 0] != terrain: speed = TERRAIN[terrain].get( ENTER_SPEED) or TERRAIN[terrain][SPEED] else: speed = TERRAIN[terrain][SPEED] speed = speed + self.army_speed_excess.get(aid, 0) self.army_speed_excess[aid], speed = modf(speed) if speed == 0: continue # Check if move is valid move_distance = abs(x - allied_coord[0]) + abs(y - allied_coord[1]) if move_distance != 1: raise ValueError( f"Player {pid} can't move army {aid} {move_distance} territories" ) owner = self.territories[x, y, 1] # Own territory or unoccupied -> simply move army if owner == pid: self.move_army(pid, aid, allied_coord, (x, y)) # Empty, occupied by enemy or stationed army else: # Stationed army player, owner or -1 (No owner) enemy_pid = next( (pid_ for pid_, armies_ in enumerate(self.armies) for aid_, pos_ in armies_.items() if aid_ != aid and pid_ != pid and pos_ == target), owner) allied_armies = [aid] for pid_, aid_, target_ in total_moves: if pid_ != pid or target_ != (x, y): continue allied_armies.append(aid_) if enemy_pid == -1: # No territory owner and no enemy army present self.move_army(pid, aid, allied_coord, target) continue else: enemy_armies = [ uid for uid, coord in self.armies[enemy_pid].items() if coord == (x, y) ] terrain = self.territories[allied_coord[0], allied_coord[1], 0] attacker_roll = sum( random.randint(0, config.BATTLE_MAX_ROLL) for _ in allied_armies) attacker_roll = round(attacker_roll * TERRAIN[terrain].get(ATTACK_MOD, 1)) terrain = self.territories[x, y, 0] defender_roll = (sum( random.randint(0, config.BATTLE_MAX_ROLL) for _ in enemy_armies)) defender_roll = round(defender_roll * TERRAIN[terrain].get(DEFENCE_MOD, 1.5)) if attacker_roll > defender_roll: # Win for attacker if enemy_armies: enemy_aid = enemy_armies.pop(0) self.army_updates.append( (enemy_pid, enemy_aid, (x, y), None)) self.armies[enemy_pid].pop(enemy_aid) if not enemy_armies: # Last army was defeated or none present self.move_army(pid, aid, allied_coord, (x, y)) else: # Win for defender (even if attacker and defender roll are the same) self.armies[pid].pop(aid) self.army_updates.append((pid, aid, allied_coord, None)) # print("Process player moves took:", time()-_s) # Check for hazardousness of current terrain type for pid, armies in enumerate(self.armies): for aid, (x, y) in list(armies.items()): if self.territories[x, y, 1] == pid: continue terrain = self.territories[x, y, 0] hazard = TERRAIN[terrain].get(HAZARD, DEFAULT_HAZARD) if random.random() < hazard: self.armies[pid].pop(aid) self.army_updates.append((pid, aid, (x, y), None)) self.tps.append(1. / (time() - _start_t)) self.root.ids.tps.text = str(round(sum(self.tps) / len(self.tps), 1)) self.root.ids.total_ticks.text = str( int(self.root.ids.total_ticks.text) + 1)
def testfunc( a: float, ) -> ty.NamedTuple("Output", [("fractional", float), ("integer", int)]): import math return math.modf(a)[0], int(math.modf(a)[1])
def CalcRadian(self, i): deg = int(math.modf(i)[1]) min = i - deg return (math.pi * (deg + 5 * min / 3.0) / 180.0)
def _parse_iso(timestamp): """Internal function for parsing a timestamp in ISO 8601 format""" timestamp = timestamp.strip() m = _iso8601_parser.match(timestamp) if not m: raise ValueError("Not a proper ISO 8601 timestamp!") year = int(m.group('year')) month = int(m.group('month')) day = int(m.group('day')) h, min, s, us = None, None, None, 0 frac = 0 if m.group('tzempty') == None and m.group('tzh') == None: raise ValueError("Not a proper ISO 8601 timestamp: " + "missing timezone (Z or +hh[:mm])!") if m.group('frac'): frac = m.group('frac') power = len(frac) frac = long(frac) / 10.0 ** power if m.group('hour'): h = int(m.group('hour')) if m.group('minute'): min = int(m.group('minute')) if m.group('second'): s = int(m.group('second')) if frac != None: # ok, fractions of hour? if min == None: frac, min = _math.modf(frac * 60.0) min = int(min) # fractions of second? if s == None: frac, s = _math.modf(frac * 60.0) s = int(s) # and extract microseconds... us = int(frac * 1000000) if m.group('tzempty') == 'Z': offsetmins = 0 else: # timezone: hour diff with sign offsetmins = int(m.group('tzh')) * 60 tzm = m.group('tzm') # add optional minutes if tzm != None: tzm = long(tzm) offsetmins += tzm if offsetmins > 0 else -tzm tz = _get_fixed_offset_tz(offsetmins) return datetime(year, month, day, h, min, s, us, tz)
def _adjust_replica2part2dev_size(self): """ Make sure that the lengths of the arrays in _replica2part2dev are correct for the current value of self.replicas. Example: self.part_power = 8 self.replicas = 2.25 self._replica2part2dev will contain 3 arrays: the first 2 of length 256 (2**8), and the last of length 64 (0.25 * 2**8). Returns a 2-tuple: the first element is a list of (partition, replicas) tuples indicating which replicas need to be (re)assigned to devices, and the second element is a count of how many replicas were removed. """ removed_replicas = 0 fractional_replicas, whole_replicas = math.modf(self.replicas) whole_replicas = int(whole_replicas) desired_lengths = [self.parts] * whole_replicas if fractional_replicas: desired_lengths.append(int(self.parts * fractional_replicas)) to_assign = defaultdict(list) if self._replica2part2dev is not None: # If we crossed an integer threshold (say, 4.1 --> 4), # we'll have a partial extra replica clinging on here. Clean # up any such extra stuff. for part2dev in self._replica2part2dev[len(desired_lengths):]: for dev_id in part2dev: dev_losing_part = self.devs[dev_id] dev_losing_part['parts'] -= 1 removed_replicas += 1 self._replica2part2dev = \ self._replica2part2dev[:len(desired_lengths)] else: self._replica2part2dev = [] for replica, desired_length in enumerate(desired_lengths): if replica < len(self._replica2part2dev): part2dev = self._replica2part2dev[replica] if len(part2dev) < desired_length: # Not long enough: needs to be extended and the # newly-added pieces assigned to devices. for part in xrange(len(part2dev), desired_length): to_assign[part].append(replica) part2dev.append(0) elif len(part2dev) > desired_length: # Too long: truncate this mapping. for part in xrange(desired_length, len(part2dev)): dev_losing_part = self.devs[part2dev[part]] dev_losing_part['parts'] -= 1 removed_replicas += 1 self._replica2part2dev[replica] = part2dev[:desired_length] else: # Mapping not present at all: make one up and assign # all of it. for part in xrange(desired_length): to_assign[part].append(replica) self._replica2part2dev.append( array('H', (0 for _junk in xrange(desired_length)))) return (list(to_assign.iteritems()), removed_replicas)
def suspend (timeout): a, b = math.modf (timeout) for i in range (int (b)): socketpool.noop () time.sleep (1) time.sleep (a)
from math import modf Found = False N = 997 # Because 999 * 999 = 998001, therefore we start from 997799 while not Found and N >= 100: Divis = 101 # We start dividing by 100 Palindrom = int(str(N) + str(N)[::-1]) # Make the Palindrom out of N. while Divis < 1000: Divis += 1 # Get the float value and the integer value of the division. (floatV, intV) = modf(Palindrom / Divis) if floatV == 0 and intV in range(100, 1000): Found = True break N -= 1 # This is the most optimal solution I could think of # given my current level of Math and Python experience. End = perf_counter() print("Result is equal to: ", max(res)) print("Time consumed: ", End-Start, "seconds.")
def solve_problem_intero(instanceProblem, iteration_manager): iteration = 0 model = cplex.Cplex() num_variables = instanceProblem.columns # si aggiungono variabili binarie al modello for j in range(num_variables): model.variables.add(names=['x' + str(j)], lb=[0.0], ub=[1.0]) # si aggiunge la funzione obiettivo al modello for j in range(num_variables): model.objective.set_linear([(j, float(instanceProblem.costs[j]))]) model.objective.set_sense(model.objective.sense.minimize) # si aggiungono i vincoli # prima si aggiungono i vincoli che sono piani di taglio if instanceProblem.cut_constraint_counter != 0: for i in range(instanceProblem.cut_constraint_counter): constraint = cplex.SparsePair( ind=[j for j in range(num_variables)], val=instanceProblem.matrix[i]) model.linear_constraints.add(lin_expr=[constraint], senses=['L'], rhs=[instanceProblem.b_vector[i]], names=['c' + str(i)]) # dopo si aggiungono i vincoli originali del problema for i in range(instanceProblem.cut_constraint_counter, instanceProblem.rows): constraint = cplex.SparsePair(ind=[j for j in range(num_variables)], val=instanceProblem.matrix[i]) model.linear_constraints.add(lin_expr=[constraint], senses=['G'], rhs=[instanceProblem.b_vector[i]], names=['c' + str(i)]) model.write("./formulazione.lp") model.solve() model.solution.write("./soluzione.lp") opt_value = str(model.solution.get_objective_value()) print("\nValore ottimo della funzione obiettivo: " + str(model.solution.get_objective_value())) instanceProblem.optimal_solution.append(float(opt_value)) iteration += 1 # creiamo la disequazione per effettuare il cutting plane, se necessario # la posizione j occupata in basis_variables_indexes dalla variabile in base con valore ottimo # frazionario, corrisponde al numero di riga del tableau (e quindi all'indice del vincolo) da # considerare per il taglio. In optimal_values_basis_variables alla medesima posizione j si trova il # corrispondente valore ottimo del rilassamento lineare della variabile in base considerata optimal_values_basis_variables = model.solution.basis.get_header()[ 1] # valori ottimi delle variabili in base basis_variables_indexes = model.solution.basis.get_header()[ 0] # indici delle variabili in base create_cut_constraint = False # rappresenta l'indice della riga del tableau finale considerata per il taglio cut_constraint_index = 0 for j in range(len(basis_variables_indexes)): # se l'indice della variabile in base è >= 0 è una variabile strutturale, se l'indice è < 0 è una variabile di # slack o di surplus if basis_variables_indexes[j] >= 0: # con 0 selezioniamo la parte frazionaria double_part = math.modf(optimal_values_basis_variables[j])[0] # selezioniamo come dizionario per il taglio quello che risulta corrispondere alla prima variabile # frazionaria della soluzione ottima del rilassamento lineare if double_part != 0.0: create_cut_constraint = True cut_constraint_index = j break if create_cut_constraint: cut_constraint_coefficients = model.solution.advanced.binvarow( cut_constraint_index) for j in range(num_variables): int_part = math.floor(cut_constraint_coefficients[j]) cut_constraint_coefficients[j] = int_part # ora che abbiamo tutti i coefficienti ed il termine noto interi, possiamo aggiungerli al modello instanceProblem.rows = instanceProblem.rows + 1 # si crea una matrice rows x columns tutta settata a 0 new_matrix = [[0] * num_variables for i in range(instanceProblem.rows)] # si aggiunge alla matrice il nuovo vincolo di cutting plane new_matrix[0] = cut_constraint_coefficients # si aggiungono alla matrice i vincoli iniziali for i in range(instanceProblem.rows - 1): new_matrix[i + 1] = instanceProblem.matrix[i] # si crea un nuovo vettore b tutto settato a 1 new_b_vector = [1.0] * instanceProblem.rows # si aggiunge al vettore b dei termini noti il nuovo termine noto dato dalla parte intera del valore ottimo # della variabile del vincolo selezionato per il taglio new_b_vector[0] = math.floor( optimal_values_basis_variables[cut_constraint_index]) # si aggiungono al vettore b i termini noti originali più quelli dei tagli precedenti for i in range(instanceProblem.rows - 1): new_b_vector[i + 1] = instanceProblem.b_vector[i] # si incrementa di 1 il contatore dei vincoli che sono piani di taglio instanceProblem.cut_constraint_counter = instanceProblem.cut_constraint_counter + 1 instanceProblem.matrix = new_matrix instanceProblem.b_vector = new_b_vector # controllo del numero di righe della matrice: se è pari a 1000 l'algoritmo si interrompe (causa versione # free cplex) if instanceProblem.rows == 1000: return None # impostiamo i valori nell'itaration mangager e verifichiamo se ci sono le condizioni per contiuare le # iterazioni last_objective_function_value = model.solution.get_objective_value() previous_objective_function_value = iteration_manager.last_objective_function_value if previous_objective_function_value != 0: difference_percent = ((last_objective_function_value - previous_objective_function_value) / previous_objective_function_value) * 100 if difference_percent >= iteration_manager.percent_limit: iteration_manager.last_objective_function_value = last_objective_function_value iteration_manager.is_difference_limit = False instanceProblem.num_try += 1 solve_problem_intero(instanceProblem, iteration_manager) elif iteration_manager.is_difference_limit: return None else: iteration_manager.last_objective_function_value = last_objective_function_value iteration_manager.is_difference_limit = True instanceProblem.num_try += 1 solve_problem_intero(instanceProblem, iteration_manager) else: iteration_manager.last_objective_function_value = last_objective_function_value solve_problem_intero(instanceProblem, iteration_manager) else: return None
''' given a positive number print its fractional part ''' import math user_input = float(input("enter any number:")) fractional_part = math.modf(user_input) print(fractional_part)
def toHWU(name,t): if (name == "Bendchi2") | (name == "Chi2rphi") | (name =="Chi2rz"): return np.digitize(t,TrackWord_config[name]["bins"],right=True)-1 else: import math '''Convert a track coordinate to Hardware Units''' intpart = TrackWord_config[name]['split'][1] n_bits = TrackWord_config[name]['split'][0] if TrackWord_config[name]['Signed']: signbit = np.signbit(t) if signbit: sign = -1 else: sign = 1 n_bits -= 1 intnbins = 2**(intpart) -1 fracnbins = 2**(n_bits-intpart) -1 if intpart > 0: t = abs(t) fractional,integer = math.modf(t) tmin = 0 tmax = TrackWord_config[name]['max'] x = tmax if integer > tmax else integer x = tmin if integer < tmin else x # Get the bin index x = (x - tmin) / ((tmax - tmin) / intnbins) if name=="Z0": x = x y = np.copysign((fractional * fracnbins) ,sign) else: x = np.copysign(x,sign) y = fractional * fracnbins return round(x),round(y) else: tmin = TrackWord_config[name]['min'] tmax = TrackWord_config[name]['max'] x = tmax if t > tmax else t x = tmin if t < tmin else x # Get the bin index x = (x - tmin) / ((tmax - tmin) / fracnbins) if TrackWord_config[name]['Signed']: t = abs(t) tmin = 0 tmax = TrackWord_config[name]['max'] x = tmax if t > tmax else t x = tmin if t < tmin else x # Get the bin index x = (x - tmin) / ((tmax - tmin) / fracnbins) x = np.copysign(x,sign) return round(x)
def stampconv(cls, pytime): sec, usec = modf(pytime) sec = int(sec) usec = int(usec // 10 ** (int(log(usec, 10)) - 6 + 1)) return sec, usec
''' abs(x) 返回数字的绝对值,如abs(-10) 返回 10 ceil(x) 返回数字的上入整数,如math.ceil(4.1) 返回 5 exp(x) 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045 fabs(x) 返回数字的绝对值,如math.fabs(-10) 返回10.0 floor(x) 返回数字的下舍整数,如math.floor(4.9)返回 4 log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0 log10(x) 返回以10为基数的x的对数,如math.log10(100)返回 2.0 max(x1, x2,...) 返回给定参数的最大值,参数可以为序列。 min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。 modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。 pow(x, y) x**y 运算后的值。 round(x [,n]) 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。 sqrt(x) 返回数字x的平方根。 ''' import math print(abs(-10)) #返回绝对值 print(math.ceil(4.5)) #向上取整 print(math.exp(1)) #e的x次幂 print(math.fabs(-10)) #返回浮点数绝对值 print(math.floor(5.9)) #向下取整 print(math.log(100, 10)) #以10为底100的对数 print(math.log10(100)) #以10为底100的对数 print(max(1, 6, -1, -2.2, 0, 22 / 3)) #返回最大值 print(min(1, 6, -1, -2.2, 0, 22 / 3)) #返回最小值 print(math.modf(-2.2)) #返回整数部分和小数部分 print(pow(2, 3)) #2的3次幂 print(round(17 / 3, 2)) #四舍五入取2位小数 print(math.sqrt(2)) #返回2的平方根
def printTracks(event,filename,hwu=True,fwpt=True,LUTeta=True): import math sector_dict = {"0":[], "1":[], "2":[], "3":[], "4":[], "5":[], "6":[], "7":[], "8":[], "9":[],"10":[],"11":[],"12":[],"13":[],"14":[],"15":[],"16":[],"17":[]} f = open(filename, "w") f.write(str(repr('Sector').rjust(15)+repr('InvR').rjust(15)+repr('Phi').rjust(15)+ repr('TanLInt').rjust(15)+repr('TanLFrac').rjust(15)+repr('Z0Int').rjust(15)+ repr('Z0Frac').rjust(15)+repr('QMVA').rjust(15)+repr('OtherMVA').rjust(15)+ repr('D0Int').rjust(15)+repr('D0Frac').rjust(15)+repr('Chi2rphi').rjust(15)+ repr('Chi2rz').rjust(15)+repr('Bendchi2').rjust(15)+repr('Hitpattern').rjust(15)+ repr('Pt').rjust(15)+repr('Eta').rjust(15)+"\n")) if LUTeta: TanLUTf = open("TanLUT.txt") TanLUTlines = TanLUTf.readlines() total_tracks = 0 for trk_i in range(len(event["phiSector"])): for sector_i in range(9): if event["phiSector"][trk_i] == sector_i: if np.sign(event['eta'][trk_i]) == -1: sector_name = str(sector_i*2) else: sector_name = str(2*sector_i + 1) sector_dict[sector_name].append(trk_i) total_tracks += 1 list_iter = 0 while total_tracks > 0: for i in range(0,18): if len(sector_dict[str(i)]) > list_iter : trk_i = sector_dict[str(i)][list_iter-1] if hwu: if fwpt: pt = repr(event["fwPt"][trk_i]).rjust(15) else: pt = repr(toHWU("Pt",event["pt"][trk_i])).rjust(15) if LUTeta: tanl_int,tanl_frac = toHWU("TanL",event["TanL"][trk_i]) temp_str = TanLUTlines[int(tanl_frac)].split(",")[int(tanl_int)] if temp_str[0] == '(': int_eta = int(temp_str[1:]) elif temp_str[-1] == ')': int_eta = int(temp_str[:-1]) else: int_eta = int(temp_str) eta = repr(int_eta).rjust(15) else: eta = repr(toHWU("eta",event["eta"][trk_i])).rjust(15) f.write(str(repr(i).rjust(15)+ repr(toHWU("InvR",event["InvR"][trk_i])).rjust(15)+ repr(toHWU("Phi",event["Sector_Phi"][trk_i])).rjust(15)+ repr(toHWU("TanL",event["TanL"][trk_i])[0]).rjust(15)+ repr(toHWU("TanL",event["TanL"][trk_i])[1]).rjust(15)+ repr(toHWU("Z0",event["z0"][trk_i])[0]).rjust(15)+ repr(toHWU("Z0",event["z0"][trk_i])[1]).rjust(15)+ repr(toHWU("MVA1",event["MVA"][trk_i])).rjust(15)+ repr(toHWU("OtherMVA",event["otherMVA"][trk_i])).rjust(15)+ repr(toHWU("D0",event["d0"][trk_i])[0]).rjust(15)+ repr(toHWU("D0",event["d0"][trk_i])[1]).rjust(15)+ repr(toHWU("Chi2rphi",event["chi2rphi"][trk_i])).rjust(15)+ repr(toHWU("Chi2rz",event["chi2rz"][trk_i])).rjust(15)+ repr(toHWU("Bendchi2",event["bendchi2"][trk_i])).rjust(15)+ repr(toHWU("Hitpattern",event["hitpattern"][trk_i])).rjust(15)+ pt+ eta+"\n")) total_tracks -= 1 else: f.write(str(repr(i).rjust(10)[:10]+" "+ repr(event["InvR"][trk_i]).rjust(12)[:12]+" "+ repr(event["Sector_Phi"][trk_i]).rjust(12)[:12]+" "+ repr(math.modf(event["TanL"][trk_i])[1]).rjust(12)[:12]+" "+ repr(math.modf(event["TanL"][trk_i])[0]).rjust(12)[:12]+ " "+ repr(math.modf(event["z0"][trk_i])[1]).rjust(12)[:12]+" "+ repr(math.modf(event["z0"][trk_i])[0]).rjust(12)[:12]+" "+ repr(event["MVA"][trk_i]).rjust(12)[:12]+" "+ repr(event["otherMVA"][trk_i]).rjust(12)[:12]+" "+ repr(math.modf(event["d0"][trk_i])[1]).rjust(12)[:12]+" "+ repr(math.modf(event["d0"][trk_i])[0]).rjust(12)[:12]+" "+ repr(event["chi2rphi"][trk_i]).rjust(12)[:12]+" "+ repr(event["chi2rz"][trk_i]).rjust(12)[:12]+" "+ repr(event["bendchi2"][trk_i]).rjust(12)[:12]+" "+ repr(event["hitpattern"][trk_i]).rjust(12)[:12]+" "+ repr(event["pt"][trk_i]).rjust(12)[:12]+" "+ repr(abs(event["eta"][trk_i])).rjust(12)[:12]+"\n")) total_tracks -= 1 f.write(str("=================================================================\n")) list_iter += 1 f.close() TanLUTf.close()
def nsbh_population(rate, t_min, t_max, f_online, d_min, d_max, h_0,\ q_0, m_min_1, m_max_1, m_mean_1, m_std_1, m_min_2, \ m_max_2, m_mean_2, m_std_2, a_min_1, a_max_1, \ a_min_2, a_max_2, seed=None, sample_z=False, \ redshift_rate=False, uniform_bh_masses=False, \ uniform_ns_masses=False, fixed_count=None, \ aligned_spins=False): # constrained realisation if desired if seed is not None: npr.seed(seed) # first draw number of events: a Poisson process, with rate # given by the number of events per year per Gpc^3, the # duration of observations and the volume if fixed_count is None: if sample_z: z_min = d2z(d_min, h_0, q_0) z_max = d2z(d_max, h_0, q_0) vol = volume_z(z_max, z_min, h_0, q_0, \ redshift_rate=redshift_rate) else: vol = volume(d_max, d_min, h_0, q_0) n_per_sec = rate * vol / 365.0 / 24.0 / 3600.0 * f_online n_exp = n_per_sec * (t_max - t_min) n_inj = npr.poisson(n_exp) else: if sample_z: z_min = d2z(d_min, h_0, q_0) z_max = d2z(d_max, h_0, q_0) n_inj = fixed_count n_per_sec = fixed_count / (t_max - t_min) # draw merger times consistent with the expected rate. add a # check to ensure that the latest merger time is within the # observation window times = np.zeros(n_inj) times[0] = t_min times[-1] = t_max + 1.0 while times[-1] >= t_max: delta_times = npr.exponential(1.0 / n_per_sec, n_inj - 1) for i in range(1, n_inj): times[i] = times[i - 1] + delta_times[i - 1] # draw distances via an interpolated CDF if sample_z: z_grid = np.linspace(z_min, z_max, 10000) p_z_grid = volume_z(z_grid, z_min, h_0, q_0, \ redshift_rate=redshift_rate) / \ volume_z(z_max, z_min, h_0, q_0, \ redshift_rate=redshift_rate) interp = si.interp1d(p_z_grid, z_grid) redshifts = interp(npr.uniform(size=n_inj)) distances = z2d(redshifts, h_0, q_0) else: d_grid = np.linspace(d_min, d_max, 10000) p_d_grid = volume(d_grid, d_min, h_0, q_0) / \ volume(d_max, d_min, h_0, q_0) interp = si.interp1d(p_d_grid, d_grid) distances = interp(npr.uniform(size=n_inj)) # draw inclinations, colatitudes and longitudes incs = np.arccos(-npr.uniform(-1.0, 1.0, size=n_inj)) colats = np.arcsin(-npr.uniform(-1.0, 1.0, size=n_inj)) longs = npr.uniform(0.0, 2.0 * np.pi, size=n_inj) # draw masses if uniform_bh_masses: m_1s = npr.uniform(m_min_1, m_max_1, size=n_inj) else: dist = ss.truncnorm((m_min_1 - m_mean_1) / m_std_1, \ (m_max_1 - m_mean_1) / m_std_1, \ loc=m_mean_1, scale=m_std_1) m_1s = dist.rvs(n_inj) if uniform_ns_masses: m_2s = npr.uniform(m_min_2, m_max_2, size=n_inj) else: dist = ss.truncnorm((m_min_2 - m_mean_2) / m_std_2, \ (m_max_2 - m_mean_2) / m_std_2, \ loc=m_mean_2, scale=m_std_2) m_2s = dist.rvs(n_inj) # now draw spins: isotropic in direction, uniform in magnitude spin_amps = npr.uniform(a_min_1, a_max_1, size=n_inj) spin_colats = np.arccos(-npr.uniform(-1.0, 1.0, size=n_inj)) spin_longs = npr.uniform(0.0, 2.0 * np.pi, size=n_inj) a_1_xs = spin_amps * np.sin(spin_colats) * np.cos(spin_longs) a_1_ys = spin_amps * np.sin(spin_colats) * np.sin(spin_longs) a_1_zs = spin_amps * np.cos(spin_colats) if aligned_spins: a_1_xs = 0.0 a_1_ys = 0.0 spin_amps = npr.uniform(a_min_2, a_max_2, size=n_inj) spin_colats = np.arccos(-npr.uniform(-1.0, 1.0, size=n_inj)) spin_longs = npr.uniform(0.0, 2.0 * np.pi, size=n_inj) a_2_xs = spin_amps * np.sin(spin_colats) * np.cos(spin_longs) a_2_ys = spin_amps * np.sin(spin_colats) * np.sin(spin_longs) a_2_zs = spin_amps * np.cos(spin_colats) if aligned_spins: a_2_xs = 0.0 a_2_ys = 0.0 # finally draw isotropic coa_phase and polarization angles coa_phases = npr.uniform(0.0, 2.0 * np.pi, size=n_inj) pols = npr.uniform(0.0, 2.0 * np.pi, size=n_inj) # store in structured array dtypes = [('simulation_id', 'U256'), ('mass1', float), \ ('mass2', float), ('spin1x', float), ('spin1y', float), \ ('spin1z', float), ('spin2x', float), \ ('spin2y', float), ('spin2z', float), ('redshift', float), \ ('distance', float), ('inclination', float), \ ('coa_phase', float), ('polarization', float), \ ('longitude', float), ('latitude', float), \ ('geocent_end_time', int), ('geocent_end_time_ns', int)] data = np.empty((n_inj, ), dtype=dtypes) data['simulation_id'] = \ ['sim_inspiral:simulation_id:{:d}'.format(i) for i in range(n_inj)] data['mass1'] = m_1s data['mass2'] = m_2s data['spin1x'] = a_1_xs data['spin1y'] = a_1_ys data['spin1z'] = a_1_zs data['spin2x'] = a_2_xs data['spin2y'] = a_2_ys data['spin2z'] = a_2_zs data['redshift'] = redshifts data['distance'] = distances data['inclination'] = incs data['coa_phase'] = coa_phases data['polarization'] = pols data['longitude'] = longs data['latitude'] = colats data['geocent_end_time'] = [int(math.modf(t)[1]) for t in times] data['geocent_end_time_ns'] = [int(math.modf(t)[0] * 1e9) for t in times] return 1.0 / n_per_sec, data
#math module import math print(math.modf(10.21)) print(round(10.62, -2)) .1 + .1 + .1 == .3 round(.1, 1) + round(.1, 1) + round(.1, 1) == round(.3, 1) round(.1 + .1 + .1, 1) == round(.3, 1)
def toBinary(self): if self.value is True: return struct.pack('>ll', 0, 1) fr, sec = math.modf(self.value) return struct.pack('>ll', long(sec), long(fr * 1e9))
def microtime(get_as_float=False): if get_as_float: return time() else: return '%f %d' % modf(time())
def fixkey(self, key): len1 = float(len(self.list)) nkey = key - modf(key / len1)[1] * len1 if nkey < 0: nkey = len1 + nkey return int(nkey)
file = open(filename, "r") print("Reading file, this may take a while...") values = [float(i) for i in file.read().split(" ")] file.close() minimum = min(values) maximum = max(values) bits = 0 signed = 0 print("Minimum value is :", minimum) if (float(minimum) < 0 or float(maximum) < 0): print("This value is below zero, adding sign bit.") bits += 1 signed = 1 print("Maximum value is :", maximum) intpart = max(math.modf(abs(minimum))[1], math.modf(maximum)[1]) intbits = 0 if intpart == 0 else math.ceil(math.log2(intpart)) bits += intbits print("Integer part requires at least " + str(bits) + " bit(s) (sign included).") decbits = int( input("How many bits do you want to use for the decimal part?\n")) bits += decbits file = open(filename.strip(".nn") + (".txt"), "w+") bitstring = "" for value in values: temp = value bitstring = "" cnt = bits - signed
assert math.gcd(1, 1) == 1 assert math.gcd(-1, 1) == 1 assert math.gcd(1, -1) == 1 assert math.gcd(-1, -1) == 1 assert math.gcd(125, -255) == 5 assert_raises(TypeError, lambda: math.gcd(1.1, 2)) assert math.factorial(0) == 1 assert math.factorial(1) == 1 assert math.factorial(2) == 2 assert math.factorial(3) == 6 assert math.factorial(10) == 3628800 assert math.factorial(20) == 2432902008176640000 assert_raises(ValueError, lambda: math.factorial(-1)) assert math.modf(1.25) == (0.25, 1.0) assert math.modf(-1.25) == (-0.25, -1.0) assert math.modf(2.56) == (0.56, 2.0) assert math.modf(-2.56) == (-0.56, -2.0) assert math.modf(1) == (0.0, 1.0) assert math.modf(INF) == (0.0, INF) assert math.modf(NINF) == (-0.0, NINF) modf_nan = math.modf(NAN) assert math.isnan(modf_nan[0]) assert math.isnan(modf_nan[1]) assert math.fmod(10, 1) == 0.0 assert math.fmod(10, 0.5) == 0.0 assert math.fmod(10, 1.5) == 1.0 assert math.fmod(-10, 1) == -0.0 assert math.fmod(-10, 0.5) == -0.0
import math s = float(input()) s = math.modf(s) print(s)
def get_rate(self, cr, uid, ids, context={}): """Calculates the cost of shipping for USPS.""" data = self.browse(cr, uid, ids[0], context=context) if not (data['rate_selection'] == 'rate_request' and data['ship_company_code'] == 'fedex'): return super(shipping_rate_wizard, self).get_rate(cr, uid, ids, context) if context.get('active_model', False) == 'sale.order': # Are we running in test mode? test = data.logis_company.test_mode or False # Find the order we're calculating shipping costs on. sale_id = context.get('active_id', False) sale = self.pool.get('sale.order').browse(cr, uid, sale_id, context=context) # Get the shipper and recipient addresses for this order. address_from = sale.company_id.partner_id address_to = sale.partner_shipping_id or '' shipper = Address(address_from.name, address_from.street, address_from.city, address_from.state_id.code, address_from.zip, address_from.country_id.name, address2=address_from.street2) recipient = Address(address_to.name, address_to.street, address_to.city, address_to.state_id.code, address_to.zip, address_to.country_id.name, address2=address_to.street2) # Get the package's weight in ounces. weight = math.modf(sale.total_weight_net) ounces = (weight[1] * 16) + round(weight[0] * 16, 2) # Create the Package we are going to send. package = Package(str(ounces), data.fedex_container, data.fedex_length, data.fedex_width, data.fedex_height, mail_class=data.fedex_service_type) # Connect to the Endicia API. api = FedEx(fedex_api.get_config(cr, uid, sale, None)) # Ask Endicia what the cost of shipping for this package is. response = {'status': -1} try: response = api.rate([package], shipper, recipient) except Exception, e: self.write(cr, uid, [data.id], {'status_message': str(e)}, context=context) # Extract the shipping cost from the response, if successful. if response['status'] == 0: ship_method_ids = self.pool.get('shipping.rate.config').search( cr, uid, [('name', '=', data.fedex_service_type)], context=context) ship_method_id = (ship_method_ids and ship_method_ids[0]) or None for item in response['info']: if 'cost' in item: self.write(cr, uid, [data.id], { 'status_message': '', 'shipping_cost': item['cost'] }, context=context) sale.write({ 'shipcharge': float(item['cost']) or 0.00, 'ship_method_id': ship_method_id, 'status_message': '' }) return True
def __truediv__(self,numb): Fract,Integ=math.modf(1/numb) return DivStr(self.string*int(Integ)+self.string[0:int(len(self.string)*Fract)])