def main(self): #1) basic initialization pygame.init() #so that key holds can be recognized. pygame.key.set_repeat(17, 17) self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption('Smoothie Maker') #counter of ticks self.current_ticks = 0 #2 set up game objects self.clock = pygame.time.Clock() #create the blender object that represents you self.blender = Blender(self, hspeed=7.0, playerNumber=self.playerNumber, playerType='user') opponentPlayerNumber = 1 if self.playerNumber == 1: opponentPlayerNumber = 2 #create the blender object that represents your opponent self.opponent = Blender(self, hspeed=7.0, playerNumber=opponentPlayerNumber, playerType='opponent') self.scoreLabel = ScoreLabel(self, playerType='user') self.scoreLabelOpponent = ScoreLabel(self, playerType='opponent') self.youLabel = PlayerLabel(self, textLabel="You", xpos=self.width / 4, ypos=40, size=50) self.oppLabel = PlayerLabel(self, textLabel="Opponent", xpos=3 * self.width / 4, ypos=40, size=50) self.gameObjectsList = list() self.gameObjectsList.append(self.blender) self.gameObjectsList.append(self.opponent) self.gameLabels = list() self.gameLabels.append(self.scoreLabel) self.gameLabels.append(self.scoreLabelOpponent) self.gameLabels.append(self.youLabel) self.gameLabels.append(self.oppLabel)
def __init__(self, args): self.blender = Blender('vitamix') # initialized, to be defined later # self.data_multibar = None self.data_stackedarea = None self.data_pie = None self.data_scatter_continuous = None self.all_plot_types = None self.difference_domains_multibar = None self.warning_multibar = None self.warning_stackedarea = None self.line_data = None # first to be initialized self.new_variable = None self.variable_list_string = None self.number_of_variables = None self.unique_plottypes = None # err msgs self.error_found = False self.err_msg = None self.calculate_stats(args)
def create_image_set(blender: Blender, n_blends: int, outdir: Path, test_set: bool = False) -> None: """ Use a Blender instance to output stamps of blended galaxies and their associated segmentation mask, plus a catalog of these sources. Parameters ---------- blender: the Blender instance n_blends: number of desired images outdir: output directory test_set: default False switch between the training and testing galaxy split """ prefix = "test" if test_set else "train" outcat = outdir / f"{prefix}_catalogue.csv" with open(outcat, "w") as f: output = csv.writer(f) output.writerow(CATALOG_HEADER) msg = f"Producing {prefix} blended images" with click.progressbar(range(n_blends), label=msg) as bar: for blend_id in bar: blend = blender.next_blend(from_test=test_set) while blend is None: blend = blender.next_blend(from_test=test_set) output.writerow(blend2cat(blend, blend_id)) save_img(blend, blend_id, prefix, outdir)
def main(self): #1) basic initialization pygame.init() #so that key holds can be recognized. pygame.key.set_repeat(17,17) self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption('Smoothie Maker') #counter of ticks self.current_ticks = 0 #2 set up game objects self.clock = pygame.time.Clock() #create the blender object that represents you self.blender = Blender(self,hspeed=7.0,playerNumber=self.playerNumber,playerType='user') opponentPlayerNumber = 1 if self.playerNumber == 1: opponentPlayerNumber = 2 #create the blender object that represents your opponent self.opponent = Blender(self,hspeed=7.0,playerNumber=opponentPlayerNumber,playerType='opponent') self.scoreLabel = ScoreLabel(self,playerType='user') self.scoreLabelOpponent = ScoreLabel(self,playerType='opponent') self.youLabel = PlayerLabel(self,textLabel="You",xpos=self.width/4,ypos=40,size=50) self.oppLabel = PlayerLabel(self,textLabel="Opponent",xpos=3*self.width/4,ypos=40,size=50) self.gameObjectsList = list() self.gameObjectsList.append(self.blender) self.gameObjectsList.append(self.opponent) self.gameLabels = list() self.gameLabels.append(self.scoreLabel) self.gameLabels.append(self.scoreLabelOpponent) self.gameLabels.append(self.youLabel) self.gameLabels.append(self.oppLabel)
def step(context, thing): context.blender = Blender() context.blender.add(thing)
def step_1(context, browser_page): #context.browser.get("https://crash-stats.mozilla.com/") context.blender = Blender() #context.blender.add(browser_page) context.browser.get(browser_page)
def start(): round_robin = 0 while True: try: manager_queue = RedisQueue('manager', host=settings.REDIS_HOST, port=settings.REDIS_PORT) # get next message - first find an available queue keys = RedisKeys(pattern='rendertaskqueue:*', host=settings.REDIS_HOST, port=settings.REDIS_PORT).keys if keys is not None and len(keys) > 0: round_robin = BlendClusterClient.next_queue(round_robin, keys) queue_name = keys[round_robin] # just grab the first queue name print 'round robin: ' + queue_name queue = RedisQueue('namechangedbelow', host=settings.REDIS_HOST, port=settings.REDIS_PORT) queue.key = queue_name # override key name (queue name) here as we have the qualified name print 'getting render task message' render_task_json = queue.get() print render_task_json render_task_obj = RenderTaskMessage.json_to_object(render_task_json) hg_url = render_task_obj.hg_url blend_file = render_task_obj.blend_file # notify manager we are working msg = RenderTaskStateChangeMessage.json_from_object({ 'id': render_task_obj.id, 'state': 1}) # set working state manager_queue.put(msg) print 'Set task to WORKING state: ' + str(render_task_obj.id) print '-------------------------' print 'WORKING' print '-------------------------' # so some work print 'About to prepare hg' hg = HgUtils(url=hg_url) print 'about to clone or pull hg' hg.clone_or_pull() full_blend_filename = hg.local_project_path + '/' + render_task_obj.blend_file short_blend_filename = ntpath.basename(full_blend_filename).split('.')[0] render_dir = hg.local_project_path + '/renders/' + short_blend_filename + '/'\ + render_task_obj.scene_name + '/' print 'Rendering in dir: ' + render_dir if not os.path.exists(render_dir): os.makedirs(render_dir) hg.push_all_changes() blender = Blender(blend_file=full_blend_filename, scene_name=render_task_obj.scene_name, start_frame=render_task_obj.frame, end_frame=render_task_obj.frame, output_dir=render_dir) blender.run() # before pushing changes update local repo hg.get_latest_changes() hg.push_all_changes() print 'done hg' msg = RenderTaskStateChangeMessage.json_from_object({ 'id': render_task_obj.id, 'state': 4}) # set success state manager_queue.put(msg) print '-------------------------' print 'SUCCESSFUL' print '-------------------------' else: print('No messages available right now, will try again in 5 seconds...') time.sleep(5) # wait 5 secs before trying again except Exception as e: print('Error raised: ' + e.message) try: msg = RenderTaskStateChangeMessage.json_from_object({ 'id': render_task_obj.id, 'state': 3}) # set working state failed manager_queue.put(msg) print '-------------------------' print 'FAILED' print '-------------------------' except: print('Trying to respond with a failure status but could not!') print('Will try again in 5 seconds...') time.sleep(5) # wait 5 secs before trying again
def step_given_put_thing_into_blender(context, thing): context.blender = Blender() context.blender.add(thing)
from blender import Blender from improc_utils import * from mask_generator import MaskGenerator if __name__ == '__main__': pyr_blender = Blender(kernel_size=5) mask_gen = MaskGenerator() im1 = open_image('d:/lenna.png', rgb=False) im2 = open_image('d:/face.jpg', rgb=False) mask = mask_gen.split(0.5, 'h', shaped_like=im1) blended = pyr_blender.blend(im1, im2, mask) mixed = pyr_blender.mix(im1, im2, mask) display_many([blended, mixed])
class GameSpace: def __init__(self, fruitConn, playerNumber, randSeed, minFruitSpeed, maxFruitSpeed): #reference to the connection to the server self.fruitConn = fruitConn self.playerNumber = playerNumber random.seed(randSeed) self.minSpeed = minFruitSpeed self.maxSpeed = maxFruitSpeed print self.minSpeed, self.maxSpeed #list of images self.listOfFruitImages = [ 'images/strawberry.png', 'images/banana.png', 'images/raspberry.png', 'images/blueberry.png' ] self.listOfVegetableImages = [ 'images/potato.png', 'images/onion.png', 'images/broccoli.png' ] self.listOfFrozenFruitImages = [ 'images/strawberryfrozen.png', 'images/bananafrozen.png', 'images/raspberryfrozen.png', 'images/blueberryfrozen.png' ] self.listOfFrozenVegetableImages = [ 'images/potatofrozen.png', 'images/frozenonion.png', 'images/broccolifrozen.png' ] self.goldenImage = 'images/pineapple.png' self.frozenGoldImage = 'images/pineapplefrozen.png' #list of your fruits and opponents fruits (the ones on the right) self.fruits = list() self.fruitsOpp = list() self.score = 0 self.opponentScore = 0 self.winningScore = 200 #for screen drawings self.size = self.width, self.height = 1280, 800 self.black = 0, 0, 0 self.white = 255, 255, 255 #to draw the white veritcal line down the middle self.point1 = self.width / 2, 0 self.point2 = self.width / 2, self.height self.counter = 0 def main(self): #1) basic initialization pygame.init() #so that key holds can be recognized. pygame.key.set_repeat(17, 17) self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption('Smoothie Maker') #counter of ticks self.current_ticks = 0 #2 set up game objects self.clock = pygame.time.Clock() #create the blender object that represents you self.blender = Blender(self, hspeed=7.0, playerNumber=self.playerNumber, playerType='user') opponentPlayerNumber = 1 if self.playerNumber == 1: opponentPlayerNumber = 2 #create the blender object that represents your opponent self.opponent = Blender(self, hspeed=7.0, playerNumber=opponentPlayerNumber, playerType='opponent') self.scoreLabel = ScoreLabel(self, playerType='user') self.scoreLabelOpponent = ScoreLabel(self, playerType='opponent') self.youLabel = PlayerLabel(self, textLabel="You", xpos=self.width / 4, ypos=40, size=50) self.oppLabel = PlayerLabel(self, textLabel="Opponent", xpos=3 * self.width / 4, ypos=40, size=50) self.gameObjectsList = list() self.gameObjectsList.append(self.blender) self.gameObjectsList.append(self.opponent) self.gameLabels = list() self.gameLabels.append(self.scoreLabel) self.gameLabels.append(self.scoreLabelOpponent) self.gameLabels.append(self.youLabel) self.gameLabels.append(self.oppLabel) #will countdown to start the game as 3,2,1.. def countDown(self): self.screen.fill(self.black) text = "3" message = 'You are the pink player on the left' if self.playerNumber == 2: message = 'You are the green player on the left' if self.current_ticks < 60: text = "3" elif self.current_ticks < 120: text = "2" elif self.current_ticks < 180: text = "1" else: self.fruitConn.startGameLoop() return 0 #handle user inputs for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.display.quit() self.fruitConn.lc.stop() self.fruitConn.closeConn() return 1 self.current_ticks += 1 gameLabel = PlayerLabel(self, textLabel="Smoothie Maker", xpos=self.width / 2, ypos=100, size=50) playerLabel = PlayerLabel(self, textLabel=message, xpos=self.width / 2, ypos=self.height / 2 + 100, size=50) numLabel = PlayerLabel(self, textLabel=text, xpos=self.width / 2, ypos=self.height / 2, size=50) self.screen.blit(numLabel.label, numLabel.rect) self.screen.blit(playerLabel.label, playerLabel.rect) self.screen.blit(gameLabel.label, gameLabel.rect) pygame.display.flip() def gameLoopIteration(self): #if you or opponent won, stop the looping call and tell the connection which will generate a new looping call if self.score >= self.winningScore: self.fruitConn.lc.stop() if self.opponentScore >= self.winningScore: self.fruitConn.gameOver('Tie!') else: self.fruitConn.gameOver('You Won') return 0 elif self.opponentScore >= self.winningScore: self.fruitConn.lc.stop() self.fruitConn.gameOver('Opponent Won') return 0 #otherwise game is not over else: #every 1 second generate a fruit if self.current_ticks % 60 == 0: self.foodType = 'fruit' #10% chance of getting a gold fruit (which is worth double) goldRandNum = random.randint(0, 9) if goldRandNum == 0: randFruitInt = -1 else: randFruitInt = random.randint( 0, len(self.listOfFruitImages) - 1) #get random data to create a fruit #rand fruit int will determine which image is loaded self.randFruitInt = randFruitInt #random position of where it will start on x axis xpos = random.randint(0, self.width / 2) self.randXPos = xpos #random velocity vspeed = random.randint(self.minSpeed, self.maxSpeed) self.randVSpeed = vspeed #give it a unique id self.fruitID = self.counter self.counter += 1 #create the fruit fruitToAdd = Fruit(self, type=self.foodType, xpos=xpos, randFruitInt=randFruitInt, vspeed=vspeed, fruitID=self.fruitID, side='left') #create the data you want to pickle over to the other player so he has the same fruit fruitData = FruitData(fruitInt=self.randFruitInt, xpos=self.randXPos, vspeed=self.randVSpeed, foodType=self.foodType, fruitID=self.fruitID) #add the fruit data over to connection's queue so it can send it over to server (then to other player) self.fruitConn.fruitQueue.put(fruitData) self.fruits.append(fruitToAdd) #every 1.67 seconds generate a veggie, do same thing as above if self.current_ticks % 100 == 0: self.foodType = 'vegetable' randFruitInt = random.randint( 0, len(self.listOfVegetableImages) - 1) self.randFruitInt = randFruitInt xpos = random.randint(0, self.width / 2) self.randXPos = xpos vspeed = random.randint(self.minSpeed, self.maxSpeed) self.randVSpeed = vspeed self.fruitID = self.counter self.counter += 1 fruitToAdd = Fruit(self, type=self.foodType, xpos=xpos, randFruitInt=randFruitInt, vspeed=vspeed, fruitID=self.fruitID, side='left') fruitData = FruitData(fruitInt=self.randFruitInt, xpos=self.randXPos, vspeed=self.randVSpeed, foodType=self.foodType, fruitID=self.fruitID) self.fruitConn.fruitQueue.put(fruitData) self.fruits.append(fruitToAdd) #handle user inputs for event in pygame.event.get(): if event.type == pygame.KEYDOWN: self.blender.move(event.key) elif event.type == pygame.MOUSEBUTTONDOWN: #get mouse click and see if it collides with a fruit on the screen mx, my = pygame.mouse.get_pos() self.freezeFruits(mx, my) elif event.type == pygame.QUIT: pygame.display.quit() self.fruitConn.lc.stop() self.fruitConn.closeConn() return 1 #6 send a tick to every game object for obj in self.gameObjectsList: obj.tick() for fr in self.fruits: fr.tick() for fr in self.fruitsOpp: fr.tick() for label in self.gameLabels: label.tick() self.scoreLabel.tick() self.scoreLabelOpponent.tick() self.youLabel.tick() self.oppLabel.tick() #7 display game objects self.screen.fill(self.black) for label in self.gameLabels: self.screen.blit(self.scoreLabel.label, self.scoreLabel.rect) self.screen.blit(self.scoreLabelOpponent.label, self.scoreLabelOpponent.rect) self.screen.blit(self.youLabel.label, self.youLabel.rect) self.screen.blit(self.oppLabel.label, self.oppLabel.rect) for fr in self.fruits: self.screen.blit(fr.image, fr.rect) for fr in self.fruitsOpp: self.screen.blit(fr.image, fr.rect) for obj in self.gameObjectsList: self.screen.blit(obj.image, obj.rect) #draw white line down the middle pygame.draw.line(self.screen, self.white, self.point1, self.point2) pygame.display.flip() self.current_ticks += 1 return 0 #will be the looping call once the game ends def goToGameOver(self, text): self.screen.fill(self.black) winnerLabel = PlayerLabel(self, textLabel=text, xpos=self.width / 2, ypos=self.height / 2, size=50) #handle user inputs for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.display.quit() self.fruitConn.lc.stop() self.fruitConn.closeConn() return 1 self.screen.blit(winnerLabel.label, winnerLabel.rect) pygame.display.flip() #adds a fruit to your screen, this is a fruit sent over by your opponent which he generated def addFruit(self, fruitInt, xpos, vspeed, foodType, iD): xpos += self.width / 2 food = Fruit(self, type=foodType, xpos=xpos, randFruitInt=fruitInt, vspeed=vspeed, fruitID=iD, side='right') self.fruitsOpp.append(food) #updates the rectangle of the opponent blender on your screen def updateOpponent(self, rect): self.opponent.rect = rect self.opponent.rect = self.opponent.rect.move(self.width / 2, 0) self.opponent.colliderect = self.opponent.rect.inflate( -self.opponent.rect.width * .18, -self.opponent.rect.height * .9) self.opponent.colliderect = self.opponent.colliderect.move( (-self.opponent.rect.width * .18) / 2, (-self.opponent.rect.height * .9) / 2) #add and subtract to your score def addToScore(self, double=False): self.score += 10 if double == True: self.score += 10 if self.score > self.winningScore: self.score = self.winningScore def subFromScore(self): self.score -= 20 if self.score < 0: self.score = 0 #will freeze any fruit at mx,my. called when get a click def freezeFruits(self, mx, my): for fruit in self.fruits: if fruit.rect.collidepoint(mx, my): fruit.freezeFruit() self.fruitConn.freezeRightFruit(fruit.fruitID) for fruit in self.fruitsOpp: if fruit.rect.collidepoint(mx, my): fruit.freezeFruit() self.fruitConn.freezeLeftFruit(fruit.fruitID) #freezes a fruit w/ given id def freezeLeftFruitWithID(self, fruitID): for fruit in self.fruits: if fruit.fruitID == fruitID: fruit.freezeFruit() def freezeRightFruitWithID(self, fruitID): for fruit in self.fruitsOpp: if fruit.fruitID == fruitID: fruit.freezeFruit()
def do_fit(self): _, _, _, blend_valuelist, blend_frequencylist = blendframe.blendlist subblend_valuelist = blend_valuelist[subblendframe.selected_subblend] subblend_frequencylist = blend_frequencylist[ subblendframe.selected_subblend] listsize = len(subblend_valuelist) self.rangelist = self.get_range() lowerx, upperx = self.rangelist index = listsize - 1 while index > -1 and not subblend_valuelist[index] < lowerx: index = index - 1 index = index + 1 lowerindex = index index = 0 while index < listsize and not subblend_valuelist[index] > upperx: index = index + 1 index = index - 1 upperindex = index indexlist = [lowerindex, upperindex] self.boolfit = False if not len(blendframe.blendlist) > 0: print("There is not a blend selected.") return self.listboxsize = listboxframe.listbox.size() if not self.listboxsize > 0: print("There is not a coke added.") return lowerconstraintlist = [] upperconstraintlist = [] for listindex in range(self.listboxsize): listboxitem = listboxframe.listbox.get(listindex) splitlist = listboxitem.split('[') splitlist = splitlist[1].split(']') constraint = splitlist[0] splitlist = constraint.split("≤") lowerconstraintlist.append(float(splitlist[0].strip())) upperconstraintlist.append(float(splitlist[2].strip())) constraintlist = [lowerconstraintlist, upperconstraintlist] blender = Blender(blendframe.blendlist, cokeframe.allcokelist, subblendframe.selected_subblend, constraintlist, indexlist) fitchoicevalue = self.fitchoicevar.get() if fitchoicevalue == 0: blender.qp_fit() else: blender.grid_fit(int(self.spacevar.get())) self.volumelist = blender.volumelist self.fit_frequencylist = [0.0] * 256 for listindex in range(self.listboxsize): _, _, _, _, coke_frequencylist = cokeframe.allcokelist[listindex] subcoke_frequencylist = coke_frequencylist[ subblendframe.selected_subblend] for k in range(256): self.fit_frequencylist[ k] = self.fit_frequencylist[k] + self.volumelist[ listindex] / 100.0 * subcoke_frequencylist[k] self.sumerror = 0.0 for k in range(lowerindex, upperindex + 1, 1): self.sumerror = self.sumerror + (self.fit_frequencylist[k] - subblend_frequencylist[k])**2 self.plot_fit() self.show_fit() self.boolfit = True
print "Shape: ", test_data.shape #get training_data training_data = pandas.load("../TrainingData.pickle") print "Training data in." #training_location_data = training_data[ ['LATITUDE', 'LONGITUDE' ] ] #training_response = training_data['Mail_Return_Rate_CEN_2010'] #training_weights = training_data['weight'] training_data, training_location_data, training_response, training_weights = preprocess_dataframe( training_data) print "Shape: ", training_data.shape ### CREATE MODEL ### bl = Blender(verbose=True, training_fraction=0.95) bl.add_model( lclR.LocalRegression(k=500, regressor=SmartSVR, params={'gamma': 0.0001}), "SmrtSVR") bl.add_model( lclR.LocalRegression(k=500, regressor=SmartSVR, params={ 'gamma': 0.001, "C": 50 }), "LooseSmrtSVR") bl.add_model( lclR.LocalRegression(k=500, regressor=sklm.ElasticNet, params={
class GameSpace: def __init__(self,fruitConn,playerNumber,randSeed,minFruitSpeed,maxFruitSpeed): #reference to the connection to the server self.fruitConn = fruitConn self.playerNumber = playerNumber random.seed(randSeed) self.minSpeed = minFruitSpeed self.maxSpeed = maxFruitSpeed print self.minSpeed,self.maxSpeed #list of images self.listOfFruitImages=['images/strawberry.png','images/banana.png','images/raspberry.png','images/blueberry.png'] self.listOfVegetableImages = ['images/potato.png', 'images/onion.png','images/broccoli.png'] self.listOfFrozenFruitImages = ['images/strawberryfrozen.png','images/bananafrozen.png','images/raspberryfrozen.png','images/blueberryfrozen.png'] self.listOfFrozenVegetableImages = ['images/potatofrozen.png', 'images/frozenonion.png','images/broccolifrozen.png'] self.goldenImage = 'images/pineapple.png' self.frozenGoldImage = 'images/pineapplefrozen.png' #list of your fruits and opponents fruits (the ones on the right) self.fruits = list() self.fruitsOpp = list() self.score = 0 self.opponentScore = 0 self.winningScore = 200 #for screen drawings self.size = self.width, self.height = 1280,800 self.black = 0,0,0 self.white = 255,255,255 #to draw the white veritcal line down the middle self.point1 = self.width/2,0 self.point2 = self.width/2,self.height self.counter = 0 def main(self): #1) basic initialization pygame.init() #so that key holds can be recognized. pygame.key.set_repeat(17,17) self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption('Smoothie Maker') #counter of ticks self.current_ticks = 0 #2 set up game objects self.clock = pygame.time.Clock() #create the blender object that represents you self.blender = Blender(self,hspeed=7.0,playerNumber=self.playerNumber,playerType='user') opponentPlayerNumber = 1 if self.playerNumber == 1: opponentPlayerNumber = 2 #create the blender object that represents your opponent self.opponent = Blender(self,hspeed=7.0,playerNumber=opponentPlayerNumber,playerType='opponent') self.scoreLabel = ScoreLabel(self,playerType='user') self.scoreLabelOpponent = ScoreLabel(self,playerType='opponent') self.youLabel = PlayerLabel(self,textLabel="You",xpos=self.width/4,ypos=40,size=50) self.oppLabel = PlayerLabel(self,textLabel="Opponent",xpos=3*self.width/4,ypos=40,size=50) self.gameObjectsList = list() self.gameObjectsList.append(self.blender) self.gameObjectsList.append(self.opponent) self.gameLabels = list() self.gameLabels.append(self.scoreLabel) self.gameLabels.append(self.scoreLabelOpponent) self.gameLabels.append(self.youLabel) self.gameLabels.append(self.oppLabel) #will countdown to start the game as 3,2,1.. def countDown(self): self.screen.fill(self.black) text = "3" message = 'You are the pink player on the left' if self.playerNumber == 2: message = 'You are the green player on the left' if self.current_ticks <60: text = "3" elif self.current_ticks < 120: text = "2" elif self.current_ticks < 180: text = "1" else: self.fruitConn.startGameLoop() return 0 #handle user inputs for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.display.quit() self.fruitConn.lc.stop() self.fruitConn.closeConn() return 1 self.current_ticks+=1 gameLabel = PlayerLabel(self,textLabel="Smoothie Maker",xpos=self.width/2,ypos= 100,size=50) playerLabel = PlayerLabel(self,textLabel=message,xpos=self.width/2,ypos = self.height/2+100,size=50) numLabel = PlayerLabel(self,textLabel=text,xpos=self.width/2,ypos=self.height/2,size=50) self.screen.blit(numLabel.label,numLabel.rect) self.screen.blit(playerLabel.label,playerLabel.rect) self.screen.blit(gameLabel.label,gameLabel.rect) pygame.display.flip() def gameLoopIteration(self): #if you or opponent won, stop the looping call and tell the connection which will generate a new looping call if self.score >= self.winningScore: self.fruitConn.lc.stop() if self.opponentScore>= self.winningScore: self.fruitConn.gameOver('Tie!') else: self.fruitConn.gameOver('You Won') return 0 elif self.opponentScore >= self.winningScore: self.fruitConn.lc.stop() self.fruitConn.gameOver('Opponent Won') return 0 #otherwise game is not over else: #every 1 second generate a fruit if self.current_ticks%60 == 0: self.foodType = 'fruit' #10% chance of getting a gold fruit (which is worth double) goldRandNum = random.randint(0,9) if goldRandNum == 0: randFruitInt = -1 else: randFruitInt = random.randint(0,len(self.listOfFruitImages)-1) #get random data to create a fruit #rand fruit int will determine which image is loaded self.randFruitInt = randFruitInt #random position of where it will start on x axis xpos = random.randint(0,self.width/2) self.randXPos = xpos #random velocity vspeed = random.randint(self.minSpeed,self.maxSpeed) self.randVSpeed = vspeed #give it a unique id self.fruitID = self.counter self.counter+=1 #create the fruit fruitToAdd = Fruit(self,type=self.foodType,xpos=xpos,randFruitInt=randFruitInt,vspeed=vspeed,fruitID=self.fruitID,side='left') #create the data you want to pickle over to the other player so he has the same fruit fruitData = FruitData(fruitInt=self.randFruitInt,xpos=self.randXPos,vspeed=self.randVSpeed,foodType=self.foodType,fruitID=self.fruitID) #add the fruit data over to connection's queue so it can send it over to server (then to other player) self.fruitConn.fruitQueue.put(fruitData) self.fruits.append(fruitToAdd) #every 1.67 seconds generate a veggie, do same thing as above if self.current_ticks %100 == 0: self.foodType = 'vegetable' randFruitInt = random.randint(0,len(self.listOfVegetableImages)-1) self.randFruitInt = randFruitInt xpos = random.randint(0,self.width/2) self.randXPos = xpos vspeed = random.randint(self.minSpeed,self.maxSpeed) self.randVSpeed = vspeed self.fruitID = self.counter self.counter+=1 fruitToAdd = Fruit(self,type=self.foodType,xpos=xpos,randFruitInt=randFruitInt,vspeed=vspeed,fruitID=self.fruitID,side='left') fruitData = FruitData(fruitInt=self.randFruitInt,xpos=self.randXPos,vspeed=self.randVSpeed,foodType=self.foodType,fruitID=self.fruitID) self.fruitConn.fruitQueue.put(fruitData) self.fruits.append(fruitToAdd) #handle user inputs for event in pygame.event.get(): if event.type == pygame.KEYDOWN: self.blender.move(event.key) elif event.type == pygame.MOUSEBUTTONDOWN: #get mouse click and see if it collides with a fruit on the screen mx,my = pygame.mouse.get_pos() self.freezeFruits(mx,my) elif event.type == pygame.QUIT: pygame.display.quit() self.fruitConn.lc.stop() self.fruitConn.closeConn() return 1 #6 send a tick to every game object for obj in self.gameObjectsList: obj.tick() for fr in self.fruits: fr.tick() for fr in self.fruitsOpp: fr.tick() for label in self.gameLabels: label.tick() self.scoreLabel.tick() self.scoreLabelOpponent.tick() self.youLabel.tick() self.oppLabel.tick() #7 display game objects self.screen.fill(self.black) for label in self.gameLabels: self.screen.blit(self.scoreLabel.label,self.scoreLabel.rect) self.screen.blit(self.scoreLabelOpponent.label,self.scoreLabelOpponent.rect) self.screen.blit(self.youLabel.label,self.youLabel.rect) self.screen.blit(self.oppLabel.label,self.oppLabel.rect) for fr in self.fruits: self.screen.blit(fr.image,fr.rect) for fr in self.fruitsOpp: self.screen.blit(fr.image,fr.rect) for obj in self.gameObjectsList: self.screen.blit(obj.image,obj.rect) #draw white line down the middle pygame.draw.line(self.screen,self.white,self.point1,self.point2) pygame.display.flip() self.current_ticks+=1 return 0 #will be the looping call once the game ends def goToGameOver(self,text): self.screen.fill(self.black) winnerLabel = PlayerLabel(self,textLabel=text,xpos=self.width/2,ypos=self.height/2,size=50) #handle user inputs for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.display.quit() self.fruitConn.lc.stop() self.fruitConn.closeConn() return 1 self.screen.blit(winnerLabel.label,winnerLabel.rect) pygame.display.flip() #adds a fruit to your screen, this is a fruit sent over by your opponent which he generated def addFruit(self,fruitInt,xpos,vspeed,foodType,iD): xpos+=self.width/2 food = Fruit(self,type=foodType,xpos=xpos,randFruitInt=fruitInt,vspeed=vspeed,fruitID=iD,side='right') self.fruitsOpp.append(food) #updates the rectangle of the opponent blender on your screen def updateOpponent(self,rect): self.opponent.rect = rect self.opponent.rect = self.opponent.rect.move(self.width/2,0) self.opponent.colliderect = self.opponent.rect.inflate(-self.opponent.rect.width*.18,-self.opponent.rect.height*.9) self.opponent.colliderect = self.opponent.colliderect.move((-self.opponent.rect.width*.18)/2,(-self.opponent.rect.height*.9)/2) #add and subtract to your score def addToScore(self,double=False): self.score+=10 if double == True: self.score+=10 if self.score > self.winningScore: self.score = self.winningScore def subFromScore(self): self.score-=20 if self.score < 0: self.score = 0 #will freeze any fruit at mx,my. called when get a click def freezeFruits(self,mx,my): for fruit in self.fruits: if fruit.rect.collidepoint(mx,my): fruit.freezeFruit() self.fruitConn.freezeRightFruit(fruit.fruitID) for fruit in self.fruitsOpp: if fruit.rect.collidepoint(mx,my): fruit.freezeFruit() self.fruitConn.freezeLeftFruit(fruit.fruitID) #freezes a fruit w/ given id def freezeLeftFruitWithID(self,fruitID): for fruit in self.fruits: if fruit.fruitID == fruitID: fruit.freezeFruit() def freezeRightFruitWithID(self,fruitID): for fruit in self.fruitsOpp: if fruit.fruitID == fruitID: fruit.freezeFruit()
------------------------ """) choice = input("Enter choice: ") if choice == EXIT: break elif choice == CREATE_OBJECT: print("All data is optional") manufacturer = input( "Enter the manufacturer of the blender: ") blender_type = input("Enter the blender type: ") blender = Blender(manufacturer=manufacturer, blender_type=blender_type) print(blender) input("Press Enter to continue...") elif choice == PRINT_OBJECT: try: print(blender) except NameError: print("Error: Please create the object of the blender") input("Press Enter to continue...") elif choice == EDIT_FIELDS: try: blender.manufacturer = input( f"Enter the manufacturer of the blender ({blender.manufacturer} - default): "
print "Test data cleaned." print "Shape: ", test_data.shape #get training_data training_data = pandas.load( "../TrainingData.pickle" ) print "Training data in." #training_location_data = training_data[ ['LATITUDE', 'LONGITUDE' ] ] #training_response = training_data['Mail_Return_Rate_CEN_2010'] #training_weights = training_data['weight'] training_data, training_location_data, training_response, training_weights = preprocess_dataframe( training_data) print "Shape: ", training_data.shape ### CREATE MODEL ### bl = Blender( verbose = True, training_fraction = 0.95) bl.add_model( lclR.LocalRegression(k = 500 , regressor = SmartSVR, params = {'gamma':0.0001}), "SmrtSVR") bl.add_model( lclR.LocalRegression(k = 500 , regressor = SmartSVR, params = {'gamma':0.001, "C":50}), "LooseSmrtSVR") bl.add_model( lclR.LocalRegression(k = 500, regressor = sklm.ElasticNet, params = {'alpha':0.0001, "normalize":True}), "ElNet500" ) bl.add_model( lclR.LocalRegression(k = 500, regressor = rfr, params={"n_jobs":5, "n_estimators": 10 } ), "rfr50est") bl.add_model( lclR.LocalRegression( k=500, regressor = sklm.Lasso, params={"alpha":0.01, "normalize":True}), "lasso" ) bl.add_model( rfr( n_jobs=150, n_estimators=200 ), "Globalrfr50est") bl.add_model( lclR.LocalRegression( k=750, regressor = sklm.Ridge, feature_selection = True, params={ 'alpha':0.001, 'normalize':True} ), "RidgeWithFeatureSelection" ) bl.add_model( lclR.LocalRegression( k=750, regressor = sklm.Ridge, feature_selection = False, params={"alpha":0.1, "normalize":True}), "Ridge") bl.add_model( lclR.LocalRegression( k = 250, regressor = sklm.Ridge, feature_selection = False, params={"alpha":1.5, "normalize":True} ), "LocalRidge") lc = [ training_location_data.values ] bl.fit( training_data.values, training_response.values, {"SmrtSVR": lc, "ElNet500":lc, "RidgeWithFeatureSelection":lc, "rfr50est":lc, "lasso":lc, "Ridge":lc, "LooseSmrtSVR":lc, "LocalRidge":lc } )
def main(n_blends, excluded_type, mag_low, mag_high, mag_diff, rad_diff, test_ratio, datapath, seed): """ Produce stamps of CANDELS blended galaxies with their individual masks """ # Define the various paths and create directories cwd = Path.cwd() datapath = cwd / datapath input_stamps = datapath / "candels_img.npy" input_segmaps = datapath / "candels_seg.npy" input_catalog = datapath / "candels_cat.csv" outdir = cwd / f"output-s_{seed}-n_{n_blends}" if not outdir.exists(): outdir.mkdir() outlog = outdir / "candels-blender.log" logging.basicConfig( filename=outlog, level=logging.INFO, format="%(asctime)s [ %(levelname)s ] : %(message)s", ) blender = Blender( input_stamps, input_segmaps, input_catalog, train_test_ratio=test_ratio, magdiff=mag_diff, raddiff=rad_diff, seed=seed, ) logger = logging.getLogger(__name__) logger.info( "\n" "Configuration\n" "=============\n" f"Number of blends: {n_blends}\n" f"Seed: {seed}\n" "\n" "Catalog cuts\n" "------------\n" f"Excluded galaxy types: {excluded_type}\n" f"Lowest magnitude: {mag_low}\n" f"Highest magnitude: {mag_high}\n" "\n" "Blend properties\n" "----------------\n" f"Top difference in magnitude between galaxies: {mag_diff}\n" f"Top distance between galaxies as a fraction of radius: {rad_diff}\n") # Apply cuts to the galaxy catalog click.echo( f"Selecting galaxies in the magnitude range {mag_low} < m < {mag_high}" ) blender.make_cut(blender.cat.mag > mag_low) blender.make_cut(blender.cat.mag < mag_high) for galtype in set(excluded_type): click.echo(f"Excluding {galtype} galaxies") blender.make_cut(blender.cat.galtype != galtype) click.echo( f"After the cuts, there are {blender.n_gal} individual galaxies " "left in the catalog.") # Compute the train/test splits n_test = int(test_ratio * n_blends) n_train = n_blends - n_test create_image_set(blender, n_train, outdir) create_image_set(blender, n_test, outdir, test_set=True) click.echo(message=f"Images stored in {outdir}")