def render(self, field, key, value, REQUEST, render_prefix=None): """ This is where most things happens """ main_content = "" here = REQUEST['here'] selection_name = field.get_value('selection_name') default_params = field.get_value('default_params') chart_title = field.get_value('chart_title') data_method = field.get_value('data_method') chart_style = field.get_value('chart_style') x_title = field.get_value('x_title') y_title = field.get_value('y_title') bg_transparent = field.get_value('bg_transparent') selection = here.portal_selections.getSelectionFor(selection_name, REQUEST=REQUEST) LOG('ZGDChart.render',0,'selection: %s, selection_name: %s' % (str(selection), str(selection_name))) # This is the default data, this is just in the case there is not method given data = {'chart_data':[]} # Retrieve the data with the data_method if hasattr(here,data_method): LOG('ZGDChart.render',0,'found method') data_method = getattr(here,data_method) data['chart_data'] = data_method() data['chart_parameter'] = {'zgdchart_runtime_title':chart_title, 'zgdchart_runtime_xtitle':x_title, 'zgdchart_runtime_ytitle':y_title, 'zgdchart_runtime_type':'Line_3D', 'zgdchart_runtime_bg_transparent':bg_transparent} # Creation selection if needed if selection is None: selection = Selection(selection_name, params=data) else: LOG('ZGDChart.render',0,'selection is not None') kw = {'params':data} selection.edit(**kw) here.portal_selections.setSelectionFor(selection_name, selection, REQUEST=REQUEST) if len(data['chart_data']) > 0: main_content = """\ <div class="ChartContent"> <table border="0" cellpadding="0" cellspacing="0""> <tr> <td valign="middle" align="center" nowrap> <img src="%s" title="Chart" border="0" alt="img"/"> </td> </tr> </table> </div>""" % str(chart_style + '?selection_name=' + selection_name) return main_content
def main(): args = argsParser() args.parse('args.xml') if args.fitnessFunction == "euclidean" : fitOp = EuclideanDistFit(args.input1, args.input2) elif args.fitnessFunction == "manhattan" : fitOp = ManhattanDistFit(args.input1, args.input2) elif args.fitnessFunction == "minkowski" : fitOp = MinkowskiDistFit(args.input1, args.input2, args.p) elif args.fitnessFunction == "linear" : fitOp = LinearInterpolation(args.input1, args.input2, args.euclF, args.manhF) else : raise "Something went wrong while assigning the fitness function" # if args.selection == "tournament" : selOp = Selection.tournament elif args.selection == "elimination": selOp = Selection.elimination else : raise "Something went wrong while assigning the selection operator" if args.elitism == 0: Selection.setElitism(0) elif args.elitism == 1: Selection.setElitism(1) else : raise "Something went wrong while assigning elitism" crossOp = Crossover.crossover mutationOp = Mutation.mutation if args.batch == 1: p = Population(args.populationSize, fitOp, selOp, crossOp, mutationOp) p.evaluateAll() run (p, args) writeOut(args.outputFile, p) else: for i in range(0, args.batch): print "\nBatch: %d/%d" %(i+1, args.batch) p = Population(args.populationSize, fitOp, selOp, crossOp, mutationOp) p.evaluateAll() run (p, args) writeOutBatch(i+1, p)
def __sort(algs, data): if 'insertion' == algs: Insertion.sort(data) if 'insertion_advance' == algs: Insertion.sort_advance(data) if 'selection' == algs: Selection.sort(data) if 'shell' == algs: Shell.sort(data) if 'merge' == algs: Merge.sort(data)
def solve(self): ''' evolution process of differential evolution algorithm ''' self.t = 0 self.initialize() for i in range(0, self.sizepop): self.evaluate(self.population[i]) self.fitness[i] = self.population[i].fitness best = np.max(self.fitness) bestIndex = np.argmax(self.fitness) self.best = copy.deepcopy(self.population[bestIndex]) self.avefitness = np.mean(self.fitness) self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness print("当前代数 %d: 最优个体适应度值: %f; 当代平均适应度值 %f; " % (self.t, self.trace[self.t, 0], self.trace[self.t, 1])) # print("最有个体:") # print(self.best.chrom) while (self.t < self.MAXGEN - 1): self.t += 1 for i in range(0, self.sizepop): # 遗传操作 mutation = Mutation(self.vardim, self.bound, self.sizepop, self.population, self.params) vi = mutation.Random_3_different_current_mutation(i) crossover = Crossover(self.vardim, self.population, self.params) ui = crossover.Standard_Crossover(i, vi) selection = Selection(self.population) xi_next = selection.selectionOperation(i, ui) self.population[i] = xi_next for i in range(0, self.sizepop): self.evaluate(self.population[i]) self.fitness[i] = self.population[i].fitness best = np.max(self.fitness) bestIndex = np.argmax(self.fitness) if best > self.best.fitness: self.best = copy.deepcopy(self.population[bestIndex]) self.avefitness = np.mean(self.fitness) self.trace[self.t, 0] = (1 - self.best.fitness) / self.best.fitness self.trace[self.t, 1] = (1 - self.avefitness) / self.avefitness print("当前代数 %d: 最优个体适应度值: %f; 当代平均适应度值 %f; " % (self.t, self.trace[self.t, 0], self.trace[self.t, 1])) # print("最优个体:") # print(self.best.chrom) print("Optimal function value is: %f; " % self.trace[self.t, 0]) print("Optimal solution is:") print(self.best.chrom) self.printResult()
def download(self, selection_name=None, data_method=None, REQUEST=None, **kw): """ This is where we actually render the chart. The main interest of doing like this is to accelerate initial rendering TODO: - add minimal security here - implement all pychart options (PNG, PS, SVG, etc.) - implement all standard parameters """ # Get the applicable selection selection = self.portal_selections.getSelectionFor(selection_name, REQUEST=REQUEST) # If selection is None, create a new one if selection is None: selection = Selection(selection_name) # Get the data method if defined if data_method is not None: here = REQUEST.get('here', self) data_method = getattr(here, data_method, None) # This is the default data, this is just in the case there is not method given if data_method is None: data = selection() else: data = selection(data_method=data_method) # Now call the script - XXX implement bindings properly here output = self._exec(here=self, pychart=pychart, data=data) # And return result return output
def __init__(self, generator, fitness, mutation, sizeOfPopulation, genPopulation, selection=None, crossover=None, numberChromosome=None, epoche=100, error=0.001, stopFunctionChange=False, data=None, **kwargs): self.generator = generator self.fitness = fitness if selection is None: selection = Selection('empty') self.selection = selection if crossover is None: crossover = Crossover('empty') self.crossover = crossover self.mutation = mutation self.sizeOfPopulation = sizeOfPopulation self.stopFunctionChange = stopFunctionChange self.populationGen = genPopulation self.numberChromosome = numberChromosome self.epoche = epoche self.error = error self.data = data self.otherArgs = kwargs
def _loop(self): done = False clock = pg.time.Clock() while not done: clock.tick(FPS) self._drawMe() pg.display.flip() for event in pg.event.get(): if event.type == pg.VIDEORESIZE: self._resize(event.w, event.h) if event.type == pg.QUIT: done = True break if event.type == pg.KEYDOWN: if event.key == pg.K_s: self._solve() if event.key == pg.K_z: self._wipe() if event.key == pg.K_r: self._reset() if event.key == pg.K_a: done = True break if event.type == pg.MOUSEBUTTONDOWN: self._mouseClicHandeler() from Selection import Selection pg.quit() Selection()
def __init__(self, name, deck_name, game_config): self.deck = Deck(deck_name) self.home_pile = HomePile(game_config.home_pile_size) self.cell_cards = CellCards(self.home_pile) self.stock_pile = StockPile() self.right_hand = RightHand() self.discard_pile = DiscardPile() self.home_pile.take_from(self.deck) self.cell_cards.take_from(self.deck) self.stock_pile.take_from(self.deck) self.set_locations() # Move cards to their proper locations self.home_pile.calibrate() self.cell_cards.calibrate() self.stock_pile.calibrate() # Start out with cell cards face down for cell in self.cell_cards.each_cell(): cell.face_down() # self.selection = Selection() self.drawables = [self.home_pile, self.cell_cards, self.stock_pile, self.discard_pile, self.right_hand, self.selection] self.clickables = [self.home_pile, self.cell_cards, self.discard_pile] self.updateables = [] self.xxxcount = 0 self.score = 0 self.cards_in_transit = [] self.name = name louie.connect(self.card_grabbed, Card.grabbed) louie.connect(self.card_thrown, Card.thrown) louie.connect(self.home_emptied, HomePile.emptied)
def __init__(self, parent, mainmesh=True, hfs=[]): self.mainmesh = mainmesh self.parent = parent self.fab_directions = [0, 1] #Initiate list of fabircation directions for i in range(1, self.parent.noc - 1): self.fab_directions.insert(1, 1) if len(hfs) == 0: self.height_fields = get_random_height_fields( self.parent.dim, self.parent.noc) #Initiate a random joint geometry else: self.height_fields = hfs if self.mainmesh: self.select = Selection(self) self.voxel_matrix_from_height_fields(first=True)
def createDummyTask(conn): ts = time.time() isodate = datetime.datetime.fromtimestamp(ts, None) accCol = conn["user"]["account"] acc = accCol.find_one({}) accid = str(acc["_id"]) coll = conn["experiment"]["task"] sell = list() selid = str(Selection.createDummySelection(conn)) sell.append(selid) post = { \ "name": "Dummy task", \ "status": "Active", \ "start": isodate, \ "end": isodate, \ "account_id": accid, \ "parameters": "a2+b2=c2", \ "selection_ids": sell, \ "result_file": "None" \ } coll.insert(post) coll.ensure_index("name", unique=True) coll.ensure_index("account_id")
from Selection import Selection if __name__ == '__main__': Selection()
def __init__(self, x, y): super().__init__(x, y) self.image = Sprites.CURSOR self.collides = False self.selection_1 = Selection(0, 0) self.selection_2 = Selection(0, 0)
from Mutation import Mutation import utils aptamerType = str(sys.argv[1]) aptamerNum = int(sys.argv[2]) seqLength = int(sys.argv[3]) selectionThreshold = long(sys.argv[4]) roundNum = int(sys.argv[5]) pcrCycleNum = int(sys.argv[6]) pcrYield = float(sys.argv[7]) pcrErrorRate = float(sys.argv[8]) outputFileNames = str(sys.argv[9]) # Instantiating classes Apt = Aptamers() S = Selection() Amplify = Amplification() Mut = Mutation() # SELEX simulation based on random aptamer assignment, hamming-based definite selection, and # non-ideal stochastic amplfication with no bias. for r in range(roundNum): if(r==0): if(aptamerType == 'DNA'): alphabetSet = 'ACGT' aptamerSeqs, initialSeqNum = Apt.optimumAptamerGenerator(aptamerNum, alphabetSet, seqLength) elif(aptamerType == 'RNA'): alphabetSet = 'ACGU' aptamerSeqs, initialSeqNum = Apt.optimumAptamerGenerator(aptamerNum, alphabetSet, seqLength) else: print("Error: Simulation of %.s aptamers not supported" %aptamerType)
def __init__(self, **kwargs): for key, value in kwargs.items(): if key == 'genetarion': self.generation_size = value elif key == 'population': self.population_size = value elif key == 'limit_population': self.limit_population = value elif key == 'crossover_rate': self.crossover_rate = value elif key == 'mutation_rate': self.mutation_rate = value elif key == 'map_points': self.map_points = value elif key == 'max_coust': self.max_coust = value elif key == 'coust_rate': self.coust_rate = value elif key == 'prizes_rate': self.prizes_rate = value elif key == 'start_point': self.start_point = value elif key == 'end_point': self.end_point = value elif key == 'prizes': prizes = np.loadtxt(value) self.prizes = prizes[:, 1] elif key == 'initial_cromossome': self.initial_cromossome = value self.best_route = value self.receive_route = True # as variáveis # self.generation_size = genetarion # self.population_size = population # self.limit_population = limit_population # self.crossover_rate = crossover_rate # self.mutation_rate = mutation_rate # self.map_points = map_points # self.max_coust = max_coust # self.start_point = np.array([start_point]) # self.end_point = np.array([end_point]) # self.prizes = np.loadtxt(prizes) self.mapa = np.loadtxt(self.map_points) self.distance_matrix_calculate() if 'initial_cromossome' not in locals(): self.initial_cromossome = np.arange(self.mapa.shape[0]) self.receive_route = False if self.start_point != self.end_point: self.initial_cromossome = np.delete( self.initial_cromossome, [self.start_point, self.end_point]) else: self.initial_cromossome = np.delete(self.initial_cromossome, [self.start_point]) self.mutation_object = Mutation(self.max_coust, self.prizes) self.mutation = self.mutation_object.scramble self.crossover_class = Crossover() self.crossover = self.crossover_class.PMX self.Population = Population(self.start_point, self.end_point, self.med_custo, self.max_coust) self.Selection_object = Selection() self.selection = self.Selection_object.tournament
def __init__( self, board, primaryObjectFamilies, secondaryObjectFamilies, primarySurfaceFamilies, secondarySurfaceFamilies ): gtk.HBox.__init__( self, False, 0 ) self.board = board self.board.registerView( self ) self.selection = Selection( self ) self.mouseManager = MouseManager.MouseManager( self ) for family in primaryObjectFamilies: self.selection.addObjects( family ) for family in primarySurfaceFamilies: self.selection.addSurfaces( family ) self.__scale = MapView.__pixelPerUnit * 4 self.__translateX = 0 self.__translateY = 0 self.__sisterViews = list() self.drawingArea = gtk.DrawingArea() self.drawingArea.connect( "expose-event", self.__onExposeEvent ) self.drawingArea.set_events( gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK ) self.drawingArea.show() toolBar = gtk.Toolbar() toolBar.set_orientation( gtk.ORIENTATION_VERTICAL ) self.__objectFamilies = primaryObjectFamilies + secondaryObjectFamilies self.__surfaces = list() for family in secondarySurfaceFamilies + primarySurfaceFamilies: for surface in GameItemTypes.surfaces[ family ]: self.__surfaces.append( surface ) toolBar.append_item( _( "Select/Move" ), "", "", None, lambda widget: self.resetMouseManager() ) for family in primarySurfaceFamilies: for surface in GameItemTypes.surfaces[ family ]: if GameItemTypes.attributes[ surface ][ "BuiltByLengths" ]: menu = gtk.Menu() item = gtk.MenuItem( _( "Length" ) ) menu.append( item ) item.connect( "activate", lambda widget, surfaceType: self.mouseManager.setState( MouseManager.StartInsertSurface, surfaceType, MouseManager.SurfaceLength() ), surface ) item.show() item = gtk.MenuItem( _( "Rectangle" ) ) menu.append( item ) item.connect( "activate", lambda widget, surfaceType: self.mouseManager.setState( MouseManager.StartInsertSurface, surfaceType, MouseManager.SurfaceRectangle() ), surface ) item.show() toolBar.append_item( _( surface ), "", "", None, lambda widget, menu: menu.popup( None, None, None, 3, 0 ), menu ) else: toolBar.append_item( _( surface ), "", "", None, lambda widget, surfaceType: self.mouseManager.setState( MouseManager.StartInsertSurface, surfaceType, MouseManager.SurfaceRectangle() ), surface ) for family in primaryObjectFamilies: for category, subCategories in GameItemTypes.objects[ family ].iteritems(): menu = gtk.Menu() for subCategory, buildingTypes in subCategories.iteritems(): for buildingType in buildingTypes: item = gtk.MenuItem( _( buildingType ) ) menu.append( item ) item.connect( "activate", lambda widget, buildingType: self.mouseManager.setState( MouseManager.InsertingObject, buildingType ), buildingType ) if not self.board.isAvailable( buildingType ): item.set_sensitive( False ) item.show() toolBar.append_item( _( category ), "", "", None, lambda widget, menu: menu.popup( None, None, None, 3, 0 ), menu ) toolBar.show() self.pack_end( toolBar, False, False, 2 ) self.pack_start( self.drawingArea, True, True, 2 )
def __init__(self, map_points, iterations, size_population, beta, alfa, cost_rate, prizes_rate, prizes, max_cost, start_point, end_point, depositos=[]): self.map_points = np.loadtxt(map_points) self.iterations = iterations self.size_population = size_population self.beta = beta self.alfa = alfa self.cost_rate = np.array(cost_rate) self.prizes_rate = prizes_rate self.prizes = np.loadtxt(prizes)[:, 1] self.max_cost = np.array(max_cost) self.start_point = start_point self.end_point = end_point self.depositos = depositos self.particles = [] self.number_agents = len(max_cost) self.distance = calculate_distances(self.map_points) self.functionObject = FunctionObjective(self.map_points, self.prizes) self.FO = self.functionObject.FO self.mensureCost = self.functionObject.med_custo self.methodInsertRemoveChromosome = self.functionObject.coust_insert self.allElementsMap = np.arange(self.map_points.shape[0]) self.allElementsMap = self.allElementsMap[self.number_agents:] # removendo depositos deposits = [x for x in self.start_point] deposits += [x for x in self.end_point if x not in deposits] deposits = np.unique(np.array(deposits)) self.initialChromossome = np.arange(self.map_points.shape[0]) self.initialChromossome = np.delete(self.initialChromossome, self.depositos) self.allElementsMap = np.copy(self.initialChromossome) self.mutationObject = Mutation(self.mensureCost, self.max_cost, self.prizes) self.mutation = self.mutationObject.scramble self.crossoverObject = Crossover() self.crossover = self.crossoverObject.cross_TOPMD self.PopulationObject = Population(self.start_point, self.end_point, self.mensureCost, self.max_cost, self.distance) self.SelectionObject = Selection() self.selection = self.SelectionObject.tournament solutions = self.PopulationObject.initializeTopMdGreed2( self.initialChromossome, self.size_population, self.number_agents, 1) for s in solutions: particle = Particle(route=s, mensure_function=self.mensureCost, fitness_function=self.FO) self.particles.append(particle)
class Player: """ A player in the game. """ finished = louie.Signal() def __init__(self, name, deck_name, game_config): self.deck = Deck(deck_name) self.home_pile = HomePile(game_config.home_pile_size) self.cell_cards = CellCards(self.home_pile) self.stock_pile = StockPile() self.right_hand = RightHand() self.discard_pile = DiscardPile() self.home_pile.take_from(self.deck) self.cell_cards.take_from(self.deck) self.stock_pile.take_from(self.deck) self.set_locations() # Move cards to their proper locations self.home_pile.calibrate() self.cell_cards.calibrate() self.stock_pile.calibrate() # Start out with cell cards face down for cell in self.cell_cards.each_cell(): cell.face_down() # self.selection = Selection() self.drawables = [self.home_pile, self.cell_cards, self.stock_pile, self.discard_pile, self.right_hand, self.selection] self.clickables = [self.home_pile, self.cell_cards, self.discard_pile] self.updateables = [] self.xxxcount = 0 self.score = 0 self.cards_in_transit = [] self.name = name louie.connect(self.card_grabbed, Card.grabbed) louie.connect(self.card_thrown, Card.thrown) louie.connect(self.home_emptied, HomePile.emptied) def draw(self, surface): for drawable in self.drawables: drawable.draw(surface) for card in self.cards_in_transit: card.draw(surface) def set_locations(self): """ Position cards """ some_card = self.home_pile.top_card() card_width, card_height = some_card.rect.width, some_card.rect.height left_margin, top_margin = 15, 450 hand_top_margin = top_margin + card_height + 10 x, y = left_margin, top_margin # Top row self.home_pile.move_to(x, y) x += card_width * 1.7 distance_between = card_width * 1.3 self.cell_cards.move_to(x, y, distance_between) x = left_margin + card_width * 0.2 y = hand_top_margin # Bottom row self.stock_pile.move_to(x, y) x += card_width * 1.5 self.discard_pile.move_to(x, y) x += card_width * 1.5 self.right_hand.move_to(x, y, 40) def update(self): for updateable in self.updateables: updateable.update() for card in self.cards_in_transit: card.update() def handle(self, event): """ Handle events that the player knows about. """ if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: self.handle_left_mouse_down(event) elif event.button == 3: self.handle_right_mouse_down(event) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: self.handle_space_bar() def handle_left_mouse_down(self, event): """ Handle a left click. """ x, y = event.pos[0], event.pos[1] for clickable in self.clickables: card = clickable.get_card(x, y) if card is not None: if not self.selection.empty() and \ self.selection.card == card: # Clear the selection if the card is already selected self.selection.clear() else: # Otherwise select the card self.selection.set(card, clickable) return # Stock pile clicks if self.stock_pile.contains(x, y): self.deal_card() def handle_right_mouse_down(self, event): """ Handle a right click. """ self.deal_card() def handle_space_bar(self): """ Handle a space bar keypress. """ self.deal_card() def deal_card(self): """ Shuffle from stock_pile to discard_pile Place in hand if count < 3, otherwise place in discard pile, count = 0 """ if self.xxxcount != 0 and self.stock_pile.cards.empty(): self.xxxcount = 3 self.xxxcount += 1 if self.xxxcount == 4: self.discard_pile.take_from(self.right_hand) self.discard_pile.calibrate() self.xxxcount = 0 if self.has_selection() and \ self.selection.home == self.discard_pile: # Clear the selection if it's the discard pile self.clear_selection() else: if self.stock_pile.cards.empty(): self.stock_pile.take_from(self.discard_pile.cards) self.stock_pile.calibrate() self.right_hand.take_from(self.stock_pile.cards) self.right_hand.calibrate() def home_emptied(self): louie.send(Player.finished) def inc_score(self): self.score += 1 def get_score(self): """ Returns the total score """ return self.num_good_cards() - self.num_bad_cards() * 2 def num_good_cards(self): """ Returns the number of cards put out """ return self.score def num_bad_cards(self): """ Returns the number of cards still in the home pile """ return self.home_pile.cards.num_cards() def card_thrown(self, card): self.cards_in_transit.append(card) def card_grabbed(self, card): self.cards_in_transit.remove(card) def get_selection(self): """ Returns the current selection. """ return self.selection def has_selection(self): """ Returns true if there is a card selected. """ return not self.selection.empty() def clear_selection(self): self.selection.clear() def get_name(self): return self.name def flip_cell(self, cell_index): self.cell_cards.get_cell(cell_index).flip()
def time(alg, a): timer = Stopwatch() if alg == "Insertion": Insertion.sort(a) if alg == "Selection": Selection.sort(a) if alg == "Shell": Shell.sort(a) return timer.elapsedTime()
roundNum = settings.getint('general', 'number_of_rounds') outputFileNames = settings.get('general', 'experiment_name') samplingSize = settings.getint('general', 'sampling_size') post_process = settings.get('general', 'post_process') selectionThreshold = settings.getint('selectionparams', 'scale') distanceMeasure = settings.get('selectionparams', 'distance') stringency = settings.getint('selectionparams', 'stringency') pcrCycleNum = settings.getint('amplificationparams', 'number_of_pcr') pcrYield = settings.getfloat('amplificationparams', 'pcr_efficiency') pcrerrorRate = settings.getfloat('amplificationparams', 'pcr_error_rate') # Instantiating the appropriate classes Apt = Aptamers() S = Selection() Amplify = Amplification() Mut = Mutation() if (distanceMeasure == "hamming"): # SELEX simulation based on random aptamer assignment, hamming-based stochastic selection, and # non-ideal stochastic amplfication with pyrimidine-based bias. for r in range(roundNum): if (r == 0): if (aptamerType == 'DNA'): alphabetSet = 'ACGT' aptamerSeqs, initialSeqNum = Apt.optimumAptamerGenerator( aptamerNum, alphabetSet, seqLength) elif (aptamerType == 'RNA'): alphabetSet = 'ACGU' aptamerSeqs, initialSeqNum = Apt.optimumAptamerGenerator(
def __init__(self, **kwargs): for key, value in kwargs.items(): if key == 'genetarion': self.generation_size = value elif key == 'population': self.population_size = value elif key == 'limit_population': self.limit_population = value elif key == 'crossover_rate': self.crossover_rate = value elif key == 'mutation_rate': self.mutation_rate = value elif key == 'map_points': self.map_points = value elif key == 'max_coust': self.max_coust = np.array(value) elif key == 'coust_rate': self.coust_rate = value elif key == 'prizes_rate': self.prizes_rate = value elif key == 'start_point': self.start_point = value elif key == 'end_point': self.end_point = value elif key == 'prizes': prizes = np.loadtxt(value) self.prizes = prizes[:, 1] elif key == 'initial_cromossome': self.initial_cromossome = value self.best_route = value self.receive_route = True elif key == 'number_agents': self.number_agents = value self.mapa = np.loadtxt(self.map_points) self.distance_matrix_calculate() self.FunctionObject = FunctionObjective(self.mapa, self.prizes) self.function_objective = self.FunctionObject.FO self.med_custo = self.FunctionObject.med_custo self.function_insert_remove = self.FunctionObject.coust_insert # todos os pontos de um mapa self.all_elements = np.arange(self.mapa.shape[0]) if 'initial_cromossome' not in locals(): self.initial_cromossome = np.arange(self.mapa.shape[0]) self.receive_route = False if self.start_point != self.end_point: self.initial_cromossome = np.delete( self.initial_cromossome, [self.start_point, self.end_point]) else: self.initial_cromossome = np.delete(self.initial_cromossome, [self.start_point]) self.mutation_object = Mutation(self.med_custo, self.max_coust, self.prizes) self.mutation = self.mutation_object.scramble self.crossover_class = Crossover() self.crossover = self.crossover_class.cross_TOP self.Population = Population(self.start_point, self.end_point, self.med_custo, self.max_coust) self.Selection_object = Selection() self.selection = self.Selection_object.tournament
def render(self, field, key, value, REQUEST, render_prefix=None): """ This is where most things happens """ main_content = "" here = REQUEST['here'] selection_name = field.get_value('selection_name') default_params = field.get_value('default_params') chart_title = field.get_value('chart_title') data_method = field.get_value('data_method') chart_style = field.get_value('chart_style') x_title = field.get_value('x_title') y_title = field.get_value('y_title') bg_transparent = field.get_value('bg_transparent') selection = here.portal_selections.getSelectionFor(selection_name, REQUEST=REQUEST) LOG( 'ZGDChart.render', 0, 'selection: %s, selection_name: %s' % (str(selection), str(selection_name))) # This is the default data, this is just in the case there is not method given data = {'chart_data': []} # Retrieve the data with the data_method if hasattr(here, data_method): LOG('ZGDChart.render', 0, 'found method') data_method = getattr(here, data_method) data['chart_data'] = data_method() data['chart_parameter'] = { 'zgdchart_runtime_title': chart_title, 'zgdchart_runtime_xtitle': x_title, 'zgdchart_runtime_ytitle': y_title, 'zgdchart_runtime_type': 'Line_3D', 'zgdchart_runtime_bg_transparent': bg_transparent } # Creation selection if needed if selection is None: selection = Selection(selection_name, params=data) else: LOG('ZGDChart.render', 0, 'selection is not None') kw = {'params': data} selection.edit(**kw) here.portal_selections.setSelectionFor(selection_name, selection, REQUEST=REQUEST) if len(data['chart_data']) > 0: main_content = """\ <div class="ChartContent"> <table border="0" cellpadding="0" cellspacing="0""> <tr> <td valign="middle" align="center" nowrap> <img src="%s" title="Chart" border="0" alt="img"/"> </td> </tr> </table> </div>""" % str(chart_style + '?selection_name=' + selection_name) return main_content
def pushReport(self, context, render_prefix=None): self.pushRequest() REQUEST = get_request() portal_selections = context.portal_selections selection_list = [self.selection_name] # when the Form which is specified by form_id, has a listbox, make prefixed_selection_name. # which is based on specified selection_name in the listbox. form_id = self.getFormId() if form_id: listbox = getattr(getattr(context, form_id), 'listbox', None) if listbox is not None: selection_name = listbox.get_value('selection_name') if render_prefix is not None: selection_name = '%s_%s' % (render_prefix, selection_name) REQUEST.other['prefixed_selection_name'] = selection_name selection_list.append(selection_name) # save report's selection and orignal form's selection, #as ListBox will overwrite it for selection_name in filter(lambda x: x is not None, selection_list): if self.temporary_selection: portal_selections.pushSelection(selection_name) else: if portal_selections.getSelectionFor(selection_name) is None: portal_selections.setSelectionFor(selection_name, Selection(selection_name)) if self.selection_report_list is not None: selection = portal_selections.getSelectionFor(selection_name, REQUEST=REQUEST) selection.edit(report_list=self.selection_report_list) if self.selection_report_path is not None: selection = portal_selections.getSelectionFor(selection_name, REQUEST=REQUEST) selection.edit(report_path=self.selection_report_path) if self.listbox_display_mode is not None: # XXX Dirty fix, to be able to change the display mode in form_view REQUEST.list_selection_name = selection_name portal_selections.setListboxDisplayMode(REQUEST, self.listbox_display_mode, selection_name=selection_name) if self.selection_params is not None: params = portal_selections.getSelectionParamsFor(selection_name, REQUEST=REQUEST) params.update(self.selection_params) portal_selections.setSelectionParamsFor(selection_name, params, REQUEST=REQUEST) if self.selection_columns is not None: portal_selections.setSelectionColumns(selection_name, self.selection_columns, REQUEST=REQUEST) if self.selection_sort_order is not None: portal_selections.setSelectionSortOrder(selection_name, self.selection_sort_order, REQUEST=REQUEST) if self.selection_stats is not None: portal_selections.setSelectionStats(selection_name, self.selection_stats, REQUEST=REQUEST) # When rendering a report section with a listbox, listbox gets parameters # from request.form and edits selection with those parameters, so if you # happen to pass explicitly selection params that have the same name as # some request parameters (some dialog fields) but different values, # listbox would not use your explicit parameters, but the ones from # REQUEST.form, so we remove eventual request parameters that have the same # name of selections parameters passed explicitly. for selection_parameter in (self.selection_params or ()): REQUEST.form.pop(selection_parameter, None)
class MapView( gtk.HBox ): __pixelPerUnit = 2.5 # 2.5 means 5 pixels per Tile (a tile is two units) def __init__( self, board, primaryObjectFamilies, secondaryObjectFamilies, primarySurfaceFamilies, secondarySurfaceFamilies ): gtk.HBox.__init__( self, False, 0 ) self.board = board self.board.registerView( self ) self.selection = Selection( self ) self.mouseManager = MouseManager.MouseManager( self ) for family in primaryObjectFamilies: self.selection.addObjects( family ) for family in primarySurfaceFamilies: self.selection.addSurfaces( family ) self.__scale = MapView.__pixelPerUnit * 4 self.__translateX = 0 self.__translateY = 0 self.__sisterViews = list() self.drawingArea = gtk.DrawingArea() self.drawingArea.connect( "expose-event", self.__onExposeEvent ) self.drawingArea.set_events( gtk.gdk.EXPOSURE_MASK | gtk.gdk.LEAVE_NOTIFY_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.POINTER_MOTION_HINT_MASK ) self.drawingArea.show() toolBar = gtk.Toolbar() toolBar.set_orientation( gtk.ORIENTATION_VERTICAL ) self.__objectFamilies = primaryObjectFamilies + secondaryObjectFamilies self.__surfaces = list() for family in secondarySurfaceFamilies + primarySurfaceFamilies: for surface in GameItemTypes.surfaces[ family ]: self.__surfaces.append( surface ) toolBar.append_item( _( "Select/Move" ), "", "", None, lambda widget: self.resetMouseManager() ) for family in primarySurfaceFamilies: for surface in GameItemTypes.surfaces[ family ]: if GameItemTypes.attributes[ surface ][ "BuiltByLengths" ]: menu = gtk.Menu() item = gtk.MenuItem( _( "Length" ) ) menu.append( item ) item.connect( "activate", lambda widget, surfaceType: self.mouseManager.setState( MouseManager.StartInsertSurface, surfaceType, MouseManager.SurfaceLength() ), surface ) item.show() item = gtk.MenuItem( _( "Rectangle" ) ) menu.append( item ) item.connect( "activate", lambda widget, surfaceType: self.mouseManager.setState( MouseManager.StartInsertSurface, surfaceType, MouseManager.SurfaceRectangle() ), surface ) item.show() toolBar.append_item( _( surface ), "", "", None, lambda widget, menu: menu.popup( None, None, None, 3, 0 ), menu ) else: toolBar.append_item( _( surface ), "", "", None, lambda widget, surfaceType: self.mouseManager.setState( MouseManager.StartInsertSurface, surfaceType, MouseManager.SurfaceRectangle() ), surface ) for family in primaryObjectFamilies: for category, subCategories in GameItemTypes.objects[ family ].iteritems(): menu = gtk.Menu() for subCategory, buildingTypes in subCategories.iteritems(): for buildingType in buildingTypes: item = gtk.MenuItem( _( buildingType ) ) menu.append( item ) item.connect( "activate", lambda widget, buildingType: self.mouseManager.setState( MouseManager.InsertingObject, buildingType ), buildingType ) if not self.board.isAvailable( buildingType ): item.set_sensitive( False ) item.show() toolBar.append_item( _( category ), "", "", None, lambda widget, menu: menu.popup( None, None, None, 3, 0 ), menu ) toolBar.show() self.pack_end( toolBar, False, False, 2 ) self.pack_start( self.drawingArea, True, True, 2 ) def __onExposeEvent( self, widget, event ): self.ctx = self.drawingArea.window.cairo_create() self.__applyTranscale() self.__drawboard() self.__drawGrid() self.mouseManager.draw() def __drawboard( self ): self.ctx.save() self.ctx.set_source_rgb( 0.9, 0.9, 1 ) self.ctx.paint() self.__drawSurfaces() self.__drawObjects() self.__drawSelection() self.__drawService() self.ctx.restore() def __drawSurfaces( self ): for surface in self.__surfaces: self.__drawSurface( surface ) def __drawSurface( self, surface ): self.__drawPolygons( self.board.getSurface( surface ).polygons, *GameItemTypes.getSurfaceColor( surface ) ) def __drawPolygons( self, polygons, r, g, b, a ): self.ctx.save() self.ctx.set_source_rgba( r, g, b, a ) pathPolygons( self.ctx, polygons ) self.ctx.fill() self.ctx.restore() def __drawObjects( self ): for objectFamily in self.__objectFamilies: self.__drawObjectFamily( objectFamily ) def __drawObjectFamily( self, family ): self.ctx.save() for o in self.board.getObjectsByFamily( family ): self.__drawObject( o ) self.ctx.restore() def __drawObject( self, o ): self.drawObjectInPolygon( o.type, o.polygon, o.rotation ) if o.hasProblem: pathPolygons( self.ctx, o.polygon.polygons ) self.ctx.set_source_rgba( 1, 0, 0, 0.5 ) self.ctx.fill() def drawObjectInPolygon( self, resourceType, polygon, rotation ): matrix = cairo.Matrix() matrix.scale( MapView.__pixelPerUnit, MapView.__pixelPerUnit ) x, y = polygon.center width, height = GameItemTypes.getObjectSize( resourceType ) matrix.translate( width, height ) matrix.rotate( -rotation * math.pi / 4 ) matrix.translate( -x, -y ) pattern = PatternRepository.getPattern( "buildings", resourceType ) pattern.set_matrix( matrix ) self.ctx.set_source( pattern ) self.ctx.paint() def drawObjectNeeds( self, o ): self.ctx.save() self.ctx.set_font_size( 15 ) maxWidth = 0 self.ctx.save() self.ctx.identity_matrix() texts = dict() for surface, ( needs, interaction, check ) in o.needs.iteritems(): if needs == check: color = ( 0, 0, 0 ) elif needs: color = ( 0.6, 0, 0 ) else: color = ( 0, 0.5, 0 ) if needs: needsLikes = "Needs" else: needsLikes = "Likes" text = _( needsLikes + "." + surface + "." + str( interaction ) ) x_bearing, y_bearing, width, height, x_advance, y_advance = self.ctx.text_extents( text ) maxWidth = max( maxWidth, width ) texts[ text ] = color self.ctx.restore() x, y = o.polygon.center self.ctx.save() self.ctx.translate( x, y ) self.ctx.scale( 1. / self.__scale, 1. / self.__scale ) self.ctx.set_source_rgb( 1, 1, 0.6 ) self.ctx.rectangle( -5, -2, maxWidth + 10, len( texts ) * 15 + 10 ) self.ctx.identity_matrix() self.ctx.fill_preserve() self.ctx.set_source_rgba( 0, 0, 0, 1 ) self.ctx.stroke() self.ctx.restore() i = 0 for text in sorted( texts.keys() ): i += 15 color = texts[ text ] self.ctx.set_source_rgb( *color ) self.ctx.move_to( x, y ) self.ctx.save() self.ctx.identity_matrix() self.ctx.rel_move_to( 0, i ) self.ctx.show_text( text ) self.ctx.restore() self.ctx.restore() def __drawSelection( self ): self.ctx.save() pathPolygons( self.ctx, self.selection.getPolygons() ) self.ctx.identity_matrix() self.ctx.set_source_rgb( 0, 0, 0 ) self.ctx.set_line_width( 4 ) self.ctx.stroke() self.ctx.restore() def __drawService( self ): self.ctx.save() wall = self.selection.getSurface( "Wall" ).tiles if len( self.selection.objects ) == 1 and len( wall ) == 0: ( o, ) = self.selection.objects if "Service.Name" in o.attributes: self.__drawSurface( "Service." + o.attributes[ "Service.Name" ] ) if len( wall ) != 0 and len( self.selection.objects ) == 0: self.__drawSurface( "Security" ) water = self.selection.getSurface( "Water" ).tiles if len( water ) != 0: self.__drawSurface( "Shoreline" ) self.ctx.restore() def __drawGrid( self ): self.ctx.save() upperBound = 2 * self.board.size self.ctx.rectangle( 0, 0, upperBound, upperBound ) if self.__scale > self.__pixelPerUnit * 2: for i in range( 0, upperBound + 1, 2 ): self.ctx.move_to( 0, i ) self.ctx.line_to( upperBound, i ) self.ctx.move_to( i, 0 ) self.ctx.line_to( i, upperBound ) self.ctx.set_source_rgba( 0.2, 0.2, 0.2, 0.5 ) self.ctx.identity_matrix() self.ctx.stroke() self.ctx.restore() def __applyTranscale( self ): self.ctx.scale( self.__scale, self.__scale ) self.ctx.translate( -self.__translateX, -self.__translateY ) # pixelX == self.__scale * ( logicX - self.__translateX ) # self.__scale == pixelX / ( logicX - self.__translateX ) # logicX == pixelX / self.__scale + self.__translateX def transcalePoint( self, pixelX, pixelY ): logicX = pixelX / self.__scale + self.__translateX logicY = pixelY / self.__scale + self.__translateY return logicX, logicY def translate( self, dx, dy ): self.__translateX -= dx / self.__scale self.__translateY -= dy / self.__scale self.queue_draw() self.__transcaleSisterViews() def zoomIn( self, x, y ): self.__rescale( x, y, math.sqrt( 2.0 ) ) def zoomOut( self, x, y ): self.__rescale( x, y, math.sqrt( 0.5 ) ) def __rescale( self, x, y, scale ): oldScale = self.__scale oldTransX = self.__translateX oldTransY = self.__translateY # x == oldScale * ( logicX - oldTransX ) # x == newScale * ( logicX - newTransX ) # => newScale * ( logicX - newTransX ) == oldScale * ( logicX - oldTransX ) # => logicX - newTransX == oldScale * ( logicX - oldTransX ) / newScale # => newTransX == oldScale * ( oldTransX - logicX ) / newScale + logicX logicX = x / self.__scale + oldTransX logicY = y / self.__scale + oldTransY newScale = max( self.__pixelPerUnit, oldScale * scale ) newTransX = oldScale * ( oldTransX - logicX ) / newScale + logicX newTransY = oldScale * ( oldTransY - logicY ) / newScale + logicY self.__scale = newScale self.__translateX = newTransX self.__translateY = newTransY self.queue_draw() self.__transcaleSisterViews() def __transcaleSisterViews( self ): for view in self.__sisterViews: view.__translateX = self.__translateX view.__translateY = self.__translateY view.__scale = self.__scale view.queue_draw() def notifyView( self ): self.queue_draw() def resetMouseManager( self ): self.mouseManager.reset() self.queue_draw() def addSisterView( self, view ): self.__sisterViews.append( view )
class methods: def __init__(self, fps, clockObject, surface, font, bars, windowsize): self.fps = fps self.clock = clockObject self.surface = surface self.font = font self.bars = bars self.windowsize = windowsize def get_array(self, length, mode=0): arr = list(range(length)) if not mode: random.shuffle(arr) elif mode == 2: arr = arr[::-1] elif mode == 3: for i in range(length - 1): if random.randint(0, 10) < 8: tmp = random.randint(4, 15) try: arr[i], arr[i + tmp] = arr[i + tmp], arr[i] except: pass return arr def setup(self, length, mode=0): self.array = self.get_array(length, mode) self.display = Display(self.windowsize[0] / length, self.windowsize, self.surface, self.font) self.accesses = 0 self.comparisons = 0 setattr(self.display, "bars", self.bars) bubble = lambda self: Bubble(self.array, self.display, self.clock, self.fps ).main() quicksort = lambda self: Quicksort(self.array, self.display, self.clock, self.fps).main() selection = lambda self: Selection(self.array, self.display, self.clock, self.fps).main() cocktail = lambda self: Cocktail(self.array, self.display, self.clock, self .fps).main() bogo = lambda self: Bogo(self.array, self.display, self.clock, self.fps ).main() oddeven = lambda self: Oddeven(self.array, self.display, self.clock, self. fps).main() shell = lambda self: Shell(self.array, self.display, self.clock, self.fps ).main() comb = lambda self: Comb(self.array, self.display, self.clock, self.fps ).main() insertion = lambda self: Insertion(self.array, self.display, self.clock, self.fps).main() mergetd = lambda self: MergeTD(self.array, self.display, self.clock, self. fps).main() radixlsd = lambda self: RadixLSD(self.array, self.display, self.clock, self .fps).main() counting = lambda self: Counting(self.array, self.display, self.clock, self .fps).main() cycle = lambda self: Cycle(self.array, self.display, self.clock, self.fps ).main() heap = lambda self: Heap(self.array, self.display, self.clock, self.fps ).main() circle = lambda self: Circle(self.array, self.display, self.clock, self.fps ).main() gnome = lambda self: Gnome(self.array, self.display, self.clock, self.fps ).main() binaryinsertion = lambda self: BinaryInsertion( self.array, self.display, self.clock, self.fps).main() pancake = lambda self: Pancake(self.array, self.display, self.clock, self. fps).main() permutation = lambda self: Permutation(self.array, self.display, self. clock, self.fps).main() strand = lambda self: Strand(self.array, self.display, self.clock, self.fps ).main() bucket = lambda self: Bucket(self.array, self.display, self.clock, self.fps ).main() minmax = lambda self: MinMax(self.array, self.display, self.clock, self.fps ).main() mergebu = lambda self: MergeBU(self.array, self.display, self.clock, self. fps).main() bitonic = lambda self: Bitonic(self.array, self.display, self.clock, self. fps).main() stooge = lambda self: Stooge(self.array, self.display, self.clock, self.fps ).main() smooth = lambda self: Smooth(self.array, self.display, self.clock, self.fps ).main() quick3 = lambda self: Quick3(self.array, self.display, self.clock, self.fps ).main()
def __init__(self, generation, population, limit_population, crossover_rate, mutation_rate, cost_rate, prizes_rate, map_points, prizes, max_cost, start_point, end_point, depositos=[]): self.generationSize = generation self.populationSize = population self.limit_population = limit_population self.crossover_rate = crossover_rate self.mutation_rate = mutation_rate self.cost_rate = np.array(cost_rate) self.prizes_rate = prizes_rate self.map_points = np.loadtxt(map_points) self.prizes = np.loadtxt(prizes)[:, 1] self.max_cost = np.array(max_cost) self.start_point = start_point self.end_point = end_point self.depositos = depositos self.number_agents = len(max_cost) self.distance = self.calculate_distances() self.functionObject = FunctionObjective(self.map_points, self.prizes) self.FO = self.functionObject.FO self.mensureCost = self.functionObject.med_custo self.methodInsertRemoveChromosome = self.functionObject.coust_insert self.allElementsMap = np.arange(self.map_points.shape[0]) self.allElementsMap = self.allElementsMap[self.number_agents:] # removendo depositos deposits = [x for x in self.start_point] deposits += [x for x in self.end_point if x not in deposits] deposits = np.unique(np.array(deposits)) self.initialChromossome = np.arange(self.map_points.shape[0]) self.initialChromossome = np.delete(self.initialChromossome, self.depositos) self.allElementsMap = np.copy(self.initialChromossome) self.mutationObject = Mutation(self.mensureCost, self.max_cost, self.prizes) self.mutation = self.mutationObject.scramble self.crossoverObject = Crossover() self.crossover = self.crossoverObject.cross_TOPMD self.PopulationObject = Population(self.start_point, self.end_point, self.mensureCost, self.max_cost, self.distance) self.SelectionObject = Selection() self.selection = self.SelectionObject.tournament