def parse_method(file, lineno, line): line = fix_up_line(line) m = method_outline.match(line) if m == None: print "Bad method declaration from %s line %d:\n\"%s\"\n" %\ (file, lineno, line) sys.exit(1) method, args, rargs = m.groups() if method == "": quit(file, lineno, "Missing a method name") validate_name(file, lineno, "Method", method, "/_-") method_args = parse_args(file, lineno, args) return_args = parse_args(file, lineno, rargs); for i in method_args: for j in return_args: if i.name() == j.name(): quit(file, lineno, "\"%s\" appears as an input and output " \ "parameter name." % i.name()) return XrlMethod(method, method_args, return_args)
def setOutputList(cls,s): cls.__OUTPUT_LIST = s.split(' ') authorizedWords = [ ['m','Write the \'.m\' file (Matlab file)'], ['pdf','Write the \'.pdf\' file (Graphic visualization of the Graph)'], ['dot','Write the \'.dot\' file (Source code for the pdf file)'], ['convergence','Write convergence file at each generation'], ['pareto-history','Write Pareto history'], ['current','Write current best individual at each generation'], ['duration','Write the duration of each generation'], ['progress','Write the progress of the optimization'], ['tmp-progress','Write the progress of the optimization in tmp directory'], ['super-ind','Compute a super-individual at each generation'], ['info-generation','Display the generation number'], ['info-improvement','Display all improvements'], ['info-operator','Display the operators list'], ['info-pygenalg','Display the pygenalg parameters'], ['end-convergence','(End of optimization) Write the convergence file'], ['end-pareto','(End of optimization) Write the complete pareto front'], ['end-node-call','(End of optimization) Write the number H calculations'], ['end-sigma','(End of optimization) Write sigma-obj1 in a file'], ['all','All the above-mentionned outputs'] ] # Suppression of empty elements while "" in cls.__OUTPUT_LIST: cls.__OUTPUT_LIST.remove("") # Verification of validity of the keywords for w in cls.__OUTPUT_LIST: if not w in [x for (x,y) in authorizedWords]: print "***********************************************************************" print 'The word \"'+w+'\" is not authorized in outputList' print 'Authorized words:' lenMax = max([len(x) for (x,y) in authorizedWords]) for w in authorizedWords: s=w[0]+' ' while len(s)<lenMax+3: s+='.' s+=' '+w[1] print ' '+s print "***********************************************************************" util.quit(__file__) # If "all", they use all authorized words if 'all' in cls.__OUTPUT_LIST: cls.__OUTPUT_LIST = [x for (x,y) in authorizedWords] # If "pdf", then remove "dot". if 'pdf' in cls.__OUTPUT_LIST and 'dot' in cls.__OUTPUT_LIST: # The writing of the pdf will, anyway, write the dot file cls.__OUTPUT_LIST.remove('dot') # If "convergence", then remove "end-convergence". if 'convergence' in cls.__OUTPUT_LIST and 'end-convergence' in cls.__OUTPUT_LIST: cls.__OUTPUT_LIST.remove('end-convergence') if 'tmp-progress' in cls.__OUTPUT_LIST: os.system('mkdir -p '+cls.__TMP_DIR+' 2>/dev/null')
def parse_args(file, lineno, str): if str == "": return [] toks = string.split(str, "&") # arg format is <name>[<type>] # ^ ^ # list types now *require* a member type hint list<type>. xrl_args = [] for t in toks: lb = string.find(t, ":") if lb == -1: quit(file, lineno, "Missing \":\" in xrlatom \"%s\"" % t) name = t[:lb] type = t[lb + 1:] validate_name(file, lineno, "Atom", name, '_-') # Parse <type>\<<member_type>\> (\<\> are literal angle brackets). lab = string.find(type, "<") member_type = None if lab != -1: rab = string.find(type, ">") if rab == -1: quit(file, lineno, "Invalid type spec \"%s\"" % type) member_type = type[lab + 1:rab] type = type[:lab] if xrl_atom_type.has_key(type) == 0: quit( file, lineno, "Atom type \"%s\" not amongst those known %s" % (type, xrl_atom_type.keys())) xa = XrlArg(name, type) if type == 'list': # Deal with type of members embedded in the container. These # are now mandatory for XIF in this branch. if xrl_atom_type.has_key(member_type) == 0: quit( file, lineno, "Member atom type \"%s\" not amongst those known %s" % (member_type, xrl_atom_type.keys())) xa.set_member_type(member_type) xrl_args.append(xa) return xrl_args
def parse_args(file, lineno, str): if str == "": return [] toks = string.split(str, "&") # arg format is <name>[<type>] # ^ ^ # list types now *require* a member type hint list<type>. xrl_args = [] for t in toks: lb = string.find(t, ":") if lb == -1: quit(file, lineno, "Missing \":\" in xrlatom \"%s\"" % t) name = t[:lb] type = t[lb + 1:] validate_name(file, lineno, "Atom", name, '_-') # Parse <type>\<<member_type>\> (\<\> are literal angle brackets). lab = string.find(type, "<") member_type = None if lab != -1: rab = string.find(type, ">") if rab == -1: quit(file, lineno, "Invalid type spec \"%s\"" % type) member_type = type[lab + 1:rab] type = type[:lab] if xrl_atom_type.has_key(type) == 0: quit(file, lineno, "Atom type \"%s\" not amongst those known %s" % (type, xrl_atom_type.keys())) xa = XrlArg(name, type) if type == 'list': # Deal with type of members embedded in the container. These # are now mandatory for XIF in this branch. if xrl_atom_type.has_key(member_type) == 0: quit(file, lineno, "Member atom type \"%s\" not amongst those known %s" % (member_type, xrl_atom_type.keys())) xa.set_member_type(member_type) xrl_args.append(xa) return xrl_args
def getOriginalString(self,opName): originalString = [z for (x,y,z) in self.__listOriginalString if x==opName] if len(originalString): return originalString[0] else: util.quit('OpManager.py')
def loadOpFile(self, opFile): print "Loading the set of operators in file: "+opFile # Get the lines fid = open(opFile) lines = fid.readlines() fid.close() lines = util.cleanLines(lines) # Get the "# operators" field if opFile[-4:]==".ind": print "Extraction of the \"# operators\" field." lines = util.getField(lines,'operators') # Process mat = [] for line in lines: values = line.replace(' ','').split(';') if "" in values: values.remove("") mat.append(values) # Filling the list of the operators: for nOp in range(0,len(mat)): operatorName = mat[nOp].pop(0).strip() # Find if the operator is "on" or "off" bool_on = mat[nOp].count("on")>0 bool_off = mat[nOp].count("off")>0 # Check that the operator is not "on" AND "off" at the same time if bool_on and bool_off: print "The operator \""+operatorName+"\" is defined as \"on\" AND \"off\" !" print "Please check in file: "+opFile util.quit(__file__) # Remove "on" and "off" from list if bool_on: mat[nOp].remove("on") if bool_off: mat[nOp].remove("off") # If the arg is not "off", then it's "on" bool_on = bool_on or (not bool_off) # Search for another name for the operator if bool_on: # Look for quotes in the list quoteNumber = 0 opString = "" for elem in mat[nOp]: if "\"" in elem: quoteNumber += 1 opString = elem if quoteNumber > 1: print "The operator \""+operatorName+"\" has several interpretation strings !" print "There is several fields with \"quotes\"" print "Please check in file: "+opFile util.quit(__file__) elif quoteNumber == 1: mat[nOp].remove(opString) opString = opString.replace('\"','') opOriginalString = opString if opString.count("(")!=opString.count(")"): print "The operator \""+operatorName+"\" has improper number of parenthesis !" print "Please check in file: "+opFile util.quit(__file__) else: opOriginalString = "" opString = operatorName # Check that the remaining arguments are digits and convert them to integer for i in range(len(mat[nOp])): if mat[nOp][i].strip().isdigit(): # N is the order with which the operator is define mat[nOp][i] = int(mat[nOp][i]) else: print "The operator \""+operatorName+"\" is defined with unrecognised option \""+elem+"\"" print "Please check in file: "+opFile util.quit(__file__) # save original string and Narg of operators self.__listOriginalString.append([operatorName , mat[nOp], opOriginalString]) for N in mat[nOp]: # BUILD completeString if opString.count("(")==0: if self.useNoParenthesis(operatorName): completeString = "(" for i in range(N-1): completeString += "$x"+str(i)+"$"+opString completeString += "$x"+str(N-1)+"$)" else: completeString = opString+"($x*$)" else: # nb : if opString contains parenthesis, then # it is supposed to contain $x*$ or $xi$, so it don't need # any change. completeString = opString # Replace $x*$ if completeString.count("$x*$"): repx = "" for i in range(N-1): repx += "$x"+str(i)+"$," repx += "$x"+str(N-1)+"$" completeString = completeString.replace("$x*$",repx) # Check that arguments "$x1$", "$x2", ... are in the range listArg = re.findall("\$x[0-9]*\$",completeString) listIndexes = [] for arg in listArg: # get the index of the argument # $x13$ will give index 13. index = int(arg.replace('$','').replace('x','')) listIndexes.append(index) # check that this index is smaller to ther order if index>=N: print "The operator \""+operatorName+"\" is defined with" print " String : "+opString print " order N="+str(N) print "String must be defined with argument $xi$," print " where i is in [0..."+str(N-1)+"]" print "You can not use "+arg print "Nb : you can also use $x*$ to which will be replaced by :" print " $x0$,$x1$,$x2$,...,$x"+str(N-1)+"$" print "Please check in file: "+opFile util.quit(__file__) # check that this index is smaller to ther order if len(set(listIndexes))<N: print "The operator \""+operatorName+"\" is defined with" print " String : "+opString print " Order N="+str(N) print "Missing argument indexes : "+str([i for i in range(N) if i not in listIndexes]) print "Please check in file: "+opFile util.quit(__file__) # save operator along with narg self.__listOperators.append(operatorName) self.__listNbArg.append(N) self.__listString.append(completeString) self.__maxNbArg = max(self.__maxNbArg,N) self.printOperatorList()
def validate_name(file, line, type, value, extra): pattern = "[A-Za-z][A-z0-9%s]?" % extra if re.match(pattern, value) == None: errmsg = "%s name \"%s\" has chars other than %s" \ % (type, value, pattern) quit(file, line, errmsg)
while True: window.fill(pygame.Color(127,127,127)) window.blit(hangimages[guess],(150,0)) guesstext = font.render("".join(guessword), False, (0,0,0)) guessrect = guesstext.get_rect() guessrect.topleft = (300,400) window.blit(guesstext, guessrect) #print(guessword) #print(word) if not "_" in guessword: pygame.display.set_caption("YOU HAVE DONE IT!") guessword = ["G","O","O","D"," ","J","O","B"] time.sleep(15) for event in pygame.event.get(): if event.type == QUIT: util.quit() elif event.type == KEYDOWN: if 92 < event.key < 122: #Enter Letter key print(chr(event.key)) if chr(event.key) in word: for x in range(0,len(word)): if chr(event.key) == word[x]: guessword[x] = chr(event.key) else: guess = guess + 1 if guess == 6: util.quit() elif event.key == 27: util.quit() else: print("Not a letter key: " + str(event.key))
else: movekey = "" if movekey == K_LEFT: head.xdirection = -1 head.ydirection = 0 if movekey == K_RIGHT: head.xdirection = 1 head.ydirection = 0 if movekey == K_UP: head.xdirection = 0 head.ydirection = -1 if movekey == K_DOWN: head.xdirection = 0 head.ydirection = 1 if util.overlapping(head,snake): util.quit(bodysize) restart() #Will do nothing if REPEAT_ON_FAIL is set to false, as the program would've quit from the util.quit if util.overlapping(food,[head]): bodysize = bodysize + 1 food = game.Circle(random.randrange(render.BOXES),random.randrange(render.BOXES)) snake.append(game.Circle(head.x,head.y)) head.x = head.x + head.xdirection head.y = head.y + head.ydirection if len(snake) > bodysize: snake.pop(0) if not(0 <= head.x < render.BOXES): util.quit(bodysize)
def setVerboseLevel(cls,d): print "***********************************************************************" print "Function \"setVerboseLevel\" is not supported anymore." print "Use function setOuputList" print "***********************************************************************" util.quit(__file__)
def endOfGeneration(self, population, iGeneration): #=================# # CHECKS # #=================# # Find new best individual popBestIndividual = population.getBestIndividual() newBestObj1 = float('inf') newBestObj2 = float('inf') for indiv in popBestIndividual: obj1 = indiv.getObj()[0] obj2 = indiv.getObj()[1] #print "bestPop : "+str(obj1)+" "+str(obj2) if (obj1<=newBestObj1) or (obj1==newBestObj1 and obj2<newBestObj2): newBestInd = indiv newBestObj1 = obj1 newBestObj2 = obj2 # Get old best individual objectives if self.__BEST is None: oldBestObj1 = float('inf') oldBestObj2 = float('inf') else: oldBestObj1 = self.__BEST.getObj()[0] oldBestObj2 = self.__BEST.getObj()[1] # Check Regression if oldBestObj1<newBestObj1*(1-util.MACHINE_EPS): print "\n" print "Error : regression of the objectives !" print "old : "+str(oldBestObj1)+" vs new : "+str(newBestObj1) util.quit(__file__) #=================# # INFOS # #=================# # Calcul Sigma Obj1 self.__SIGMA_OBJ1 += newBestObj1 * iGeneration # Total number of generations nbGenMax = self.getParam(self.NB_GENERATIONS_LABEL) #=================# # OUTPUTS # #=================# # Check Improvement if (iGeneration==1) or (iGeneration==nbGenMax) or (oldBestObj1>newBestObj1) or (oldBestObj1==newBestObj1 and oldBestObj2>newBestObj2): # Memorization of the new best individual self.__BEST = newBestInd # Check the consistancy of the best Individual newBestInd.checkConsistency('GenAlgBehavior:endOfGeneration, newBestInd') # Update the maximum number of nodes in a graph Individual.setNbNodesLimit(3*newBestInd.getNbNodes()) # Save best individual (duplicate and improve it before saving) if 'current' in self.__OUTPUT_LIST: g = newBestInd.getGraph().duplicate() g.mutationKeepBest() g.mutationShortenGraph() newBestIndCopy = Individual.generateFromGraph(g) name = self.__RESULT_DIR+'/model_current' # Write the .ind file newBestIndCopy.writeIndFile(name) if 'dot' in self.__OUTPUT_LIST: newBestIndCopy.writeDotFile(name) if 'pdf' in self.__OUTPUT_LIST: newBestIndCopy.writePdfFile(name) if 'm' in self.__OUTPUT_LIST: newBestIndCopy.writeMatlabFile(name) if 'info-improvement' in self.__OUTPUT_LIST: # Print last improvment print "Obj1: "+str(newBestObj1)+" Obj2: "+str(newBestObj2) if 'convergence' in self.__OUTPUT_LIST: # Write obj1 in statistic file fid = open(self.__RESULT_DIR+'/convergence.txt', 'a') fid.write( str(iGeneration)+" "+str(newBestObj1)+" "+str(newBestObj2)+"\n" ) fid.close() if 'end-convergence' in self.__OUTPUT_LIST: self.__CONVERGENCE.append([iGeneration, newBestObj1, newBestObj2]) # Write Pareto history if 'pareto-history' in self.__OUTPUT_LIST: # For Q = 2, pareto front is written if # iGen is in [1 3 10 31 100 316 1000 3162 10000 31622 etc...] NR = numpy.power(10,numpy.floor(numpy.log10(iGeneration))) Q = 5 tab = numpy.round(NR*pow(10,numpy.array(range(Q))/float(Q))) if (iGeneration in tab) or (iGeneration==nbGenMax): self.writeParetoObj(iGeneration,population) # Build super linear graph if 'super-ind' in self.__OUTPUT_LIST: graphList = [] for indiv in popBestIndividual: g = indiv.getGraph() logHMax = g.getLogHMax() if not ( g.isConstant() or numpy.isinf(logHMax) or numpy.isnan(logHMax) ): graphList.append(g) if len(graphList)>2: gn=Graph.linearCrossover(graphList) if gn is not None: superIndiv = Individual.generateFromGraph(gn) superIndivError = superIndiv.getError() if superIndivError < self.__SUPER_INDIV_ERROR and superIndivError < newBestObj1 : print " Obj1: "+str(superIndiv.getError())+" Obj2: "+str(superIndiv.getComplexity())+" (SuperInd)" superIndiv.checkConsistency('GenAlgBehavior:endOfGeneration, superIndiv') name = self.__RESULT_DIR+'/model_sup' superIndiv.writeIndFile(name) if 'dot' in self.__OUTPUT_LIST: superIndiv.writeDotFile(name) if 'pdf' in self.__OUTPUT_LIST: superIndiv.writePdfFile(name) if 'm' in self.__OUTPUT_LIST: superIndiv.writeMatlabFile(name) self.__SUPER_INDIV_ERROR = superIndivError if 'duration' in self.__OUTPUT_LIST: generationDuration = time.time() - self.__GENERATION_STARTING_TIME fid = open(self.__RESULT_DIR+'/duration.txt', 'a') fid.write(str(iGeneration)+" "+str(generationDuration)+"\n" ) fid.close() if 'progress' in self.__OUTPUT_LIST: fid = open(self.__RESULT_DIR+'/progress.txt', 'w') fid.write(str(iGeneration)+"/"+str(self.getParam(self.NB_GENERATIONS_LABEL))+" "+str(newBestObj1)+" "+str(newBestObj2)) fid.close() if 'tmp-progress' in self.__OUTPUT_LIST: if self.__LAST_PRINT_TIME is None or (time.time()-self.__LAST_PRINT_TIME>10): self.__LAST_PRINT_TIME = time.time() fid = open(self.__TMP_DIR+'/progress.txt', 'w') fid.write(str(iGeneration)+"/"+str(self.getParam(self.NB_GENERATIONS_LABEL))+" "+str(newBestObj1)+" "+str(newBestObj2)) fid.close()