def SFENG(Nodes, mlinks, seed): Net = [[0 for col in range(Nodes)] for row in range(Nodes)] pos = len(seed) for i in range(pos): for j in range(pos): Net[i][j] = seed[i][j] sumlinks = 0 for i in range(pos): sumlinks = sumlinks + sum(Net[i]) while pos < Nodes: linkage = 0 tmp = random() if tmp < 0.8:#override mlinks. mlinks = 1 elif tmp < 0.95: mlinks = 2 else: mlinks = 3 while linkage <> mlinks: rnode = int(random()*pos) deg = sum(Net[rnode]) * 2 rlink = random() if rlink < float(deg) / sumlinks and Net[pos][rnode] <> 1 and Net[rnode][pos] <> 1: Net[pos][rnode] = 1 Net[rnode][pos] = 1 linkage = linkage + 1 sumlinks = sumlinks + 2 pos = pos + 1 return Net
def setup_test05(self): print "... benchmarking 8-PSK demapper" self.nobits = 4 self.data_subcarriers = 200 self.blks = self.N*(10 + 1) self.tb = gr.top_block() #self.bitmap = [self.nobits]*self.data_subcarriers self.demodulator = generic_demapper_vcb(self.data_subcarriers,10) const = self.demodulator.get_constellation( self.nobits ) assert( len( const ) == 2**self.nobits ) self.bitdata = [random()+1j*random() for i in range(self.blks*self.data_subcarriers)] self.src = blocks.vector_source_c(self.bitdata,False, self.data_subcarriers) #self.src = symbol_random_src( const, self.data_subcarriers ) self.bitmap = [0]*self.data_subcarriers + [self.nobits]*self.data_subcarriers self.bitmap_src = blocks.vector_source_b(self.bitmap,True, self.data_subcarriers) #self.bmaptrig_stream = [1, 2]+[0]*(11-2) #self.bitmap_trigger = blocks.vector_source_b(self.bmaptrig_stream, True) self.snk = blocks.null_sink(gr.sizeof_char) self.tb.connect(self.src,self.demodulator,self.snk) self.tb.connect(self.bitmap_src,(self.demodulator,1))
def plot_paths_2d(self, start_sys, end_sys, input_ring, c_skew = .001, endpoints = True, saved_start = None, rand_colors = False): """ This returns a graphics object of solution paths in the complex plane. INPUT: - start_sys -- a square polynomial system, given as a list of polynomials - end_sys -- same type as start_sys - input_ring -- for coercion of the variables into the desired ring. - c_skew -- optional. the imaginary part of homotopy multiplier; nonzero values are often necessary to avoid intermediate path collisions - endpoints -- optional. Whether to draw in the ends of paths as points. - saved_start -- optional. A phc output file. If not given, start system solutions are computed via the phc.blackbox function. OUTPUT: - lines and points of solution paths EXAMPLES:: sage: from sage.interfaces.phc import * sage: from sage.structure.sage_object import SageObject sage: R2.<x,y> = PolynomialRing(QQ,2) sage: start_sys = [x^5-y^2,y^5-1] sage: sol = phc.blackbox(start_sys, R2) # optional -- phc sage: start_save = sol.save_as_start() # optional -- phc sage: end_sys = [x^5-25,y^5-x^2] # optional -- phc sage: testing = phc.plot_paths_2d(start_sys, end_sys, R2) # optional -- phc sage: type(testing) # optional -- phc (normally use plot here) <class 'sage.plot.graphics.Graphics'> """ paths = phc.path_track(start_sys, end_sys, input_ring, c_skew = c_skew, saved_start = saved_start) path_lines = [] sol_pts = [] if rand_colors: r_color = {} for a_var in input_ring.gens(): var_name = str(a_var) r_color[var_name] = (random(),random(),random()) for a_sol in paths: for a_var in input_ring.gens(): var_name = str(a_var) temp_line = [] for data in a_sol: temp_line.append([data[var_name].real(), data[var_name].imag()]) if rand_colors: path_lines.append(line(temp_line, rgbcolor = r_color[var_name])) else: path_lines.append(line(temp_line)) if endpoints: sol_pts = [] for a_sol in paths: for a_var in input_ring.gens(): var_name = str(a_var) sol_pts.append(point([a_sol[0][var_name].real(), a_sol[0][var_name].imag()])) sol_pts.append(point([a_sol[-1][var_name].real(), a_sol[-1][var_name].imag()])) return sum(sol_pts) + sum(path_lines) else: return sum(path_lines)
def __init__(self, **kwds): base = uniform(50,70) altura = uniform(40,90) x= uniform(20,80) super(Enemy, self).__init__([(0, 0), (base, 0), (x, altura)], color='black', **kwds) self.tipo='enemy' x_pos = uniform(-600,600) y_pos = uniform(-400,400) while 400>x_pos>-400 and 300>y_pos>-300: x_pos = uniform(-600,600) y_pos = uniform(-400,400) type = random() #if type < 0.5 : # self = Poly.regular(N=4, length = 50, color = 'black', world = self) #elif type < 0.8: # self = Poly.regular(N=4, length = 50, color = 'black', world = self) #else: # self = Poly.regular(N=3, length = 60, color = 'black', world = self) self.pos_cm = VectorM(x_pos, y_pos) #Vetor do inimigo ao player self.vel_cm = VectorM(random() * 200, random() * 200) self.receiving_input = False
def phiPsi(structType,index,userDef): if structType == 'extended' or structType == 'alpha': #print angles[structType] return angles[structType] elif structType == 'uniform': x = random() y = random() x = x*360. if x > 180: x = x - 360. y = y*360. if y > 180: y = y - 360. return x,y elif structType == 'gaussian': x = -1 while x < 0 or x > 360: x = gauss(180,12) if x > 180: x = x - 360 y = -1 while y < 0 or y > 360: y = gauss(180,12) if y > 180: y = y - 360 return x,y elif structType == 'user_defined': x,y = userDef[index] return x,y
def step0(self): if self.step != 0: raise Exception, "Wrong step" self.step = self.step + 1 random = self.domain_space.random_element x = [] x.append(random()) x.append(random()) x.append(self.solution - x[0] - x[1]) self.x = x random = self.range_space.random_element c = [] c.append(random()) c.append(random()) c.append(-c[0] - c[1]) self.c = tuple(c) self.r = [] for i in range(3): self.r.append(c[i] + self.instance.partial_map(x[i], x[i-1])) result = [] result.append(hash_sage_object(self.c)) for i in range(3): result.append(hash_sage_object(self.x[i])) result.append(hash_sage_object(self.r[i])) return result
def create_new(self): # if pool is not full create a random brain if len(self.list) < self.maxMembers: #Create a brain brain=BackPropBrain(self.layerSizes) brain.proof_count=0 return brain # keep testing the best brain in case it was a fluke!!! # this removes the best net from the pool # it will get back in if it scores OK if random() < REPROVE_PROB: brain=self.list[0].brain del self.list[0] brain.proof_count += 1 return brain # Otherwise just select a random brain from the pool clone=self.select2() # if this returned None create a new random brain if clone==None: brain=BackPropBrain(self.layerSizes) brain.proof_count=0 return brain # mutate the cloned brain by a random amount. clone.mutate(random()) clone.proof_count=0 return clone
def get_random_cross_link_dataset(representation, resolution=1.0, number_of_cross_links=10, ambiguity_probability=0.1, confidence_score_range=[0,100], avoid_same_particles=False): '''Return a random cross-link dataset as a string. Every line is a residue pair, together with UniqueIdentifier and XL score.''' residue_pairs=get_random_residue_pairs(representation, resolution, number_of_cross_links, avoid_same_particles) from random import random unique_identifier=0 cmin=float(min(confidence_score_range)) cmax=float(max(confidence_score_range)) dataset="#\n" for (name1, r1, name2, r2) in residue_pairs: if random() > ambiguity_probability: unique_identifier+=1 score=random()*(cmax-cmin)+cmin dataset+=str(name1)+" "+str(name2)+" "+str(r1)+" "+str(r2)+" "+str(score)+" "+str(unique_identifier)+"\n" return dataset
def perturbMatch(matches, numVars, numWords, subs): # match: [[[1,2], [4,6]], [0, 1]] #S = [randint(0, numWords) for i in range(numVars*2)] #S.sort() #matches[0] = [[S[2*i],S[2*i+1]] for i in range(numVars)] # extract current sorted index list S = [] for item in matches[0]: S.append(item[0]) S.append(item[1]) # now perturn index list for i in range(len(S)): if random() > 0.5: S[i] = min(max(S[i] + randint(-1, 1), 0), numWords) #print " S:", S S.sort() #print "Ss:", S # reassign S matches[0] = [[S[2*i],S[2*i+1]] for i in range(numVars)] for i in range(len(matches[1])): if random() > 0.75: matches[1][i] = randint(0, len(subs[i])-1) return matches
def __init__(self, pos): self.position = pos self.frame = 1 self.time = 0 self.type = choice(["Weaponry","Shields","Thrust","Bomb"]) self.rotate = 0 self.speed = [(random()-0.5)*0.5,(random()-0.5)*0.5]
def drawname(person,NN): newrX = [] newrY = [] stepSizex = [] stepSizey =[] studentName = [] global rX global rY global w for i in range(0,NN): newrX.append(1000*random()+20) newrY.append(350*random()+ 250) ## 250 leaves a gap at the top studentName.append(w.create_text(rX[i],rY[i],text=person[i],font=fontz)) stepSizex.append((newrX[i]-rX[i])/400) stepSizey.append((newrY[i]-rY[i])/400) for step in range(1,400): skip = 0 for i in range(0,NN): skip = skip + 1 if (skip%2) == 0: jitter = 1/1000 else: jitter = -1/1000 rX[i] = stepSizex[i] + rX[i] rY[i] = stepSizey[i] + rY[i] w.pack() w.coords(studentName[i],rX[i],rY[i]) root.update_idletasks() root.update()
def lastTickEventsAnalyze(self): self.dangerEvents = [e for e in self.dangerEvents if (self.game.match.timePassed-e.time)<self.eventInvalidationTime] for event in self.lastTickEvents: if event.type==MatchCombatEvent.TYPE_RESPAWN: bot = event.subject if bot in self.game.enemyTeam.members: bot.position = self.level.findRandomFreePositionInBox(self.game.enemyTeam.botSpawnArea) bot.seenLast = 0 bot.health = 100 bot.facingDirection = Vector2((random()-0.5),random()-0.5) if self.enemyBotsAlive!=self.countBot: self.updateDangerAtRespawn() self.enemyBotsAlive=self.countBot #print "Alive enemies: %d"%self.enemyBotsAlive elif event.type==MatchCombatEvent.TYPE_KILLED: if event.subject.team.name!=self.game.team.name: self.enemyBotsAlive-=1 #print "Alive enemies: %d"%self.enemyBotsAlive else: self.dangerEvents.append(event) #pos = e.instigator.position if e.instigator!=None else e.subject.position pos = event.subject.position self.levelAnalysis.updateDangerStatic(pos, 4, 196) self.botInit(event.subject) elif event.type == MatchCombatEvent.TYPE_FLAG_PICKEDUP and event.subject.team.name==self.game.team.name: self.dangerEvents.append(event)
def __init__(self,pos,type,velocity,gamecontainer): pygame.sprite.Sprite.__init__(self) self.screen_size=Constants.SCREEN.get_size() self.gamecontainer = gamecontainer self.type = type if self.type == "blue": if len(Atom.images_blue) == 0: for i in os.listdir("sprites/atom_blue"): Atom.images_blue.append(pygame.image.load("sprites/atom_blue/" + i)) Atom.images_blue[-1] = Atom.images_blue[-1].convert_alpha() #for blitting more faster if self.type == "green": if len(Atom.images_green) == 0: Atom.images_green.append(pygame.image.load("sprites/atom_green/atom_1.png")) Atom.images_green[-1] = Atom.images_green[-1].convert_alpha() if self.type == "red": if len(Atom.images_red) == 0: Atom.images_red.append(pygame.image.load("sprites/atom_red/atom_1.png")) Atom.images_red[-1] = Atom.images_red[-1].convert_alpha() self.image = eval("Atom.images_" + self.type + "[0]") self.original=self.image.copy() self.rect = self.image.get_rect() self.x = pos[0] self.y = pos[1] self.rect.center = (self.screen_size[0]*self.x,self.screen_size[1]*self.y) self.dirty=0 self.angle = radians(360.0)*random() self.randomphase = [35.0*random(),35.0*random()] self.time_speed =pygame.time.Clock() self.dt =0.0 self.time =0.0 self.time1 =0.0 self.angle = 0.0 self.acum = [0.0,0.0] #Since screen space is integer self.noise = Perlin.SimplexNoise(); self.mass = 0.25 self.state="normal" self.target_time=0.0 self.childCount=0 self.combo=0 self.scorecombo = 0 self.fade_score = False self.velocityfactor = velocity self.frame = 0 self.increasesize = True self.animtime = 0.0
def Run(self): seed() maxVal = 0.3 print "start" self.sss.move("sdh","home",False) self.sss.move("torso","home",False) handle01 = self.sss.move("arm","folded",False) self.sss.move("tray","up") handle01.wait() for i in range(1,3): r1 = (random()-0.5)*2*maxVal; r2 = (random()-0.5)*2*maxVal; self.sss.move("torso",[[0.5*r1,0.5*r2,r1,r2]]) self.sss.move("arm","pregrasp") self.sss.move_cart_rel("arm",[[0.0, 0.0, -0.1], [0.0, 0.0, 0.0]]) self.sss.move_cart_rel("arm",[[0.0, 0.1, 0.0], [0.0, 0.0, 0.0]]) self.sss.move("sdh","cylopen") self.sss.move("sdh","cylclosed") self.sss.move("tray","down") self.sss.move("tray","up") self.sss.move("arm","folded") self.sss.sleep(1) self.sss.move("sdh","home",False) self.sss.move("torso","home",False) self.sss.move("arm","folded",False) self.sss.move("tray","up")
def __init__(self, parent, plot, roiList=[], sectionNumber=1, *args, **kwargs): ''' Constructor Create a label, a text control, and a remove button. textLabel - An ascii string that will be used as a label for the text control width - The width in pixels of the text control, it defaults to 200 height - The height in pixels of the text control, it defaults to 20 sectionNumber - The number of the text control, which is added to the label sectionList - A list of text controls that the new text control is appended to ''' wx.Panel.__init__(self, parent=parent, style=wx.BORDER_RAISED, id=wx.ID_ANY ,*args, **kwargs) self._parentPanel = parent self._sectionNumber = sectionNumber self._roi_type = self._parentPanel.GetRoiType() self.plot = plot self.red = random() self.blue = random() self.green = random() self.color = wx.Colour((self.red * 255), (self.green * 255), (self.blue * 255)) self.labelColor = wx.Colour(255,255,255) if self._roi_type == constants.LINE: self.color = wx.Colour((self.red * 255), (self.green * 255), (self.blue * 255)) self.roi = LineROI(self.plot[0], self.plot[1], self.plot[2], self.red, self.green, self.blue) else: self.color = wx.Colour((self.red * 255), (self.green * 255), 0) self.roi = RectROI(self.plot[0], self.plot[1], self.plot[2], self.red, self.green, 0) roiList.append(self.roi) return
def __process_menu_items(self, elapsedTime): ''' Process menu's flying item moving @param elapsedTime: elapsed time @return: ''' # Add items while len(self.menu_items) < 20: # Set random color r = randint(0, 2) clr = COLOR_RED if r == 1: clr = COLOR_BLUE if r == 2: clr = COLOR_GREEN # Set random location rx = (random() * 2.0 - 1.0) * 25.0 ry = (random() * 2.0 - 1.0) * 25.0 rz = 100.0 * (1 + random()) self.menu_items.add(Item(array([rx, ry, rz], 'f'), clr, 1)) # Delete items which locate behind the screen td = [] for i in self.menu_items: i.getPosition()[2] -= elapsedTime * 100.0 if i.getPosition()[2] < 0: td.append(i) for i in td: self.menu_items.remove(i)
def update(self, dt): if (self.x-self.r < 0 and self.vx < 0) or \ (self.x+self.r > window.width and self.vx > 0): self.vx *= -1.0 if (self.y-self.r < 0 and self.vy < 0) or \ (self.y+self.r > window.height and self.vy > 0): self.vy *= -1.0 self.x += self.vx * dt self.y += self.vy * dt if not self.excited: for sidex in [-1,1]: sidev = self.vx*sidex l = observedlambda(laser_lambda, sidev) p = abs_p_max*prob(l, l_abs, sigma) if random()<=p: self.excited = True self.exc_t = datetime.now() self.vx -= sidex*h/(l*m)*v_param for sidey in [-1,1]: sidev = self.vy*sidey l = observedlambda(laser_lambda, sidev) p = abs_p_max*prob(l, l_abs, sigma) if random()<=p: self.excited = True self.vy -= sidey*h/(l*m)*v_param else: if random()<=emission_p: self.excited = False a = random()*2.0*pi v = v_param*h/(l_abs*m) self.vx += v*cos(a) self.vy += v*sin(a)
def RandomUniformPoints(n, s): points = [] for i in range(n): x = random() y = random() points.append(Point(s + i, "", Vector((x, y)))) return points
def tree(frm, p, a, r, c, ml, mr, e, d): # Endpoint q q = p + a # Animate at a slow rate to see the tree get built rate(600) # Create the 'branch', starting at 'p' and with the direction vector 'a' cylinder(frame=frm, pos=p, axis=a, radius=r, color=c) # Place a spere at the end of each branch, as a joint for the next set of branches sphere(frame=frm, pos=q, radius=r, color=c) # Stop recursion at d == 0, also stop recursion for some of the smaller twigs if (d > 0) and ( (d > 1) or (random() > 0.33) ): # Get rotation axis by cross product of direction vector 'a' a1 = cross(a, (0,0,1) ) # New direction vector: first calc new length, the rotate it around # perpendicular axis 'a1' s = ml * a * ( 0.8 + 0.4 * random() ) s = rotate(s,axis=a1,angle=e) # Number of branches in this step n = 4 if random() > 0.3 else 3 # Smaller twigs only get 2 branches if (d < 3): n = 2 for i in range(n): # Distribute the branches a full rotation around the axis 'a' v = rotate( rotate(s, axis=a, angle=2.0*pi/n*i+pi/5.0/d*random()), axis=a, angle=pi/4.0*(random()-0.5)) # Recurse tree(frm, q, v, mr*r, c, ml, mr, e, d-1) else: return
def get_random_move(board): ''' Routine Description: This routine returns a random move. Arguments: board - Supplies the current board. Return Value: A row, col tuple for the coordinates of the random move. ''' board_dimension = len(board) while True: row = int(random() * board_dimension); col = int(random() * board_dimension); if board[row][col] == EMPTY_CHAR: break; return row, col
def gera_num_cc(abreviatura): j = 0 i = 0 comprimento_tuplo = len(iin) # Tal como e dito no enunciado, e necessario utilizar a funcao random que esta #localizada na biblioteca random do python para gerar um numero aleatorio #(nos intervalos entre 0 e 1), como nao era possivel utilizar o randint nem #o choice, a alternativa foi utilizar a funcao random para gerar um numero #aleatorio e multiplicar esse mesmo numero aleatorio pelo tamanho do tuplo (comprimento_aleatorio) #e tambem no caso dos prefixos (numeros_aleatorios), que consequentemente vai #gerar uma das posicoes possiveis (0,1 ou 2) ate chegar ao fim do comprimento do tuplo while j < comprimento_tuplo: if iin[j][1] == abreviatura: comprimento_aleatorio = iin[j][3][int(random() * len(iin[j][3]))] numeros_aleatorios = iin[j][2][int(random() * len(iin[j][2]))] j = j+1 numero_gerado = str(numeros_aleatorios) comprimento_numero_gerado = len(numero_gerado) limite = int(comprimento_aleatorio)-int(comprimento_numero_gerado)-1 while i < limite: numero_gerado = numero_gerado + str(int(random()*10)) i = i + 1 dig_verificacao = digito_verificacao(numero_gerado) numero_gerado = int(numero_gerado + dig_verificacao) return numero_gerado
def __init__(self, position, myTex, speed): self.pos = position.copy() self.length = random()+0.5 self.fireTexSide = 1.0 self.myTexture = myTex self.speed = randomizeVector(speed, 0.4) * (random() / 10 + 0.15) self.exist = True
def random_function_with_no_argument_maker(function_settings): def choice_value(values, r): i = 0 while r > values[i]['probability']: i += 1 return values[i]['value'] if function_settings['type'] == 'random function': if function_settings['subtype'] == 'gaussian': mean = function_settings['mean'] variance = function_settings['variance'] return lambda: gauss(mean, variance) elif function_settings['subtype'] == 'uniform distribution': interval = function_settings['interval'] return lambda: uniform(*interval) elif function_settings['subtype'] == 'discrete distribution': values = copy.deepcopy(function_settings['values']) total = 0 for pair in values: total += pair['probability'] pair['probability'] = total return lambda: choice_value(values, random()) elif function_settings['subtype'] == 'chi-squared distribution': k = function_settings['k'] coefficient = function_settings['coefficient'] return lambda: coefficient * math.fsum(gauss(0, 1)**2 for i in range(k)) return lambda: random()
def __init__(self,nome,pai,frm, cor, ml, mr, e): """ nome: string identificadora do ramo pai: ramo pai (string pai.nome) frm: frame do objeto cor: cor do ramo ml: fração do comprimento do ramo pai (+ruido) mr: e: """ self.pai = pai #ramo pai self.arvore = None self.nome = nome a1,a2 = cross(pai.eixo,(0,0,1)), cross(pai.eixo,(1,0,0)) self.v = ml*pai.eixo*(0.8+0.4*random()) s = rotate(self.v,axis=a1,angle=e) self.pai.ramos[self.nome]=self n = len(pai.ramos) self.ramos = {} self.pos = pai.fim self.frm = frm #print n, (2.0*pi/n)*(n-1)+pi/6.0*random() self.eixo = rotate(rotate(s,axis=pai.eixo,angle=2.0*pi*random()), axis=pai.eixo,angle=pi/4.0*(random()-0.5)) self.cor = cor self.isTronco = False self.fim = self.pos+self.eixo self.folhas = [] self.shape = cylinder(frame=self.frm, pos=self.pai.fim, axis=self.eixo, radius=self.raio, color=self.cor, material=materials.wood) sphere(frame=self.frm, pos=self.fim, radius=self.raio, color=cor, material=materials.wood)
def attack(self): IGNORE = open("/dev/null" , "w") sts = [] length = len(self.ports) at_port = 10 * (random()) % length for i in range(length): try: st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) st.connect((self.server, int(self.ports[i]))) sts.append(st) except: continue while(True): data = hashlib.md5(100 * str(random())).digest() sts[int(10 * random() % length)].sendall(data) #buf = sts[int(10 * random() % length)].recv(1024) #print >>IGNORE, (buf,) IGNORE.close() for st in sts: st.close()
def __init__(self): self.is_bouncy = 0 self.x = center self.v = 0 self.a = 0 self.t = 0 self.tv = 0 self.r = 10 self.thrusting = 0 self.retroing = 0 self.lefting = 0 self.righting = 0 self.hidden = 0 self.m = ship_mass self.ci = Polygon(canvas, 0, 0, 0, 0, 0, 0, fill='#005500', outline='white') tk.bind("<Return>", self.thrust) tk.bind("<KeyRelease-Return>", self.unthrust) tk.bind("<slash>", self.retro) tk.bind("<KeyRelease-slash>", self.unretro) tk.bind("z", self.left) tk.bind("<KeyRelease-z>", self.unleft) tk.bind("x", self.right) tk.bind("<KeyRelease-x>", self.unright) tk.bind("q", self.bang) tk.bind("<space>", self.hide) tk.bind("p", pause) tk.bind("+", next_level) tk.bind("=", new_level) tk.bind("-", prev_level) self.gender = int(random()*2)*2 - 1 self.sg = int(random()*2)*2 - 1
def boardchoice(gamemode, grid, SEA): while True: p1boardchoice = input(p1name + ", would you like your board to be\ random(R) or custom(C)? [R/C]\n~~> ").upper() if p1boardchoice not in ("R", "C"): print("\nInvalid choice, please choose again.\n") else: break p1board = GenBoard while True: if p1boardchoice == "R": board = p1board.gen_random_board(grid, SEA) elif p1boardchoice == "C": board = p1board.gen_custom_board(grid, SEA) displayboard(board) #This bit is hurting my head... idk if a class should be used or not... #I suspect that a class is now unnecessary and I should remove it but I #cannot think of an elegant way of dealing with player 1 and 2. #As it stands, a horrible mess of IF, ELIF and ELSE statements are needed #and this is the main cause of my headache... tl;dr MAKE THIS WORK NICER!!! if gamemode == 2: while True: p2boardchoice = input(p1name + ", would you like your board to be\ random(R) or custom(C)? [R/C]\n~~> ").upper() if p2boardchoice not in ("R", "C"): print("\nInvalid choice, please choose again.\n") else: break
def selectAction(self, sensors): """ Considers a number of candidate actions and chooses the one in which the maximal progress is expected (most of the time). With some small probability will also take random actions. """ # Generate a set of candidate actions candidateActions = [[random() for v in range(self.motorVectorSize)] for n in range(self.numCandidates)] progress = [] candidateRegions = [] # For each sensorimotor vector, find the associated region # and determine learning progress candidateRegions = [self.memory.closestRegion(sensors+motors) for motors in candidateActions] progress = [region.learningProgress() for region in candidateRegions] # Choose the action from region with maximal progress # most of the time if random() < self.probOfRandAction: choice = randrange(self.numCandidates) else: choice = indexOfMax(progress) self.sensorimotor = sensors + candidateActions[choice] self.winningRegion = candidateRegions[choice] # Determine the expert's prediction of the next sensors self.prediction = region.askExpert(self.sensorimotor) return candidateActions[choice]
def GetTaskArgs(taskNum, currIndex, maxValue = 5000, minValue = 1, nRows = 0, nCols = 0): argType = JQRTask[taskNum][currIndex].split(':')[0] numArgs = int(JQRTask[taskNum][currIndex].split(':')[1]) _args = [] while (len(_args) < numArgs): if (argType == "INT"): if( taskNum == 7): value = random.randrange(nRows) _args.append(value) value = random.randrange(nCols) _args.append(value) return _args value = random.randrange(maxValue - minValue) + minValue _args.append(value) elif (argType == "FLOAT"): _args.append(random.uniform(maxValue - minValue) + minValue) elif (argType == "STR"): chars = string.ascii_uppercase + string.digits genString = '' numChars = int(JQRTask[taskNum][currIndex].split(':')[2]) for character in numChars: genString.join(random(chars)) _args.append(''.join(random(chars))) elif (argType == "CHAR"): _args.append(string.ascii_uppercase + string.digits) return _args
def foxGrowth(): """ foxGrowth is called once at the end of each time step. It makes use of the global variables: CURRENTFOXPOP and CURRENTRABBITPOP, and both may be modified by this procedure. Each fox, based on the probabilities in the problem statement, may eat one rabbit (but only if there are more than 10 rabbits). If it eats a rabbit, then with a 1/3 prob it gives birth to a new fox. If it does not eat a rabbit, then with a 1/10 prob it dies. Nothing is returned. """ global CURRENTRABBITPOP global CURRENTFOXPOP for _ in range(CURRENTFOXPOP): eat_prob = CURRENTRABBITPOP/float(MAXRABBITPOP) if eat_prob > random(): if CURRENTRABBITPOP > 10: CURRENTRABBITPOP -= 1 if 1/3.0 > random(): CURRENTFOXPOP += 1 else: if 0.1 > random(): CURRENTFOXPOP -= 1
def orderSentence(sentence, dhLogits, printThings): root = None logits = [None] * len(sentence) logProbabilityGradient = 0 if args.model == "REAL_REAL": # Collect tokens to be removed (i.e., punctuation) eliminated = [] for line in sentence: line["coarse_dep"] = makeCoarse(line["dep"]) if line["dep"] == "root": root = line["index"] continue # Exclude Punctuation if line["dep"].startswith("punct"): if args.model == "REAL_REAL": eliminated.append(line) continue # Determine ordering relative to head key = (sentence[line["head"] - 1]["posUni"], line["dep"], line["posUni"]) line["dependency_key"] = key dhLogit = dhWeights[stoi_deps[key]] if True or args.model == "REAL": dhSampled = (line["head"] > line["index"]) else: dhSampled = (dhLogit > 0) direction = "DH" if dhSampled else "HD" if printThings: print("\t".join( map(str, [ "ORD", line["word"], line["posUni"], line["index"], ("->".join(list(key)) + " ")[:22], line["head"], dhLogit, dhSampled, direction ]))) headIndex = line["head"] - 1 sentence[headIndex]["children_" + direction] = ( sentence[headIndex].get("children_" + direction, []) + [line["index"]]) nounPhrases = [] for line in sentence: if line["posUni"] == "NOUN": childrenLeft = [ sentence[i - 1] for i in line.get("children_DH", []) ] childrenRight = [ sentence[i - 1] for i in line.get("children_HD", []) ] leftDependencies = [x["dep"] for x in childrenLeft] if len(leftDependencies) == 0: continue if set(leftDependencies).issubset( set(["case", "det", "nummod", "amod"])): leftLengths = [ len(x.get("children_DH", []) + x.get("children_HD", [])) for x in childrenLeft ] if max(leftLengths + [0]) == 0: if len(leftDependencies) == 1: continue #print(leftDependencies, leftLengths) dependents = [ sentence[i - 1] for i in line.get("children_DH", []) ] if model_[1] != "": positions = {{ "A": "amod", "N": "nummod", "D": "det" }[x]: model_[1].index(x) for x in "AND"} positions["case"] = -1 # print(positions) dependents = sorted( dependents, key=lambda x: positions[x["coarse_dep"]]) # quit() # if args.model == "GROUND_AND": # dependents = sorted(dependents, key=lambda x:{"case" : -1, "amod" : 0, "nummod" : 1, "det" : 2}[x["coarse_dep"]]) # elif args.model == "GROUND_NDA": # dependents = sorted(dependents, key=lambda x:{"case" : -1, "amod" : 2, "nummod" : 0, "det" : 1}[x["coarse_dep"]]) # elif args.model == "GROUND_ADN": # dependents = sorted(dependents, key=lambda x:{"case" : -1, "amod" : 0, "nummod" : 2, "det" : 1}[x["coarse_dep"]]) # elif args.model == "GROUND_DAN": # dependents = sorted(dependents, key=lambda x:{"case" : -1, "amod" : 1, "nummod" : 2, "det" : 0}[x["coarse_dep"]]) # elif args.model != "GROUND": # assert False nounPhrases.append(dependents + [line]) if random() > 0.98: print([x["word"] for x in nounPhrases[-1]]) return nounPhrases
from mixture import * from random import * N = 50 M = 40 G = 8 pi1 = [] mList1 = [] for j in range(G): p = [] for i in range(N): p.append(random()) g = lambda x: x / sum(p) p = map(g, p) pi1.append(random()) mList1.append(MultinomialDistribution(M, N, p)) fpi = lambda x: x / sum(pi1) pi1 = map(fpi, pi1) mix = MixtureModel(G, pi1, mList1) [true, s] = mix.labelled_sample(75) pi2 = [] mList2 = [] for j in range(G): p2 = []
def orderSentence(sentence, dhLogits, printThings): root = None logits = [None] * len(sentence) logProbabilityGradient = 0 sentenceHash = hash_(" ".join([x["word"] for x in sentence])) for line in sentence: line["fine_dep"] = line["dep"] if line["fine_dep"] == "root": root = line["index"] continue if line["fine_dep"].startswith("punct"): continue posHead = sentence[line["head"] - 1]["posUni"] posHere = line["posUni"] if line["dep"] == "nsubj" and posHead == "VERB" and posHere == "NOUN": line["dep"] = "nsubj_" + str(sentenceHash) line["fine_dep"] = line["dep"] key = (posHead, line["fine_dep"], posHere) if line["fine_dep"] != "root" else stoi_deps["root"] line["dependency_key"] = key dhLogit = dhWeights[stoi_deps[key]] probability = 1 / (1 + torch.exp(-dhLogit)) dhSampled = (random() < probability.data.numpy()) line["ordering_decision_log_probability"] = torch.log( 1 / (1 + torch.exp(-(1 if dhSampled else -1) * dhLogit))) direction = "DH" if dhSampled else "HD" if printThings: print "\t".join( map(str, [ "ORD", line["index"], (line["word"] + " ")[:10], (".".join(list(key)) + " ")[:22], line["head"], dhSampled, direction, (str(float(probability)) + " ")[:8], str(1 / (1 + exp(-dhLogits[key])))[:8], (str(distanceWeights[stoi_deps[key]].data.numpy()) + " ")[:8], str(originalDistanceWeights[key])[:8] ])) headIndex = line["head"] - 1 sentence[headIndex]["children_" + direction] = ( sentence[headIndex].get("children_" + direction, []) + [line["index"]]) sentence[headIndex]["children_decisions_logprobs"] = ( sentence[headIndex].get("children_decisions_logprobs", []) + [line["ordering_decision_log_probability"]]) for line in sentence: if "children_DH" in line: childrenLinearized = orderChildrenRelative(sentence, line["children_DH"][:], False) line["children_DH"] = childrenLinearized if "children_HD" in line: childrenLinearized = orderChildrenRelative(sentence, line["children_HD"][:], True) line["children_HD"] = childrenLinearized linearized = [] recursivelyLinearize(sentence, root, linearized, Variable(torch.FloatTensor([0.0]))) if printThings or len(linearized) == 0: print " ".join(map(lambda x: x["word"], sentence)) print " ".join(map(lambda x: x["word"], linearized)) # store new dependency links moved = [None] * len(sentence) for i, x in enumerate(linearized): moved[x["index"] - 1] = i for i, x in enumerate(linearized): if x["head"] == 0: # root x["reordered_head"] = 0 else: x["reordered_head"] = 1 + moved[x["head"] - 1] return linearized, logits
stoi_deps = dict(zip(itos_deps, range(len(itos_deps)))) print itos_deps relevantPath = "/u/scr/mhahn/deps/DLM_MEMORY_OPTIMIZED/locality_optimized_dlm/manual_output_funchead_fine_depl_funchead_perSent/" import os dhWeights = Variable(torch.FloatTensor([0.0] * len(itos_deps)), requires_grad=True) distanceWeights = Variable(torch.FloatTensor([0.0] * len(itos_deps)), requires_grad=True) for i, key in enumerate(itos_deps): dhLogits[key] = 0.0 if key == ("VERB", "obj", "NOUN"): dhLogits[key] = (10.0 if random() < 0.5 else -10.0) dhWeights.data[i] = dhLogits[key] originalDistanceWeights[key] = 0.0 #random() distanceWeights.data[i] = originalDistanceWeights[key] assert abs(float(dhWeights.data.sum())) == 10, dhWeights.data.sum() words = list(vocab.iteritems()) words = sorted(words, key=lambda x: x[1], reverse=True) itos = map(lambda x: x[0], words) stoi = dict(zip(itos, range(len(itos)))) if len(itos) > 6: assert stoi[itos[5]] == 5 vocab_size = 50000
def cheb_eval_e(cs, x, result): cs_0 = cs x_0 = x result_0 = result dd_0 = None dd_2 = None dd_1 = None dd_3 = None temp_1 = None temp_0 = None temp_2 = None temp_3 = None d_0 = None d_2 = None d_1 = None d_3 = None d_4 = None e_0 = None e_2 = None e_1 = None e_3 = None e_4 = None cs_c_j_IV_1 = None cs_c_j_IV_0 = None cs_c_j_IV_2 = None cs_c_cs_order_IV_0 = None cs_c_0_IV_0 = None result_err_0 = None cs_a_IV_0 = None result_val_IV_0 = None cs_b_IV_0 = None y_0 = None y2_0 = None gen_bad = random() < probability global insertion_count if gen_bad: insertion_count += 1 d_0 = 0.0 dd_0 = 0.0 cs_a_IV_0 = cs_0.a cs_b_IV_0 = cs_0.b y_0 = (2.0 * x_0 - cs_a_IV_0 - cs_b_IV_0) / (cs_b_IV_0 - cs_a_IV_0) y2_0 = 2.0 * y_0 e_0 = 0.0 phi0 = Phi() for j_0 in range(cs_0.order, 0, -1): phi0.set() dd_2 = phi0.phiEntry(dd_0, dd_1) temp_1 = phi0.phiEntry(None, temp_0) d_2 = phi0.phiEntry(d_0, d_1) e_2 = phi0.phiEntry(e_0, e_1) cs_c_j_IV_1 = phi0.phiEntry(None, cs_c_j_IV_0) temp_0 = d_2 cs_c_j_IV_0 = cs_0.c[j_0] d_1 = y2_0 * d_2 - dd_2 + cs_c_j_IV_0 e_1 = e_2 + fabs(y2_0 * temp_0) + fabs(dd_2) + fabs(cs_c_j_IV_0) dd_1 = temp_0 dd_3 = phi0.phiExit(dd_0, dd_1) temp_2 = phi0.phiExit(None, temp_0) d_3 = phi0.phiExit(d_0, d_1) e_3 = phi0.phiExit(e_0, e_1) cs_c_j_IV_2 = phi0.phiExit(None, cs_c_j_IV_0) temp_3 = d_3 cs_c_0_IV_0 = cs_0.c[0] d_4 = fuzzy(y_0 * d_3 - dd_3 + 0.5 * cs_c_0_IV_0, gen_bad) e_4 = e_3 + fabs(y_0 * temp_3) + fabs(dd_3) + 0.5 * fabs(cs_c_0_IV_0) result_val_IV_0 = d_4 result_0.val = result_val_IV_0 cs_c_cs_order_IV_0 = cs_0.c[cs_0.order] result_err_0 = GSL_DBL_EPSILON * e_4 + fabs(cs_c_cs_order_IV_0) result_0.err = result_err_0 lo = locals() record_locals(lo, test_counter) return GSL_SUCCESS
def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ ghostState.scaredTimer for ghostState in newGhostStates ] "*** YOUR CODE HERE ***" from random import random pos = currentGameState.getPacmanPosition() food = currentGameState.getFood() ghostStates = currentGameState.getGhostStates() scaredTimes = [ghostState.scaredTimer for ghostState in ghostStates] distance = lambda x: util.manhattanDistance(x, newPos) ghostPositions = map(lambda x: x.getPosition(), newGhostStates) distance_to_ghosts = sum(map(distance, ghostPositions)) def food_distance(foodList): distance_to_closest_food = float('inf') for pellet in foodList: distance_to_closest_food = min(distance_to_closest_food, distance(pellet)) return distance_to_closest_food distance_to_food = food_distance(food.asList()) distance_to_new_food = food_distance(newFood.asList()) better_score = successorGameState.getScore( ) > currentGameState.getScore() lost = successorGameState.isLose() won = successorGameState.isWin() less_food = len(newFood.asList()) < len(food.asList()) closer_to_food = distance_to_new_food < distance_to_food ghosts_too_close = distance_to_ghosts < 4 value = (better_score * 5) \ - (lost * 100) \ + (won * 100) \ + (less_food * 5) \ + (closer_to_food) \ + random() \ + (1.0 / (distance_to_food + 0.00000001)) if ghosts_too_close: non_zero_distance = distance_to_ghosts + 0.000001 ghost_penalty = (1.0 / non_zero_distance) * 100 value -= ghost_penalty return value
def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <write something here so we know what you did> """ "*** YOUR CODE HERE ***" from pprint import pprint from operator import attrgetter from random import random # pprint(currentGameState.data.__dict__) # pprint(currentGameState.data.agentStates[0].__dict__) # pprint(currentGameState.data.agentStates[1].__dict__) # pprint(currentGameState.data.agentStates[1].configuration.__dict__) pacman = currentGameState.data.agentStates[0] ghosts = currentGameState.data.agentStates[1:] ghost_scared_timers = map(attrgetter('scaredTimer'), ghosts) ghost_positions = map(attrgetter('configuration.pos'), ghosts) gs = zip(ghost_scared_timers, ghost_positions) moved = currentGameState.data._agentMoved food = currentGameState.data.food.asList() capsules = currentGameState.data.capsules score = currentGameState.data.score scoreChange = currentGameState.data.scoreChange win = currentGameState.data._win lose = currentGameState.data._lose dist_func = lambda x: util.manhattanDistance(pacman.configuration.pos, x) distance_to_ghosts = sum(map(dist_func, ghost_positions)) value = score \ + win * 100 \ + lose * -1000 \ + (1.0 / (len(food) + 1)) * 10 \ + (1.0 / (len(capsules) + 1)) \ + random() / 10.0 # + distance_to_ghosts \ distance_to_closest_food = float('inf') for pellet in food: distance_to_closest_food = min(distance_to_closest_food, dist_func(pellet)) if distance_to_closest_food < float('inf'): value += 10.0 / distance_to_closest_food def min_dist(lst): closest_dist = float('inf') for point in lst: closest_dist = min(closest_dist, dist_func(point)) return closest_dist distance_to_closest_cap = min_dist(capsules) if distance_to_closest_cap < float('inf'): value += 1.0 / distance_to_closest_cap distance_to_ghosts = min_dist(ghost_positions) ghosts_too_close = distance_to_ghosts < 4 if ghosts_too_close: non_zero_distance = distance_to_ghosts + 0.000001 ghost_penalty = (1.0 / non_zero_distance) * 100 value -= ghost_penalty return value
oval(545, 783, 9, 7) oval(548, 765, 28, 15) #ГЛАЗА НОС penSize(1) penColor(100, 100, 100) brushColor(0, 0, 0) circle(547, 762, 3) circle(559, 758, 3) circle(574, 764, 1) #ИГЛЫ1 penColor(50, 50, 50) brushColor(35, 28, 28) for i in range(20): tre2(390 + 70 * (random() - 0.5), 778 + 45 * (random() - 0.5), 0.4 * (random() + 0.2)) a = random() if a > 0.4 and a < 0.47: brushColor(200, 113, 56) circle(390 + 40 * (random() - 0.5), 740 + 40 * (random() - 0.5), 20) brushColor(35, 28, 28) for i in range(20): tre2(450 + 70 * (random() - 0.5), 778 + 45 * (random() - 0.5), 0.4 * (random() - 0.2)) for i in range(20): tre2(490 + 70 * (random() - 0.5), 778 + 45 * (random() - 0.5), 0.4 * (-random() - 0.1)) #ОВОЩИ grib(430, 750)
def gsl_sf_bessel_J0_e(x, result): x_1 = x result_2 = result stat_ca_0 = None stat_ca_1 = None ampl_0 = None ampl_1 = None ca_err_IV_0 = None ca_err_IV_1 = None cp_err_IV_0 = None cp_err_IV_1 = None result_err_7 = None result_err_8 = None result_err_9 = None result_err_10 = None result_err_11 = None cp_0 = None cp_1 = None ct_val_IV_0 = None ct_val_IV_1 = None result_val_1 = None result_val_2 = None result_val_3 = None sqrty_0 = None sqrty_1 = None ct_0 = None ct_1 = None ca_val_IV_0 = None ca_val_IV_1 = None cp_val_IV_0 = None cp_val_IV_1 = None cp_val_IV_2 = None stat_cp_0 = None stat_cp_1 = None result_val_IV_1 = None result_val_IV_2 = None stat_ct_0 = None stat_ct_1 = None y_2 = None z_0 = None z_1 = None ca_0 = None ca_1 = None gen_bad = random() < probability global insertion_count if gen_bad: insertion_count += 1 y_2 = fabs(x_1) if y_2 < 2.0 * GSL_SQRT_DBL_EPSILON: result_val_1 = 1.0 result_2.val = result_val_1 result_err_7 = y_2 * y_2 result_2.err = result_err_7 lo = locals() record_locals(lo, test_counter) return GSL_SUCCESS elif y_2 <= 4.0: lo = locals() record_locals(lo, test_counter) return cheb_eval_e(bj0_cs, 0.125 * y_2 * y_2 - 1.0, result_2) else: ca_0 = gsl_sf_result(0.0, 0.0) ct_0 = gsl_sf_result(0.0, 0.0) cp_0 = gsl_sf_result(0.0, 0.0) z_0 = 32.0 / (y_2 * y_2) - 1.0 stat_ca_0 = cheb_eval_e(_gsl_sf_bessel_amp_phase_bm0_cs, z_0, ca_0) stat_ct_0 = cheb_eval_e(_gsl_sf_bessel_amp_phase_bth0_cs, z_0, ct_0) ct_val_IV_0 = ct_0.val stat_cp_0 = gsl_sf_bessel_cos_pi4_e(y_2, ct_val_IV_0 / y_2, cp_0) sqrty_0 = sqrt(y_2) ca_val_IV_0 = ca_0.val ampl_0 = fuzzy((0.75 + ca_val_IV_0) / sqrty_0, gen_bad) cp_val_IV_0 = cp_0.val result_val_2 = ampl_0 * cp_val_IV_0 result_2.val = result_val_2 cp_val_IV_1 = cp_0.val ca_err_IV_0 = ca_0.err cp_err_IV_0 = cp_0.err result_err_8 = fabs(cp_val_IV_1) * ca_err_IV_0 / sqrty_0 + fabs( ampl_0) * cp_err_IV_0 result_2.err = result_err_8 result_val_IV_1 = result_2.val result_err_9 = result_2.err result_err_10 = result_err_9 + GSL_DBL_EPSILON * fabs(result_val_2) result_2.err = result_err_10 lo = locals() record_locals(lo, test_counter) return GSL_ERROR_SELECT_3(stat_ca_0, stat_ct_0, stat_cp_0) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, stat_ca_0] stat_ca_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, ampl_0] ampl_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, ca_err_IV_0] ca_err_IV_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, cp_err_IV_0] cp_err_IV_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [result_err_7, None, result_err_10] result_err_11 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, cp_0] cp_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, ct_val_IV_0] ct_val_IV_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [result_val_1, None, result_val_2] result_val_3 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, sqrty_0] sqrty_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, ct_0] ct_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, ca_val_IV_0] ca_val_IV_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, cp_val_IV_1] cp_val_IV_2 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, stat_cp_0] stat_cp_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, result_val_IV_1] result_val_IV_2 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, stat_ct_0] stat_ct_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, z_0] z_1 = phiIf(phiPreds, phiNames) phiPreds = [y_2 < 2.0 * GSL_SQRT_DBL_EPSILON, y_2 <= 4.0] phiNames = [None, None, ca_0] ca_1 = phiIf(phiPreds, phiNames)
itos_deps = sorted(vocab_deps) stoi_deps = dict(zip(itos_deps, range(len(itos_deps)))) dhWeights = [0.0] * len(itos_deps) distanceWeights = [0.0] * len(itos_deps) import os if args.model == "REAL" or args.model == "REAL_REAL": originalCounter = "NA" elif args.model == "RANDOM_BY_TYPE": dhByType = {} distByType = {} for dep in itos_pure_deps: dhByType[dep.split(":")[0]] = random() - 0.5 distByType[dep.split(":")[0]] = random() for key in range(len(itos_deps)): dhWeights[key] = dhByType[itos_deps[key][1].split(":")[0]] distanceWeights[key] = distByType[itos_deps[key][1].split(":")[0]] originalCounter = "NA" elif args.model.startswith("GROUND"): groundPath = "/u/scr/mhahn/deps/manual_output_ground_coarse/" import os files = [ x for x in os.listdir(groundPath) if x.startswith(args.language[:args.language.rfind("_")] + "_infer") ] print(files) assert len(files) > 0 with open(groundPath + files[0], "r") as inFile:
# 10.6 # 10.6 #We can find help for any module by using help() function #import math #help(math) # Working with random module: # This module defines several functions to generate random numbers. # 1. random() function: # This function always generate some float value between 0 and 1 ( not inclusive) # 0<x<1 from random import * for i in range(5): print(random()) # 0.07990074114281398 # 0.36859019598438514 # 0.5902214425800926 # 0.9577999234654806 # 0.6404993189190803 #2. randint() function: #To generate random integer beween two given numbers(inclusive) from random import * for i in range(5): print(randint(1,100)) # out-100 # 20 # 7
def gsl_sf_pow_int_e(x,n,result): x_1 = x;n_1 = n;result_2 = result; result_val_1=None;result_val_2=None;result_val_3=None;result_val_4=None;u_0=None;u_1=None;u_2=None;x_2=None;x_3=None;x_5=None;x_4=None;x_6=None;count_0=None;count_2=None;count_1=None;count_3=None;result_err_1=None;result_err_2=None;result_err_3=None;result_err_4=None;value_1=None;value_4=None;value_2=None;value_3=None;value_5=None;n_2=None;n_3=None;n_5=None;n_4=None;n_6=None; gen_bad = random() < probability global insertion_count if gen_bad: insertion_count += 1 value_1=1.0 count_0=0 if n_1<0: n_2=-n_1 if x_1==0.0: u_0=1.0/x_1 result_val_1=u_0 if n_2%2==1 else u_0*u_0 result_err_1=inf result_2.val=result_val_1 result_2.err=result_err_1 print("overflow err") phiPreds = [x_1==0.0] phiNames = [result_val_1,None] result_val_2= phiIf(phiPreds, phiNames) phiPreds = [x_1==0.0] phiNames = [u_0,None] u_1= phiIf(phiPreds, phiNames) phiPreds = [x_1==0.0] phiNames = [result_err_1,None] result_err_2= phiIf(phiPreds, phiNames) x_2=1.0/x_1 phiPreds = [n_1<0] phiNames = [result_val_2,None] result_val_3= phiIf(phiPreds, phiNames) phiPreds = [n_1<0] phiNames = [u_1,None] u_2= phiIf(phiPreds, phiNames) phiPreds = [n_1<0] phiNames = [x_2,x_1] x_3= phiIf(phiPreds, phiNames) phiPreds = [n_1<0] phiNames = [result_err_2,None] result_err_3= phiIf(phiPreds, phiNames) phiPreds = [n_1<0] phiNames = [n_2,n_1] n_3= phiIf(phiPreds, phiNames) phi0 = Phi() while True: phi0.set() x_5 = phi0.phiEntry(x_3,x_4) count_2 = phi0.phiEntry(count_0,count_1) value_4 = phi0.phiEntry(value_1,value_3) n_5 = phi0.phiEntry(n_3,n_4) if GSL_IS_ODD(n_5): value_2 = value_4*x_5 phiPreds = [GSL_IS_ODD(n_5)] phiNames = [value_2,value_4] value_3= phiIf(phiPreds, phiNames) n_4 = n_5>>1 x_4 = fuzzy(x_5*x_5, gen_bad) count_1 = count_2+1 if n_4==0: break x_6 = phi0.phiExit(x_3,x_4) count_3 = phi0.phiExit(count_0,count_1) value_5 = phi0.phiExit(value_1,value_3) n_6 = phi0.phiExit(n_3,n_4) result_val_4=value_5 result_err_4=2.0*GSL_DBL_EPSILON*(count_3+1.0)*fabs(value_5) result_2.val=result_val_4 result_2.err=result_err_4 lo = locals() record_locals(lo, test_counter) return GSL_SUCCESS
def __init__(self, alpha, no_of_inputs): self.alpha = alpha self.act = 0.0 self.weights = [random() for _ in range(no_of_inputs)]
def testFsum(self): # math.fsum relies on exact rounding for correct operation. # There's a known problem with IA32 floating-point that causes # inexact rounding in some situations, and will cause the # math.fsum tests below to fail; see issue #2937. On non IEEE # 754 platforms, and on IEEE 754 platforms that exhibit the # problem described in issue #2937, we simply skip the whole # test. # Python version of math.fsum, for comparison. Uses a # different algorithm based on frexp, ldexp and integer # arithmetic. from sys import float_info mant_dig = float_info.mant_dig etiny = float_info.min_exp - mant_dig def msum(iterable): """Full precision summation. Compute sum(iterable) without any intermediate accumulation of error. Based on the 'lsum' function at http://code.activestate.com/recipes/393090/ """ tmant, texp = 0, 0 for x in iterable: mant, exp = math.frexp(x) mant, exp = int(math.ldexp(mant, mant_dig)), exp - mant_dig if texp > exp: tmant <<= texp-exp texp = exp else: mant <<= exp-texp tmant += mant # Round tmant * 2**texp to a float. The original recipe # used float(str(tmant)) * 2.0**texp for this, but that's # a little unsafe because str -> float conversion can't be # relied upon to do correct rounding on all platforms. tail = max(len(bin(abs(tmant)))-2 - mant_dig, etiny - texp) if tail > 0: h = 1 << (tail-1) tmant = tmant // (2*h) + bool(tmant & h and tmant & 3*h-1) texp += tail return math.ldexp(tmant, texp) test_values = [ ([], 0.0), ([0.0], 0.0), ([1e100, 1.0, -1e100, 1e-100, 1e50, -1.0, -1e50], 1e-100), ([2.0**53, -0.5, -2.0**-54], 2.0**53-1.0), ([2.0**53, 1.0, 2.0**-100], 2.0**53+2.0), ([2.0**53+10.0, 1.0, 2.0**-100], 2.0**53+12.0), ([2.0**53-4.0, 0.5, 2.0**-54], 2.0**53-3.0), ([1./n for n in range(1, 1001)], float.fromhex('0x1.df11f45f4e61ap+2')), ([(-1.)**n/n for n in range(1, 1001)], float.fromhex('-0x1.62a2af1bd3624p-1')), ([1.7**(i+1)-1.7**i for i in range(1000)] + [-1.7**1000], -1.0), ([1e16, 1., 1e-16], 10000000000000002.0), ([1e16-2., 1.-2.**-53, -(1e16-2.), -(1.-2.**-53)], 0.0), # exercise code for resizing partials array ([2.**n - 2.**(n+50) + 2.**(n+52) for n in range(-1074, 972, 2)] + [-2.**1022], float.fromhex('0x1.5555555555555p+970')), ] for i, (vals, expected) in enumerate(test_values): try: actual = math.fsum(vals) except OverflowError: self.fail("test %d failed: got OverflowError, expected %r " "for math.fsum(%.100r)" % (i, expected, vals)) except ValueError: self.fail("test %d failed: got ValueError, expected %r " "for math.fsum(%.100r)" % (i, expected, vals)) self.assertEqual(actual, expected) from random import random, gauss, shuffle for j in range(1000): vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10 s = 0 for i in range(200): v = gauss(0, random()) ** 7 - s s += v vals.append(v) shuffle(vals) s = msum(vals) self.assertEqual(msum(vals), math.fsum(vals))
def random_data(length, start, end): data = [] for i in range(0, length): data.append(int(random() * (end + 1) - start)) data.sort() return data
itos_pure_deps = sorted(list(depsVocab)) stoi_pure_deps = dict(zip(itos_pure_deps, range(len(itos_pure_deps)))) itos_deps = sorted(vocab_deps) stoi_deps = dict(zip(itos_deps, range(len(itos_deps)))) dhWeights = [0.0] * len(itos_deps) distanceWeights = [0.0] * len(itos_deps) import os if model == "RANDOM_MODEL": assert False for key in range(len(itos_deps)): dhWeights[key] = random() - 0.5 distanceWeights[key] = random() originalCounter = "NA" elif model == "REAL" or model == "REAL_REAL": originalCounter = "NA" elif model == "RANDOM_BY_TYPE": dhByType = {} distByType = {} for dep in itos_pure_deps: dhByType[dep.split(":")[0]] = random() - 0.5 distByType[dep.split(":")[0]] = random() for key in range(len(itos_deps)): dhWeights[key] = dhByType[itos_deps[key][1].split(":")[0]] distanceWeights[key] = distByType[itos_deps[key][1].split(":")[0]] originalCounter = "NA" elif model == "RANDOM_BY_TYPE_CONS":
def kmeansCondensationN(self, k=10, lowInit=None, highInit=None, maxIter=100): ''' Condenses mixands by first clustering them into k groups, using k-means. Then each group is condensed to a single Gaussian using Runnalls Method. Each Gaussian is then added to a new GMM. Has a tendency to overcondense Inputs: k: number of mixands in the returned GMM lowInit: lower bound on the placement of initial grouping means highInit: upper bound on placement of initial grouping means ''' if (self.size <= k): return self if (lowInit == None): lowInit = [0] * len(self.Gs[0].mean) if (highInit == None): highInit = [5] * len(self.Gs[0].mean) #Initialize the means. Spread randomly through the bounded space means = [0] * k for i in range(0, k): tmp = [] if (isinstance(self.Gs[0].mean, list)): for j in range(0, len(self.Gs[0].mean)): tmp.append(random() * (highInit[j] - lowInit[j]) + lowInit[j]) else: tmp.append(random() * (highInit - lowInit) + lowInit) means[i] = tmp converge = False count = 0 newMeans = [0] * k while (converge == False and count < maxIter): clusters = [GM() for i in range(0, k)] for g in self.Gs: #put the gaussian in the cluster which minimizes the distance between the distribution mean and the cluster mean if (isinstance(g.mean, list)): clusters[np.argmin([ self.distance(g.mean, means[j]) for j in range(0, k) ])].addG(g) else: clusters[np.argmin([ self.distance([g.mean], means[j]) for j in range(0, k) ])].addG(g) #find the mean of each cluster newMeans = [0] * k for i in range(0, k): if (isinstance(self.Gs[0].mean, list)): newMeans[i] = np.array([0] * len(self.Gs[0].mean)) for g in clusters[i].Gs: newMeans[i] = np.add(newMeans[i], np.divide(g.mean, clusters[i].size)) if (np.array_equal(means, newMeans)): converge = True count = count + 1 for i in range(0, len(newMeans)): for j in range(0, len(newMeans[i])): means[i][j] = newMeans[i][j] #condense each cluster for c in clusters: c.condense(1) #add each cluster back together ans = GM() for c in clusters: ans.addGM(c) ans.action = self.action #Make sure everything is positive semidefinite #TODO: dont just remove them, fix them? dels = [] for g in ans.Gs: if (det(np.matrix(g.var)) <= 0): dels.append(g) for rem in dels: if (rem in ans.Gs): ans.Gs.remove(rem) ans.size -= 1 #return the resulting GMM return ans
stoi_pure_deps = dict(zip(itos_pure_deps, range(len(itos_pure_deps)))) itos_deps = itos_pure_deps stoi_deps = stoi_pure_deps #print itos_deps #dhWeights = [0.0] * len(itos_deps) distanceWeights = [0.0] * len(itos_deps) import os if model == "RANDOM_MODEL": for key in range(len(itos_deps)): #dhWeights[key] = random() - 0.5 distanceWeights[key] = random() originalCounter = "NA" elif model == "REAL" or model == "REAL_REAL": originalCounter = "NA" elif model == "RANDOM_BY_TYPE": #dhByType = {} distByType = {} generateGrammar = random.Random(5) for dep in itos_pure_deps: # dhByType[dep] = random() - 0.5 distByType[dep] = generateGrammar.random() for key in range(len(itos_deps)): # dhWeights[key] = dhByType[itos_deps[key]] distanceWeights[key] = distByType[itos_deps[key]] originalCounter = "NA"
# 난수로 pi의 근삿값을 구해보기 # Monte Carlo 방법: 난수를 수학 문제 해결에 사용함 # 원면적 / 사각형면적 = pi * r^2 / (2 * r)^2 = pi / 4 # 전체 원을 생각하지 말고, 사분원만을 생각하면 됨! (완벽한 대칭이므로) # 1. 0.0 ~ 1.0까지의 난수를 발생해 원 안에 떨어지면 inside 변수가 증가함 # 2. 원 안에 떨어졌다는 의미는 원점으로부터 거리가 1.0 이하이어야 함 # 원점으로부터 거리가 1.0이하라는 의미는 원 반지름 범위 안에 있어야 함을 의미 # 3. 전체 점(n)들 중에서 원안에 있는 점(insides)들의 비율 insides/n을 계산한 것이 pi / 4임 # 4. pi = 4 * insides / n from random import * from math import sqrt n = int(input("반복횟수를 입력: ")) #이 횟수가 클수록 점점 더 근사해짐 insides = 0 #사분원 안에 들어오면 증가함 for i in range(0, n): #반복횟수만큼 반복함 x = random() #[0.0, 1.0) 사이의 난수 발생 (소수) y = random() if sqrt(x**2 + y**2) <= 1: #원점으로부터 거리가 1.0(반지름)이하라면 insides += 1 pi = 4 * insides / n #4분원만 생각했으므로! print(pi)
6 || week || 0-6 7 || day of year || 1-366 8 || summer time || 0,1 or -1 """ """ asctime(tuple) || time tuple to string localtime(secs) || sec value to time tuple, convertion by local time gmtime(secs) || mktime(tuple) || time tuple to local time sleep(secs) || sleep strptime(string(,format)) || time string to time tuple time() || current time UTC """ ### random : """ random() || random 0-1 getrandbits(n) || longint type return a n bit binary num uniform(a,b) || random value(float) between a,b randrange([start],stop,[step]) || random int in range(condition) choice(seq) || random choice shuffle(seq[,rand]) || shuffle sample(seq,n) || random choice a number of samples """ from random import * val = getrandbits(16) # a 16 bits rand print val values = range(1, 11) + 'Jack Queen King'.split() suits = 'diampnds clubs hearts spades'.split()
Python 2.7.6 (default, Sep 9 2014, 15:04:36) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin Type "copyright", "credits" or "license()" for more information. >>> import random >>> random.randint(0, 5) 1 >>> random.choice9[1,3,5,7,9]) SyntaxError: invalid syntax >>> random.choice([1.3.5.7.9]) SyntaxError: invalid syntax >>> random.choice([1, 3, 5, 7, 9]) 1 >>> random.choice([1, 3, 5, 7, 9]) 9 >>> random,random() Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> random,random() TypeError: 'module' object is not callable >>> random.random() 0.5290582054438404 >>> hel(random) Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> hel(random) NameError: name 'hel' is not defined >>> help(random) Help on module random:
def random_points(k): points = [] for k in range(k): points.append(Point(random(), random()))
def Run(self): print "start" seed() maxVal = 0.04 file_path = "./" listener = tf.TransformListener() nr_images = 14 # move components to initial position self.sss.move("head", "back") self.sss.move("arm", "calib") self.sss.move("torso", "home") self.sss.move("sdh", "home") self.sss.wait_for_input() self.sss.move("sdh", "calib") self.sss.wait_for_input() # start calbration routine for i in range(1, nr_images): if i == 1: r1 = maxVal r2 = maxVal elif i == 2: r1 = -maxVal r2 = maxVal elif i == 3: r1 = maxVal r2 = -maxVal elif i == 4: r1 = -maxVal r2 = -maxVal else: r1 = (random() - 0.5) * 2 * maxVal r2 = (random() - 0.5) * 2 * maxVal self.sss.move("torso", [[r1, r2, r1, r2]]) self.sss.sleep(1) try: (trans, rot) = listener.lookupTransform('/base_link', '/head_color_camera_r_link', rospy.Time(0)) rpy = euler_from_quaternion(rot) cyaw = cos(rpy[2]) syaw = sin(rpy[2]) cpitch = cos(rpy[1]) spitch = sin(rpy[1]) croll = cos(rpy[0]) sroll = sin(rpy[0]) R11 = cyaw * cpitch R12 = cyaw * spitch * sroll - syaw * croll R13 = cyaw * spitch * croll + syaw * sroll R21 = syaw * cpitch R22 = syaw * spitch * sroll + cyaw * croll R23 = syaw * spitch * croll - cyaw * sroll R31 = -spitch R32 = cpitch * sroll R33 = cpitch * croll fout = open(file_path + 'calpic' + str(i) + '.coords', 'w') fout.write( str(R11) + ' ' + str(R12) + ' ' + str(R13) + ' ' + str(trans[0] * 1000) + '\n' + str(R21) + ' ' + str(R22) + ' ' + str(R23) + ' ' + str(trans[1] * 1000) + '\n' + str(R31) + ' ' + str(R32) + ' ' + str(R33) + ' ' + str(trans[2] * 1000)) fout.close() except (tf.LookupException, tf.ConnectivityException): print "tf exception" self.sss.sleep(1) cv.SaveImage(file_path + 'calpic' + str(i) + '.png', self.cv_image) self.sss.sleep(1) self.sss.move("torso", "home") print "finished"
# 2-4 랜덤함수 from random import * # 랜덤 라이브러리 불러오기 print(random()) # 0.0 ~ 1.0 미만의 임의의 값 생성 print(random() * 10) # 0.0 ~ 10.0 미만의 임의의 값 생성 print(int(random() * 10)) # 0 ~ 10 미만의 임의의 값 생성 / int() : 정수값 부분만 볼 수 있게 해줌 print(int(random() * 10) + 1) # 1 ~ 10 이하의 임의의 값 생성 # 로또 숫자를 뽑기 print(int(random() * 45) + 1) # 1 ~ 45 이하의 임의의 값 생성 print(randrange(1, 46)) # 1 ~ 46 미만의 임의의 값 생성 (정수값) print(randint(1, 45)) # 1 ~ 45 이하의 임의의 값 생성 (정수값)
def train_or_test_set(train_file, test_file): probility = random() if probility < (2/3): return trainfile, 0 else: return testfile, 1
itos_deps = sorted(vocab_deps) stoi_deps = dict(zip(itos_deps, range(len(itos_deps)))) dhWeights = [0.0] * len(itos_deps) distanceWeights = [0.0] * len(itos_deps) import os if args.model == "REAL" or args.model == "REAL_REAL": originalCounter = "NA" elif args.model == "RANDOM_BY_TYPE": dhByType = {} distByType = {} for dep in itos_pure_deps: dhByType[makeCoarse(dep)] = random() - 0.5 distByType[makeCoarse(dep)] = random() for key in range(len(itos_deps)): key_ = itos_deps[key] _, dep, _, _ = key_ dhWeights[key] = dhByType[makeCoarse(dep)] distanceWeights[key] = distByType[makeCoarse(dep)] originalCounter = "NA" elif args.model == "RANDOM_INFOSTRUC": dhByType = {} distByType = {} for dep in itos_pure_deps: for infostruc in ["N", "f", "c", "t"]: dhByType[(makeCoarse(dep), infostruc)] = random() - 0.5 distByType[(makeCoarse(dep), infostruc)] = random() for key in range(len(itos_deps)):
def initPop(): for i in range(POP_SIZE): universe = [random() for i in range(MAX_FEATURE)] Population.append(universe)
def winsServe(self): # Returns true with probability self.prob return random() <= self.prob
def mvoParkinson(): readData() allFeatures() initPop() for i in range(len(Population)): universeObj = { 'universe': Population[i], 'cost': calc_Fitness(Population[i]) } Universes.append(universeObj) Time = 1 while Time < MAX_ITER + 1: #WEP Update WEP = WEP_Min + Time * ((WEP_Max - WEP_Min) / MAX_ITER) #TDR Update TDR = 1 - ((Time)**(1 / 6) / (MAX_ITER)**(1 / 6)) BestCost = best_cost() BestUniverse = [ x['universe'] for x in Universes if x['cost'] == BestCost ] SortedUniverses = Universes[:] SortedUniverses.sort(key=operator.itemgetter('cost'), reverse=True) NormalizedRates = [x['cost'] for x in SortedUniverses] NormalizedRates = np.array(NormalizedRates) NormalizedRates = (NormalizedRates - np.min(NormalizedRates)) / ( np.max(NormalizedRates) - np.min(NormalizedRates)) for i in range(1, len(Population)): black_hole_index = i for j in range(MAX_FEATURE): #Exploration r1 = random() if r1 < NormalizedRates[i]: white_hole_index = roulette_wheel_selection( NormalizedRates) if white_hole_index == -1: white_hole_index = 0 Universes[black_hole_index]['universe'][ j] = SortedUniverses[white_hole_index]['universe'][j] #Exploitation r2 = random() if r2 < WEP: r3 = random() if r3 < 0.5: Universes[i]['universe'][ j] = BestUniverse[0][j] + TDR * (random()) else: Universes[i]['universe'][ j] = BestUniverse[0][j] - TDR * (random()) if Universes[i]['universe'][j] > 1: Universes[i]['universe'][j] = 1 if Universes[i]['universe'][j] < 0: Universes[i]['universe'][j] = 0 for i in range(len(Population)): Universes[i] = { 'universe': Universes[i]['universe'], 'cost': calc_Fitness(Universes[i]['universe']) } print(BestCost) Time = Time + 1
import random num1= int(input ("enter a num")): num2=int(input("enetr a num")): num3 =random(radint(num1,num2)): guess=int(input("guess the number")): if num3 > guess : print ( " lower number " ) if num3 < guess : print ( " higher number" ) if num3 == guess : print ( " perfect ")