def bomb_check(self): """ Comprueba el estado de las bombas activas. Realiza su trabajo en otro thread. """ # TODO: Excepciones while self.current_timer > -1: with player_damage_lock: for bomb in self.bombs: if time() - 1 >= self.start_time: bomb['timer'] -= 1 self.start_time = time() if bomb['timer'] <= 0: bomb_x = bomb['x'] bomb_y = bomb['y'] destroyed_tiles = [] minx = bomb_x - BOMB_RANGE if bomb_x - BOMB_RANGE >= 0 else 0 miny = bomb_y - BOMB_RANGE if bomb_y - BOMB_RANGE >= 0 else 0 maxx = bomb_x + BOMB_RANGE if bomb_x + BOMB_RANGE < self.MAP_WIDTH else self.MAP_WIDTH - 1 maxy = bomb_y + BOMB_RANGE if bomb_y + BOMB_RANGE < self.MAP_HEIGHT else self.MAP_HEIGHT - 1 # Ver que tiles se rompen for checked_x in range(minx, maxx): for checked_y in range(miny, maxy): if self.current_map[checked_x][checked_y]: if distance(bomb_x, bomb_y, checked_x, checked_y) <= BOMB_RANGE: destroyed_tiles.append( self.current_map[checked_x] [checked_y]) self.current_map[checked_x][ checked_y] = 0 if destroyed_tiles: self.map_changes.append(destroyed_tiles) # Ver si damos a algun jugador: try: if self.current_players is None: raise NoPlayersException current_players = self.current_players for k, v in current_players.items(): player_pos = estimate_current_position( v['position'], v['velocity'], (datetime.now() - datetime.strptime( v.get('serverTimeStamp', ''), DATE_FORMAT)).total_seconds()) if distance(bomb_x, bomb_y, player_pos['x'], player_pos['y']) <= BOMB_RANGE: v['health'] = 0 self.current_players = current_players except NoPlayersException: print("No current players") with bombs_lock: self.bombs = [bomb for bomb in self.bombs if bomb['timer'] > 0]
def Bifurcate(self): r = self.r[self.extr_type] _extrLs = [] if self.extr_type == Extreme.APICAL: if distance(self.sec.points[-1][:3], self.glomPos) != GLOM_RADIUS: pos = getP( distance(self.sec.points[-1][:3], self.glomPos) - GLOM_RADIUS, versor(self.glomPos, self.sec.points[-1][:3]), self.sec.points[-1][:3]) stretchSection(self.sec.points, pos) # orientation respect glomerulus gl_phi, gl_theta = Spherical.to(self.glomPos, self.sec.points[-1][:3])[1:] # make tuft TUFTS = int(r.discunif(self.cfg.N_MIN_TUFT, self.cfg.N_MAX_TUFT)) for i in range(TUFTS): sec = Section() sec.connect(self.nrn.apic[0]) self.nrn.tuft.append(sec) extr = Extreme() extr.sec = sec extr.phi, extr.theta = i * 2 * pi / TUFTS * ( 1 + 0.75 * r.uniform(-0.5 / TUFTS, 0.5 / TUFTS)), pi / 4 extr.basePhi, extr.baseTheta = self.basePhi, self.baseTheta extr.limit = r.uniform(self.cfg.TUFT_MIN_LEN, self.cfg.TUFT_MAX_LEN) extr.extr_type = Extreme.TUFT extr.glomPos = self.glomPos extr.cfg = self.cfg extr.r = self.r extr.nrn = self.nrn _extrLs.append(extr) elif self.extr_type == Extreme.DENDRITE: def get_phi(): phi = r.negexp(self.cfg.BIFURC_PHI_MU) while phi < self.cfg.BIFURC_PHI_MIN or phi > self.cfg.BIFURC_PHI_MAX: phi = r.repick() return phi for i in range(2): sec, extr = mkDendrite(self.cfg, self.r, self.nrn, self.depth + 1, self.sec) self.nrn.dend.append(sec) extr.phi = self.phi + ((-1)**i) * get_phi() extr.theta = self.theta extr.dist = self.dist extr.basePhi = self.basePhi extr.baseTheta = self.baseTheta _extrLs.append(extr) return _extrLs
def throw_rock(player, objects, cs, stdscr, m): width = len(m[1]) height = len(m) news.append("Where do you want to throw the rock?") display_news(stdscr, news, width, height) stdscr.addstr(player.y - 1,player.x, "^", curses.color_pair(1)), stdscr.addstr(player.y + 1,player.x, "v", curses.color_pair(1)) stdscr.addstr(player.y,player.x - 1, "<", curses.color_pair(1)) stdscr.addstr(player.y,player.x + 1, ">", curses.color_pair(1)) stdscr.refresh() inp = stdscr.getch() dx = 0 dy = 0 if inp == curses.KEY_DOWN: dy = 5 elif inp == curses.KEY_UP: dy = -5 elif inp == curses.KEY_LEFT: dx = -5 elif inp == curses.KEY_RIGHT: dx = 5 news.append("Yeet!") drop_first(lambda x: x.type == "rock", player.inv) rock = Object(player.x + dx, player.y + dy,".", 12, "rock") objects.append(rock) enemies = filter(lambda c: c.type != "player" and distance(c,rock) <= 10, cs) for e in enemies: e.target = (rock.x, rock.y) e.distracted = 3
def geodist(q, p): phiq, thetaq = p2e(q) phip, thetap = p2e(p) if phiq < phip: def swap(a, b): return b, a phip, phiq = swap(phip, phiq) thetap, thetaq = swap(thetap, thetaq) if phiq > phip and (phiq - phip) % (2 * pi) > pi: phiq = -(2 * pi - phiq) def pt(t): phi = (phiq - phip) * t + phip theta = (thetaq - thetap) * t + thetap return e2p(phi, theta) t = 0.0 dt = (1.0 / 360 * 2 * pi) / max([abs(phiq - phip), abs(thetaq - thetap)]) tot = 0.0 a = pt(0) seq = [a] while t < 1: t += dt b = pt(t) seq.append(b) tot += misc.distance(a, b) a = b return tot, seq
def drawsoma(): pts = self.mitral.soma.points center = misc.centroid(pts) # calc. soma radius radius = 0. for p in pts: radius += misc.distance(p, center) radius /= len(pts) radius *= cone_factor # versor u = tuple( misc.versor(self.mitral.apic.points[0], self.mitral.apic.points[1])) src = tvtk.ConeSource(center=tuple(center[0:3]), radius=radius, height=radius, direction=u, resolution=20) mapper = tvtk.PolyDataMapper(input=src.output) actor = tvtk.Actor(mapper=mapper) fig.scene.add_actor(actor) actor.property.color = self.soma_color return actor
def get_below(p): def get_nears(q): npt = [] for dx, dy, dz in moves: npt.append((q[0] + dx, q[1] + dy, q[2] + dz)) return npt def get_p(x, u): dim = params.grid_dim o = params.granule_origin q = () for i in range(3): q += (int(round((p[i] + x * u[i] - o[i]) / dim) * dim + o[i]), ) return q # scroll the line from points to the center u = misc.versor(params.bulbCenter, p) L = misc.distance(p, params.bulbCenter) dx = L / params.grid_dim nnpts = set() x = 0. while x <= L: q = get_p(x, u) if q not in nnpts: nnpts.update(get_nears(q)) x += dx return nnpts
def core_clusters(dynamic_clustering, pdb_file, dcd_pkl_filename): # dict of trajectory frames dynamic_clustering_frames_list = {} # dict of [cluster_no - frameids] for i in dynamic_clustering: try: dynamic_clustering_frames_list[dynamic_clustering[i]].append( int(i)) except: dynamic_clustering_frames_list[dynamic_clustering[i]] = [int(i)] frames = preprocessing.load_residues('reduced_dimensions.pkl') distances_of_frames_in_cluster = {} # this is distance-frameindex mapping avg_structure_in_cluster = {} # this is distance-frameindex mapping for i in dynamic_clustering_frames_list: #print i, "cluster_id" temp = misc.most_probable_structure_in_cluster( dynamic_clustering_frames_list[i], frames, pdb_file, i, "dynamic", dcd_pkl_filename) total_number_of_strucutres = len(dynamic_clustering_frames_list[i]) for j in range(total_number_of_strucutres): distances_of_frames_in_cluster[misc.distance( frames[dynamic_clustering_frames_list[i][j]], temp)] = dynamic_clustering_frames_list[i][j] distance_value = sorted(distances_of_frames_in_cluster.keys())[ (total_number_of_strucutres / 2) + 1] distances_of_frames_in_cluster[i] = distance_value avg_structure_in_cluster[i] = temp return distances_of_frames_in_cluster, avg_structure_in_cluster
def get_conntable_from_atoms(self, cart_coords, atom_types, atom_names, extra_param=0.16): """ returns a connectivity table from the atomic coordinates and the covalence radii of the atoms. TODO: - read FREE command from db to control binding here. :param cart_coords: cartesian coordinates of the atoms :type cart_coords: list :param atom_types: Atomic elements :type atom_types: list of strings :param atom_names: atom name in the file like C1 :type atom_names: list of strings """ names = [] for n, i in enumerate(atom_names, 1): names.append([n, i]) conlist = [] for co1, typ, n1 in zip(cart_coords, atom_types, names): for co2, typ2, n2 in zip(cart_coords, atom_types, names): if n1 == n2: continue ele1 = ELEMENTS[typ.capitalize()] ele2 = ELEMENTS[typ2.capitalize()] d = distance(co1[0], co1[1], co1[2], co2[0], co2[1], co2[2], round_out=5) # print(d, n1, n2, (ele1.covrad+ele2.covrad)+extra_param) # a bond is defined with less than the sum of the covalence # radii plus the extra_param: if d <= (ele1.covrad + ele2.covrad) + extra_param and d > (ele1.covrad or ele2.covrad): conlist.append([n2[1], n1[1]]) if [n1[1], n2[1]] in conlist: continue return (conlist)
def wiggle(self, root): """ Returns the closest point to this root that is an actual root. """ distance, knot = min( (misc.distance(root, knot), knot) for knot in self.knots ) #print >> sys.stderr, "Wiggling point %s to knot %s" % (repr(root), repr(knot)) return knot
def get_below(p): def get_nears(q): npt = [] for dx, dy, dz in moves: npt.append((q[0]+dx, q[1]+dy, q[2]+dz)) return npt def get_p(x, u): dim = params.grid_dim o = params.granule_origin q = () for i in range(3): q += (int(round((p[i] + x * u[i] - o[i])/dim)*dim+o[i]),) return q # scroll the line from points to the center u = misc.versor(params.bulbCenter, p) L = misc.distance(p, params.bulbCenter) dx = L / params.grid_dim nnpts = set() x = 0. while x <= L: q = get_p(x, u) if q not in nnpts: nnpts.update(get_nears(q)) x += dx return nnpts
def villager_sez(c, player): if distance(c, player) < 2 and c.has_talked == False: news.append("Villager sez: " + c.speek) if c.type == "wizardio": player.inv.append(choice(town_objects)) c.has_talked = True
def get_granules_below(p, glomid): bnd_up = misc.Ellipsoid(params.bulbCenter, params.granAxisUp) bnd_dw = misc.Ellipsoid(params.bulbCenter, params.granAxisDw) p_up = bnd_up.project(p) p_dw = bnd_dw.project(p) #params.glomRealCoords[glomid]) def get_neighbors(q): neighpt = [] for dx, dy, dz in _gran_voxel: neighpt.append((q[0] + dx, q[1] + dy, q[2] + dz)) return neighpt def get_p(x): d = params.gran_voxel return (int((p_dw[0] + x * (p_up[0] - p_dw[0])) / d) * d, int((p_dw[1] + x * (p_up[1] - p_dw[1])) / d) * d, int((p_dw[2] + x * (p_up[2] - p_dw[2])) / d) * d) pts = set() nmoves = 1 + int(misc.distance(p_up, p_dw) / params.gran_voxel) x = 0.0 while x < 1: pts.update(get_neighbors(get_p(x))) x += 1.0 / nmoves return pts
def __tricubic__(p1, p2, window): """ Weighs points close to eachother close to 1. Weighs points close to the window distance close to 0. Weighs points past the window distance to 0. """ z = misc.distance(p1,p2) weight = (1 - abs(z/float(window))**3)**3 return weight if abs(z) < window else 0.0
def axe_effect(player, creatures, m, objects, global_objects, screen, global_cs, self): junk = list(filter(lambda x: x.icon == "?", objects)) junk = map(lambda w: (w, misc.distance(w, player)), junk) junk = list(filter(lambda b: b[1] <= 1, junk)) if junk == []: destroy_wood(player, m) else: b = min(junk, key=lambda t: t[1])[0] objects.remove(b) global_objects.remove(b) globals.news.append("bash!") player.inventory.append(make_item("a piece of wood"))
def bias(): _phi, _theta = convert_direction(self.phi, self.theta, self.basePhi, self.baseTheta) p = Spherical.xyz(self.cfg.GRW_WALK_LEN, _phi, _theta, self.sec.points[-1][:3]) dglom = distance(p, self.glomPos) if dglom > GLOM_RADIUS * 0.9: _phi, _theta = Spherical.to( getP(dglom - GLOM_RADIUS * 0.9, versor(self.glomPos, p), p), self.sec.points[-1][:3])[1:] self.phi, self.theta = convert_direction( _phi, _theta, self.basePhi, self.baseTheta, True)
def gobbo_attack(gobbo, player, m): # Make gobbo stand in place for a few turns after it hits you if gobbo.did_attack == True: if randint(1, 4) == 1: gobbo.did_attack = False return if distance(gobbo, player) <= 1.0: if not player_has_shield(player): player.health -= 1 news.append("Oof! You got attacked!") gobbo.did_attack = True else: drop_first(lambda o: o.type == "shield", player.inv)
def make_13_dist(self, nn): """ return 1,3-distance as [('at1', 'at2', 'distance'), ('at1', 'at2', 'distance'), ...] needs next neighbors pairs """ dist_13 = [] for i in nn: atom1 = i[0] atom2 = i[1] c1 = self.coords_dict[atom1] c2 = self.coords_dict[atom2] dist_13.append((atom1, atom2, distance(c1[0], c1[1], c1[2], c2[0], c2[1], c2[2]))) return dist_13
def compute_length(self): """compute distance, save to self.length and return""" self.validate() length = 0.0 cities = self.world.cities for route in self.routes: prev_city = route[0] for city in route[1:]: length += distance(cities[city], cities[prev_city]) prev_city = city self.length = length return length
def fill_soma(sections, elements, cellid): points = [] for sec in sections: points += sec.points center = misc.centroid(points)[:3] radius = 0.0 for p in sec.points: radius += misc.distance(p[:3], center) radius /= len(points) verse = misc.versor(bulbdef.bulb_center, center) o = Soma(center, radius, verse) o.gids.append(cellid) elements.objs.append(o)
def adjmatrix(self): """ create a distance matrix for the atom coordinates """ import networkx as nx G = nx.Graph() for i in self._connectivity_table: atom1 = i[0] atom2 = i[1] if atom1 in self._atoms: coord1 = self.coords_dict[atom1] coord2 = self.coords_dict[atom2] dist = distance(coord1[0], coord1[1], coord1[2], coord2[0], coord2[1], coord2[2]) G.add_edge(atom1, atom2, weight=dist) return G
def distance_to(self, param_num, config, value): # i'm going to cheat for now and just pick the closest intersecting corner ints = self.intersections(param_num, value) #print 'simplexes', self.simplexes #print 'ints', ints #raw_input() dists = [] for simplex in ints: for i in simplex: dists.append( (misc.distance(i, config)) ) if len(dists) == 0: #print >> sys.stderr, "BADNESS: no intersections found for %s" % repr(value) dist = None else: dist = min(dists) return dist
def drawsoma(): pts = self.mitral.soma.points center = misc.centroid(pts) # calc. soma radius radius = 0. for p in pts: radius += misc.distance(p, center) radius /= len(pts) radius *= cone_factor # versor u = tuple(misc.versor(self.mitral.apic.points[0], self.mitral.apic.points[1])) src = tvtk.ConeSource(center=tuple(center[0:3]), radius=radius, height=radius, direction=u, resolution=20) mapper = tvtk.PolyDataMapper(input=src.output) actor = tvtk.Actor(mapper=mapper) fig.scene.add_actor(actor) actor.property.color = self.soma_color return actor
def granule_voxels(p1, p2): u = misc.versor(p2, p1) def nears(q): nn = [] for dx, dy, dz in moves: nn.append((q[0] + dx, q[1] + dy, q[2] + dz)) return nn def pt(x): p = ( p1[0] + x * u[0], p1[1] + x * u[1], p1[2] + x * u[2]) p = ( int(round((p[0] - params.granule_origin[0]) / params.grid_dim)) * params.grid_dim + params.granule_origin[0], \ int(round((p[1] - params.granule_origin[1]) / params.grid_dim)) * params.grid_dim + params.granule_origin[1], \ int(round((p[2] - params.granule_origin[2]) / params.grid_dim)) * params.grid_dim + params.granule_origin[2]) return p L = misc.distance(p1, p2) dx = L / params.grid_dim visited = set() x = 0. while x <= L: visited.add(pt(x)) x += dx nnpts = set() # near points for q in visited: nnpts.update(nears(q)) # return ggids ggids = set() for q in nnpts: if pos2gid.has_key(q): ggids.add(pos2gid[q]) return list(ggids)
def granule_voxels(p1, p2): u = misc.versor(p2, p1) def nears(q): nn = [] for dx, dy, dz in moves: nn.append((q[0] + dx, q[1] + dy, q[2] + dz)) return nn def pt(x): p = (p1[0] + x * u[0], p1[1] + x * u[1], p1[2] + x * u[2]) p = ( int(round((p[0] - params.granule_origin[0]) / params.grid_dim)) * params.grid_dim + params.granule_origin[0], \ int(round((p[1] - params.granule_origin[1]) / params.grid_dim)) * params.grid_dim + params.granule_origin[1], \ int(round((p[2] - params.granule_origin[2]) / params.grid_dim)) * params.grid_dim + params.granule_origin[2]) return p L = misc.distance(p1, p2) dx = L / params.grid_dim visited = set() x = 0. while x <= L: visited.add(pt(x)) x += dx nnpts = set() # near points for q in visited: nnpts.update(nears(q)) # return ggids ggids = set() for q in nnpts: if pos2gid.has_key(q): ggids.add(pos2gid[q]) return list(ggids)
def granule_priden_length(ggid): from granules import granule_position_orientation as gpo from misc import distance psoma, u, proj = gpo(ggid) return distance(psoma, proj)
self.__readsections(cell.soma) self.__readsections(cell.apic) self.__readsections(cell.tuft) self.__readsections(cell.dend) self.__connect(cell) return cell if __name__ == '__main__': cr = CellReader('../bulbvis/mccells.car') hist = [0] * int(1040 / 40) import misc for i in range(635, 1904): try: cell = cr.readcell(i) center = misc.centroid(cell.soma[0].points) for dnd in cell.dend: for p in dnd.points: d = misc.distance(p, center) hist[int(d / 40)] += 1. except: break s = 0. for x in hist: s += x for i in range(len(hist)): hist[i] /= s with open('../sholl.txt', 'w') as fo: for i in range(len(hist)): fo.write('%d %g\n' % (i * 40, hist[i]))
def __update(self, p): d = distance(p, self.sec.points[-1][:3]) self.dist += d self.bif_dist += d self.sec.points.append(p)
def distance(self, another_place): return distance(self, another_place)
def __find_knn__(self, configuration): distances = [ (misc.distance(configuration, entry[0]), idx) for idx, entry in enumerate(self.__data__) ] distances.sort() return tuple( self.__data__[idx] for distance, idx in distances[:self.k] )
def dynamic_cluster_trajectory(meta_stability_criteria = 0.9, pdb_file = "", dcd_pkl_filename = ""): model = joblib.load("KMEANS.pkl") X = preprocessing.load_residues('reduced_dimensions.pkl') #print X.shape mean_cluster_ids = shelve.open("kmeans_trajectory_clustering") # this structure stores cluster-ids for each frame of the trajectory if (len(mean_cluster_ids) == 0): for i in range(X.shape[0]): prediction = model.predict(X[i].reshape((1, -1))) mean_cluster_ids[str(i)] = int(prediction) #print "yo" number_of_current_clusters = model.cluster_centers_.shape[0] d = dict(mean_cluster_ids) mean_cluster_ids.close() while (True): cluster_membership = {} #print number_of_current_clusters, "--" for i in range(X.shape[0]): try: cluster_membership[int(d[str(i)])] += 1 except: cluster_membership[int(d[str(i)])] = 1 transition_matrix = ds.Autovivification() for i in set(d.values()): for j in set(d.values()): transition_matrix[i][j] = 0 for i in range(X.shape[0] - 1): transition_matrix[int(d[str(i)])][int(d[str(i + 1)])] += 1 # normalizing values row-wise cluster_probability = {} for i in set(d.values()): sums = 0 for j in set(d.values()): sums += transition_matrix[i][j] cluster_probability[i] = sums for j in set(d.values()): transition_matrix[i][j] /= sums * 1.0 dynamic_clusters = ds.disjoint(set(d.values())) visited = {} for i in set(d.values()): temp_visited = dfs_markov(i, set(d.values()), transition_matrix, dynamic_clusters, visited, meta_stability_criteria) visited = copy.deepcopy(temp_visited) dynamic_clusters.compress() dynamic_clusters.save_structure() cluster_ids = dynamic_clusters.get_clusters(cluster_probability) new_clusters = cluster_ids.values() #print len(set(new_clusters)) if number_of_current_clusters == len(set(new_clusters)): # applying cluster core correction distances_of_frames_in_cluster, avg_structure_in_cluster = core_clusters(d, pdb_file, dcd_pkl_filename) #print len(set(d.values())), "original" X = preprocessing.load_residues('reduced_dimensions.pkl') d_new = {} d_new["0"] = d["0"] for index in range(1, len(X)): dist = misc.distance(X[index], avg_structure_in_cluster[d[str(index)]]) if dist > distances_of_frames_in_cluster[d[str(index)]]: d_new[str(index)] = d_new[str(index - 1)] else: d_new[str(index)] = d[str(index)] d = d_new dynamic_clustering = shelve.open("dynamic_clustering") dynamic_clustering.clear() for i in d: dynamic_clustering[i] = d[i] dynamic_clustering.close() #print len(set(d.values())), "original" sequence = get_most_probable_path(d) #print len(sequence) #print sequence return sequence, transition_matrix else: #print set(new_clusters) number_of_current_clusters = len(set(new_clusters)) d_new = {} for i in range(X.shape[0]): d_new[str(i)] = cluster_ids[int(d[str(i)])] d = d_new dynamic_clustering = shelve.open("dynamic_clustering") dynamic_clustering.clear() for i in d: dynamic_clustering[i] = d[i] dynamic_clustering.close() return