def runGrid(passCount, filename='lists/binaries2.dat'): ''' Wrapper function to run the binary mofel fitting grid. :param passCount: [in] The maximum amount of passes to run on the grid :param filename: [in] The filename of the file containing a list of targets field and APOGEE ID's to use ''' timer = Timer() timer.start() # Prep Grid locationIDs, apogeeIDs = np.loadtxt(filename, unpack=True, delimiter=',', dtype=str) targetCount = len(locationIDs) gridParams = [GridParam(locationIDs[i], apogeeIDs[i]) for i in range(targetCount)] minimizedVisitParams = [np.array([]) for i in range(targetCount)] # Use past results # checkPreviousData(gridParams) grid(passCount, gridParams, minimizedVisitParams) writeGridToFile(gridParams) for i in range(len(minimizedVisitParams)): filename = 'lists/chi2/' + minimizedVisitParams[i][0].locationID + '/' + minimizedVisitParams[i][0].apogeeID + '.lis' if not os.path.exists('lists/chi2/' + minimizedVisitParams[i][0].locationID + '/'): os.makedirs('lists/chi2/' + minimizedVisitParams[i][0].locationID + '/') writeGridToFile(minimizedVisitParams[i], filename=filename) print('Total run time: ' + str(round(timer.end(), 2)) + str('s'))
def grid(passCount, gridParams, minimizedVisitParams): ''' The binary model fitting grid. This function will fit the targets of the following parameters: 1) Teff of component A 2) Teff of component B 3) Flux Ratio of component B 4) Relative Heliocentric Velocity of Component A 5) Relative Heliocentric Velocity of Component B After chi2 minimization of the above parameters, the parameters used to get the minimized chi2 value is written into lists/chi2.lis. The other parameters that were tested on the grid and their corresponding chi2 values can be found in lists/chi2/FIELD_ID/2M_ID.lis. :param passCount: [in] The amount of maximum amount of passes the grid will go through :param gridParams: [in/out] The list of GridParams that contain the targets fitting data (built in runGrid) :param minimizedVisitParams: [out] All the visits with the minimized chi2 parameters ''' targetCount = len(gridParams) tpass = Timer() tpassSum = 0.0 for j in range(passCount): tpass.start() print('-------------PASS ' + str(j+1) + '/' + str(passCount) + '-------------') ttarget = Timer() ttargetSum = 0.0 for i in range(targetCount): locationID = gridParams[i].locationID apogeeID = gridParams[i].apogeeID badheader, header = apread.apStar(locationID, apogeeID, ext=0, header=True) nvisits = header['NVISITS'] print('Fitting: ' + locationID + ', ' + apogeeID + ', nvisits: ' + str(nvisits)) print('On target: ' + str(i+1) + '/' + str(targetCount)) ttarget.start() gridParams[i], minimizedVisitParams[i] = bg.targetGrid(gridParams[i], minimizedVisitParams[i], plot=False) temp = ttarget.end() ttargetSum+= temp print('Target run time: ' + str(round(temp, 2)) + str('s')) temp = tpass.end() tpassSum+= temp print('Pass run time: ' + str(round(temp, 2)) + str('s')) print('Average target run time: ' + str(round(ttargetSum/targetCount, 2)) + str('s')) print('Average pass run time: ' + str(round(tpassSum/passCount, 2)) + str('s'))
def test3(): print("Test 3: Multiple entry get (count={0})".format(count)) client = Client("localhost", 10001) timer = Timer() for i in range(0, count): client.entry_get("test speed", i) client.close() print("Seconds: {0}".format(timer.end()))
def test2(): print("Test 2: Multiple entry set opening/closing connection (count={0})". format(count)) timer = Timer() for i in range(0, count): client = Client("localhost", 10001) client.entry_set("test speed", i, i) client.close() client.close() print("Seconds: {0}".format(timer.end()))
def main(): """ Below test that Timer default unit is seconds error message when starting a started timer and error message when ending a non-started timer. """ print('========== Exercise 2.1.1 ==========') t = Timer() t.start() t.start() time.sleep(1) t.end() t.end() print(t.unit) """ Below ensures that the units are being changed accordingly """ t.unit = 'm' t.start() time.sleep(2) t.end() print(t.prevtime) print(t.unit)
class World(): def __init__(self): self.t = Timer() pygame.init() self.size = SIZE self.screen = pygame.display.set_mode(self.size) self.mpos = 50, 50 self.arr = loadImage(IMAGEPATH) self.arr = self.arr * -1 + 255 sx, sy = self.size self.mAArr = np.fromfunction(lambda x, y: np.arctan2(y - sy, x - sx), (2 * sx, 2 * sy)) self.mDArr = np.fromfunction(lambda x, y: np.hypot(y - sy, x - sx), (2 * sx, 2 * sy)) self.stars = star.World(self.size) self.silhouette = Silhouette(self, self.arr) self.moon = Moon(self) def draw(self): self.t.end('irr') sarr = np.zeros(self.size + (3, )) sarr[:, :, 0] = 10 sarr[:, :, 1] = 0 sarr[:, :, 2] = 10 arrOverlayWhite(sarr, self.stars.drawnArr) self.t.end('stars') arrOverlayWhite(sarr, self.moon.draw(sarr.shape)) self.t.end('moon') arrOverlayBlack(sarr, self.silhouette.foreground) self.t.end('fore') arrOverlayWhite(sarr, self.silhouette.draw(sarr.shape)) self.t.end('silhouette') arrBlitSurf(self.screen, sarr) self.t.end('blit') pygame.display.update()
# and open the template in the editor. __author__ = "ilausuch" __date__ = "$13-jun-2017 20:33:29$" import sys import os sys.path.append(os.path.abspath("../Core")) sys.path.append(os.path.abspath("../Addons")) from Timer import Timer from Cache import Cache, CacheItem if __name__ == "__main__": cache = Cache() count = 100000 timer = Timer() for i in range(0, count): cache.put("Bank1", CacheItem(i, i)) print("{0} puts in {1} seconds".format(count, timer.end())) timer = Timer() for i in range(0, count): cache.get("Bank1", i) print("{0} gets in {1} seconds".format(count, timer.end()))
for i in range(3): if procs[i].is_alive() == False: badheader, header = apread.apStar(locationIDs[i], apogeeIDs[i], ext=0, header=True, dr='13') nvisits = header['NVISITS'] visitSum+= timers[i].end() / nvisits if procs[0].is_alive() == False and procs[1].is_alive() == False and procs[2].is_alive() == False: running = False time.sleep(2)''' timer = Timer() visitSum = 0.0 for i in range(targetCount): badheader, header = apread.apStar(locationIDs[i], apogeeIDs[i], ext=0, header=True, dr='13') nvisits = header['NVISITS'] timer.start() runTarget(targets[i]) visitSum+= timer.end() / nvisits print(visitSum) print('avg visit time:', visitSum/targetCount) ''' done=4 print('------------Target ' + str(done + 1) + '/' + str(targetCount) + ' ------------') while targetQueue.empty() == False: # runTarget(targetQueue.get_nowait()) for i in range(4): if procs[i].is_alive() == False: del(procs[i]) if targetQueue.empty() == False: procs.append(Process(target=runTarget, args=(targetQueue.get_nowait(),))) procs[3].start() done+=1
def targetGrid(gridParam, minimizedVisitParams, plot=True): ''' The grid tests against ranging effective temperatures for both stars and the flux ratio of the secondary component. This is done by target. :param gridParam: [in/out] The GridParam of the target :param gridRes: [out] The visits that have the same paramters as the minimized chi2 visit :param plot: [in] If true makes plots to see intermediate steps (default=True) ''' locationID = gridParam.locationID apogeeID = gridParam.apogeeID badheader, header = apread.apStar(locationID, apogeeID, ext=0, header=True) specs = apread.apStar(locationID, apogeeID, ext=1, header=False) specerrs = apread.apStar(locationID, apogeeID, ext=2, header=False) nvisits = header['NVISITS'] # chi2 = np.full((nvisits, nrangeTeffA, nrangeTeffB, nrangeFluxRatio), -1.) #chi2 = np.full((nvisits, nrangeTeffA, nrangeTeffB, nrangeFluxRatio, nrangeRVA, nrangeRVB), -1.) ipg = ferre.Interpolator(lib='GK') ipf = ferre.Interpolator(lib='F') # Create file to store all the chi2 values path = 'lists/all_chi2/' + str(locationID) + '/' if not os.path.exists(path): os.makedirs(path) fn = open(path + apogeeID + '.lis', 'w') fn.write(gridParam.toStringHeader()) timer = Timer() timeSum = 0.0 allChi2 = [] visitGridParamsBuffer = [] for visit in range(1, nvisits + 1): timer.start() if (nvisits != 1): spec = specs[1+visit] specerr = specerrs[1+visit] else: spec = specs specerr = specerrs if (len(minimizedVisitParams) == 0): gridParam = GridParam(locationID, apogeeID) gridParam.constructParams() gridParam.getRVs(visit) else: gridParam = minimizedVisitParams[visit - 1] visitGridParamsBuffer.append(gridParam) # Prepare grid ranges rangeTeffA = np.arange(gridParam.minTeffA, gridParam.maxTeffA, gridParam.teffStepA) rangeTeffB = np.arange(gridParam.minTeffB, gridParam.maxTeffB, gridParam.teffStepB) rangeFluxRatio = np.arange(gridParam.minFluxRatio, gridParam.maxFluxRatio, gridParam.fluxStep) rangeRVA = np.arange(gridParam.minRVA, gridParam.maxRVA, gridParam.rvAStep) rangeRVB = np.arange(gridParam.minRVB, gridParam.maxRVB, gridParam.rvBStep) nrangeTeffA = len(rangeTeffA) nrangeTeffB = len(rangeTeffB) nrangeFluxRatio = len(rangeFluxRatio) nrangeRVA =len(rangeRVA) nrangeRVB =len(rangeRVB) chi2 = np.full((nrangeTeffA, nrangeTeffB, nrangeFluxRatio, nrangeRVA, nrangeRVB), -1.) print('Visit: ' + str(visit) ,'Grid dimensions: ' + str(chi2.shape)) # Prep Spectra aspec= np.reshape(spec,(1, len(spec))) aspecerr= np.reshape(specerr,(1, len(specerr))) cont= spec / continuum.fit(aspec, aspecerr, type='aspcap')[0] conterr = specerr / continuum.fit(aspec, aspecerr, type='aspcap')[0] shiftedSpec = bm.shiftFlux(cont, header['VHELIO' + str(visit)]) # Run grid for i in range(nrangeTeffA): gridParam.modelParamA.teff = rangeTeffA[i] componentA = bm.genComponent(gridParam.modelParamA, ipf, ipg) for j in range(nrangeTeffB): gridParam.modelParamB.teff = rangeTeffB[j] componentB = bm.genComponent(gridParam.modelParamB, ipf, ipg) for k in range(nrangeFluxRatio): gridParam.modelParamB.fluxRatio = rangeFluxRatio[k] componentBR = componentB * rangeFluxRatio[k] for l in range(nrangeRVA): gridParam.modelParamA.rv = rangeRVA[l] componentAS = bm.shiftFlux(componentA, rangeRVA[l]) for m in range(nrangeRVB): gridParam.modelParamB.rv = rangeRVB[m] componentBS = bm.shiftFlux(componentBR, rangeRVB[m]) binaryFlux = bm.combineFlux(componentAS, componentBS) chi2[i][j][k][l][m] = calcChi2(binaryFlux, shiftedSpec, conterr) / (len(binaryFlux) - 5.0) gridParam.chi2 = chi2[i][j][k][l][m] fn.write(gridParam.toString()) if (plot is True): restLambda = splot.apStarWavegrid() BinPlot.plotDeltaVCheck(locationID, apogeeID, visit, [ [ restLambda, binaryFlux, 'blue', 'model' ], [ restLambda, cont, 'orange', 'unshifted' ], [ restLambda, shiftedSpec, 'green', 'shifted' ]], [gridParam.modelParamA.teff,gridParam.modelParamB.teff, gridParam.modelParamB.fluxRatio], 'Delta V Shift', folder='grid_deltaVCheck') timeSum+=timer.end() allChi2.append(chi2) fn.close() print('Average visit time: ' + str(round(timeSum/nvisits, 2)) + str('s')) # Get minized values for each visit indices = None for i in range(nvisits): inds = getMinIndicies(allChi2[i]) rangeTeffA = np.arange(visitGridParamsBuffer[i].minTeffA, visitGridParamsBuffer[i].maxTeffA, visitGridParamsBuffer[i].teffStepA) rangeTeffB = np.arange(visitGridParamsBuffer[i].minTeffB, visitGridParamsBuffer[i].maxTeffB, visitGridParamsBuffer[i].teffStepB) rangeFluxRatio = np.arange(visitGridParamsBuffer[i].minFluxRatio, visitGridParamsBuffer[i].maxFluxRatio, visitGridParamsBuffer[i].fluxStep) rangeRVA = np.arange(visitGridParamsBuffer[i].minRVA, visitGridParamsBuffer[i].maxRVA, visitGridParamsBuffer[i].rvAStep) rangeRVB = np.arange(visitGridParamsBuffer[i].minRVB, visitGridParamsBuffer[i].maxRVB, visitGridParamsBuffer[i].rvBStep) nrangeTeffA = len(rangeTeffA) nrangeTeffB = len(rangeTeffB) nrangeFluxRatio = len(rangeFluxRatio) nrangeRVA =len(rangeRVA) nrangeRVB =len(rangeRVB) visitGridParamsBuffer[i].setParams(i + 1, rangeTeffA[inds[0]], rangeTeffB[inds[1]], rangeFluxRatio[inds[2]], rangeRVA[inds[3]], rangeRVB[inds[4]], allChi2[i][inds[0]][inds[1]][inds[2]][inds[3]][inds[4]]) if (indices is None): indices = [i + 1, inds, allChi2[i][inds[0]][inds[1]][inds[2]][inds[3]][inds[4]]] if (allChi2[i][inds[0]][inds[1]][inds[2]][inds[3]][inds[4]] < indices[2]): indices = [i + 1, inds, allChi2[i][inds[0]][inds[1]][inds[2]][inds[3]][inds[4]]] inds = getMinIndicies(allChi2) gridParam = visitGridParamsBuffer[inds[0]] return gridParam, visitGridParamsBuffer
class Babe(King): def __init__(self, screen, levels): self.screen = screen self.sprites = Babe_Sprites().babe_images self.levels = levels self.level = self.levels.max_level self.timer = Timer() # Booleans self.isWalk = False self.isCrouch = False self.isFalling = False self.isKiss = False self.hasKissed = False self.collideBottom = False self.lastCollision = True # Animation self.walkCount = 0 self.x, self.y = 375, 113 self.width, self.height = 32, 32 self.rect_x, self.rect_y = self.x + 1, self.y + 7 self.rect_width, self.rect_height = self.width - 12, self.height - 8 self.current_image = self.sprites["Babe_Stand1"] # Particles self.jump_particle = King_Particle("images\\particles\\jump_particle.png", 5, 1, 32) self.snow_jump_particle = King_Particle("images\\particles\\snow_jump_particle.png", 4, 3, 36) self.isJump = False self.isLanded = False # Audio self.channel = pygame.mixer.Channel(10) self.audio = Babe_Audio().audio # Physics self.physics = Physics() self.speed, self.angle = 0, 0 self.maxSpeed = 11 self.walkAngles = {"right" : math.pi/2, "left" : -math.pi/2} self.slip = 0 # Ending self.ending_distance = 50 def blitme(self): self.x = self.rect.x - 6 self.y = self.rect.y - 9 if self.levels.current_level == self.level: self.screen.blit(self.current_image, (self.x, self.y)) # pygame.draw.rect(self.screen, (255, 0, 0), self.rect, 1) def update(self, king, command = None): if self.levels.current_level == self.level: self._check_events(command) self._update_audio1() self._add_gravity() self._move() self._check_collisions() self._update_vectors() self._update_sprites() self._update_audio2() self._update_particles() if not self.levels.ending: self._check_ending(king) def _check_ending(self, king): if self.rect_y - king.rect_y >= 0: if self.rect_x - king.rect_x <= self.ending_distance: self.levels.ending = True king.rect_x, king.rect_y = self.rect_x - self.ending_distance, self.rect_y king.speed = 0 def _check_events(self, command): if command: if command == "Crouch" and not self.isCrouch: self.timer.start() self.isCrouch = True elif command == "Jump": self._jump() elif command == "Kiss": self.isKiss = True elif command == "WalkLeft": self._walk("left") elif command == "WalkRight": self._walk("right") elif command == "Snatched": self.rect_y += 999 else: self.isKiss = False self.hasKissed = False def _move(self): if self.speed > self.maxSpeed: self.speed = self.maxSpeed self.rect_x += math.sin(self.angle) * self.speed self.rect_y -= math.cos(self.angle) * self.speed # def _check_collisions(self): # self.isFalling = True # self.collideBottom = False # self.slip = 0 # for platform in self.levels.levels[self.levels.current_level].platforms: # if self._collide_rect(self.rect, platform): # if self.rect.bottom >= platform.top and round(self.rect.bottom - platform.top) <= round(self.speed) and -math.cos(self.angle) > 0 and not platform.support: # self.rect.bottom = platform.top # self.isFalling = False # self.isContact = False # self.collideBottom = True # if not self.lastCollision: # self.isLanded = True # self.lastCollision = platform # self.slip = platform.slip # if not self.collideBottom: # self.lastCollision = None def _update_vectors(self): if self.collideBottom: self.angle, self.speed = self.physics.add_vectors(self.angle, self.speed, -self.physics.gravity[0], -self.physics.gravity[1]) self.speed *= self.slip def _walk(self, direction): self.speed = 1 self.angle = self.walkAngles[direction] self.isWalk = True def _jump(self): speed = (2 + (self.timer.elapsed_time()*2) / 150) angle = 0 self.angle, self.speed = self.physics.add_vectors(self.angle, self.speed, angle, speed) self.isJump = True self.isCrouch = False self.isWalk = False self.timer.end() def _update_sprites(self): if self.isCrouch: self.current_image = self.sprites["Babe_Crouch"] if self.isFalling: if self.angle < math.pi/2 or self.angle > 3 * math.pi / 2: self.current_image = self.sprites["Babe_Jump"] else: self.current_image = self.sprites["Babe_Fall"] elif self.isKiss: self.current_image = self.sprites["Babe_Kiss"] elif self.lastCollision and self.isLanded: self.current_image = self.sprites["Babe_Land"] else: if self.walkCount <= 5: self.current_image = self.sprites["Babe_Stand1"] elif self.walkCount <= 8: self.current_image = self.sprites["Babe_Stand2"] elif self.walkCount <= 13: self.current_image = self.sprites["Babe_Stand3"] else: self.walkCount = 0 self.walkCount += 1 def _update_audio1(self): if self.lastCollision: if self.isJump: self.channel.play(self.audio["babe_jump"]) def _update_audio2(self): if self.lastCollision: if self.isLanded: self.channel.play(self.audio["king_land"]) self.isLanded = False if self.isKiss: if not self.channel.get_busy() and not self.hasKissed: self.channel.play(self.audio["babe_kiss"]) self.hasKissed = True
for visit in range(1, nvisits): if (nvisits != 1): ccf = data['CCF'][0][1 + visit] else: ccf = data['CCF'][0] max1, max2 = getMaxPositions(ccf, ranger) r = [] for cut in range(20): r.append(calcR(ccf, cut*10, (401 - (cut * 10)))) if r < 1.0: if recorded is False: recorded = True interestingTargets.append([locationID, apogeeID, "r"]) if str(max2) != 'none': if recorded is False: recorded = True interestingTargets.append([locationID, apogeeID, ranger]) positions.append([max1, max2, r]) reportPositions(locationID, apogeeID, ranger, positions) recordTargets(interestingTargets, ranger, 'interestingTargets') recordTargets(skippedTargets, ranger, 'skippedTargets') print("done", t.current()) t.end()