def Provisional(self,N,provis,unknowns): j=0 finalX=Points('New Provisional Points') orientations={} for i in unknowns: name= i[0:-2] variable = i[-1] if variable=="o": orientations[name]= float64(N[j]) j+=1 continue x=provis[name].x y=provis[name].y h=provis[name].h if not finalX.has_key(name): finalX[name]= Point(0,0,0,False,name) if variable=="x": finalX[name].ChangeVariable(variable,float64(x+N[j])) j+=1 continue if variable=="y": finalX[name].ChangeVariable(variable,float64(y+N[j])) j+=1 continue if variable=="h": finalX[name].ChangeVariable(variable,float64(h+N[j])) j+=1 continue return finalX
def new(self, pos, which): if len(self) >= 3 or len(self.pts) > 0: return Points.new(self, pos) if len(self) < 3: return corners = [] for p in self: corners.append(np.array((p[0], p[1], p[2]))) del self[:] corners.append(corners[2] + corners[0] - corners[1]) dx = (corners[1] - corners[0]) / (self.size[0] * 3) dy = (corners[3] - corners[0]) / (self.size[1] * 3) del self.pts[:] for y in range(self.size[1] * 3 + 1): for x in range(self.size[0] * 3 + 1): pt = corners[0] + dx * x + dy * y self.pts.append(pt) self.generate() self.get_geom().set_visibility(Bezier.CURVE, True)
def __init__(self, data, pts_vis=True, curve_vis=True, polygon_vis=False, pts=None): self.dv = np.zeros(3) self.size = data[0] self.dens = data[1] gm = Surface() self.pts = [] if pts == None else pts Points.__init__(self, gm) gm.set_visibility(Bezier.POINTS, pts_vis) gm.set_visibility(Bezier.CURVE, False) gm.set_visibility(Bezier.POLYGON, False) self.calc_size() self.allocate() self.set_data((self.pts, self.bezy)) if self.pts != []: self.generate() self.get_geom().set_visibility(Bezier.CURVE, True)
def new( self , pos , which ) : if len(self) >= 3 or len(self.pts) > 0 : return Points.new( self , pos ) if len(self) < 3 : return corners = [] for p in self : corners.append( np.array(( p[0] , p[1] , p[2] )) ) del self[:] corners.append( corners[2] + corners[0] - corners[1] ) dx = (corners[1] - corners[0]) / (self.size[0]*3) dy = (corners[3] - corners[0]) / (self.size[1]*3) del self.pts[:] for y in range(self.size[1]*3+1) : for x in range(self.size[0]*3+1): pt = corners[0] + dx * x + dy * y self.pts.append( pt ) self.generate() self.get_geom().set_visibility( Bezier.CURVE , True )
def Provisional(self, N, provis, unknowns): j = 0 finalX = Points('New Provisional Points') orientations = {} for i in unknowns: name = i[0:-2] variable = i[-1] if variable == "o": orientations[name] = float64(N[j]) j += 1 continue x = provis[name].x y = provis[name].y h = provis[name].h if not finalX.has_key(name): finalX[name] = Point(0, 0, 0, False, name) if variable == "x": finalX[name].ChangeVariable(variable, float64(x + N[j])) j += 1 continue if variable == "y": finalX[name].ChangeVariable(variable, float64(y + N[j])) j += 1 continue if variable == "h": finalX[name].ChangeVariable(variable, float64(h + N[j])) j += 1 continue return finalX
def split(quadrilateral, count_in_row, count_in_col): ''' Quadrilateral.split Split to many samll ones. ''' vertices = Quadrilateral.vertices(quadrilateral) the_points = Points.cal_internal_points(vertices, count_in_col+1, count_in_row+1) return Points.get_quadrilaterals(the_points, count_in_col, count_in_row)
def __init__(self, root_path, scale): # GPS trajectory points self.points = Points() # dataset root path self.root_path = root_path # dataset directories self.directories = os.listdir(root_path) # dataset scale self.scale = scale
def __init__( self , pts_vis = True , curve_vis = True , polygon_vis = False ) : b = Bezier() Points.__init__( self , b ) b.set_visibility( Bezier.POINTS , pts_vis ) b.set_visibility( Bezier.CURVE , curve_vis ) b.set_visibility( Bezier.POLYGON , polygon_vis ) self.set_data( self )
def __init__(self, parameters): """Assign some initial values and parameters --- Arguments --- parameters (dict): key: x, y, nl, K, length_limit, h, t_max, e, debug_mode See details for each values in Points's documentation. """ if type(parameters) != dict: raise TypeError("params should be dictionary") self.__dict__ = parameters self.t = 0. # debugging if self.debug_mode: log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG) else: log.basicConfig(format="%(levelname)s: %(message)s") self.point = Points(N=len(self.x), position_x=self.x, position_y=self.y, natural_length=self.nl, K=self.K, length_limit=self.length_limit) # 成長率の決定 # 累積的に成長する場合 # self.grow_func = lambda arr: arr * 1.01 # 一定の成長率で成長する場合 # self.grow_func = lambda arr: arr + 0.00025 self.grow_func = lambda arr: arr + 0.001 # 乱数を含める # import random # def glow_randomly(arr): # D = np.array([0.0005 + 0.001 * random.random() # for i in range(self.point.N)]) # return arr + D # self.grow_func = glow_randomly def grow_func_k(arr, old_nl, new_nl): return arr * old_nl / new_nl self.grow_func_k = grow_func_k self.fig, self.ax = plt.subplots() self.l, = self.ax.plot(np.array([]), np.array([]), 'bo-') self.ax.set_xlim([-30., 30.]) self.ax.set_ylim([-30., 30.]) # toggle pause/resume by clicking the matplotlib canvas region self.pause = False
def new( self , pos , which ) : if len(self) >= self.gapsize or len(self.pts) > 0 : return Points.new( self , pos ) if len(self) < self.gapsize : return corners = [] for p in self : corners.append( np.array(( p[0] , p[1] , p[2] ),np.float32) ) del self[:] self.make_pts( corners )
def draw( self ) : Points.draw( self ) for s in self.surfs : s.draw() if self._subsurfs != None and self._fill_gap != None : glDepthFunc(GL_NEVER) for i in range(self.base_surfs) : glBegin(GL_POINTS) for j in range(16) : glColor3f(0,(j+1.0)/16.0,0) glVertex3f(*self._subsurfs[i][j]) glEnd() glColor3f(1,1,1) glDepthFunc(GL_LEQUAL)
def __init__(self, data, pts_vis=True, curve_vis=True, polygon_vis=False, pts=None): self.dv = np.zeros(3) self.size = data[0] self.dens = data[1] gm = SurfaceTrimmed() self.pts = pts if pts != None else [] Points.__init__(self, gm) gm.set_visibility(Bezier.POINTS, pts_vis) gm.set_visibility(Bezier.CURVE, False) gm.set_visibility(Bezier.POLYGON, False) # trimming data self.trimm_curr = None self.reset_trimms() self.bezy = None self.calc_size() self.allocate() self.gen_ind() self.set_data((self.pts, self.bezy, self.addpts)) i = 0 self.base = [] for t in np.linspace(3, 4, 256 / 4 + 1): for j in range(4): i += 1 self.base.append(rekN(3, j, t)) self.base = np.array(self.base, np.float32) if self.pts != []: self.generate() self.get_geom().set_visibility(Bezier.CURVE, True) # debug data self.trim_p0 = None self.trimming_curve = None
def __init__(self, min_year, max_year): self.min_year = min_year self.max_year = max_year self.max_rank = 60 self.topn = 10 self.path = '../data' self.file_prefix = 'rushing_' self.df = pd.DataFrame() self.to_int_vars = [ 'Year', 'RK', 'ATT', 'YDS', 'LONG', '20+', 'TD', 'FUM', '1D' ] self.to_flt_vars = ['YDS/G', 'YDS/A'] self.funcs = Methods() self.points = Points() self.feature_vector = [ u'RK', u'is_runner', u'games_played', u'n_years', u'td_per_game', u'att_per_game', u'r_yards_game', u'r_20p_game', u'r_fum_game', u'r_yds_att', u'log_long', u'r_1d_game', u'avg_career_rank', u'previous_rank1_clean', u'previous_rank2_clean', u'previous_rank3_clean', u'previous_rank4_clean', u'previous_rank5_clean', u'lst_rank_delta', u'r_td_rec', u'log_yards' ] self.dep_var = [ u'y_future_rank', u'y_top5', 'y_sqrt_future_rank', 'y_future_points', 'y_sqr_future_points' ]
def __init__(self, game, point_config='STD_CONFIG', uid=1, max_turns=3): self.game = game self.id = uid self.turn = 0 self.points = Points(config=point_config) self.dice = Dice() self.max_turns = max_turns
def __init__(self, filename=None): if filename != None: dump = self._get_from_file(filename) self._points, self._edges, self._routes = dump['points'], dump['edges'], dump['routes'] return self._points, self._edges = Points('points_dump_with_neighbors').get_points_edges() self._calculate_routes()
def draw_points(): """ The function draw all points and their radius for better find on board. """ goal_points_idx = [(1, 4), (1, 5), (1, 6), (12, 4), (12, 5), (12, 6)] #Points in gates cnt = 0 for i in range(1, boardwidth + 2): for z in range(1, boardheight + 2): if (z, i) in point_for_skip: continue if cnt % 2 == 0: point_radius = pygame.draw.circle(DISPLAYSURF, FOREST, (size * i, size * z), 15) point_p = pygame.draw.circle(DISPLAYSURF, WHITE, (size * i, size * z), 4) else: point_radius = pygame.draw.circle(DISPLAYSURF, FOREST, (size * i, size * z), 15) point_p = pygame.draw.circle(DISPLAYSURF, WHITE, (size * i, size * z), 4) x = (size * i, size * z) if (z, i) in goal_points_idx: if goal_points_idx.index((z, i)) in [0, 1, 2]: POINTS_pos.append( Points(cords=x, point_pos=point_p, pointradius=point_radius, p1_goal=True) ) #Points for upper gate (Player2-gate) else: POINTS_pos.append( Points(cords=x, point_pos=point_p, pointradius=point_radius, p2_goal=True) ) #Points for bottom gate (Player1-gate) else: POINTS_pos.append( Points(cords=x, point_pos=point_p, pointradius=point_radius)) cnt += 1 cnt -= 1
def __init__(self, params=secp256k1): self.a = params[0] self.b = params[1] self.p = params[2] if (len(params) >= 5): self.g = Points(params[3][0], params[3][1], self) if (len(params) >= 5): self.n = params[4]
def __init__( self , data , pts_vis = True , curve_vis = True , polygon_vis = False , pts = None ) : self.dv = np.zeros(3) self.size = data[0] self.dens = data[1] gm = SurfaceTrimmed() self.pts = pts if pts != None else [] Points.__init__( self , gm ) gm.set_visibility( Bezier.POINTS , pts_vis ) gm.set_visibility( Bezier.CURVE , False ) gm.set_visibility( Bezier.POLYGON , False ) # trimming data self.trimm_curr = None self.reset_trimms() self.bezy = None self.calc_size() self.allocate() self.gen_ind() self.set_data( (self.pts,self.bezy,self.addpts) ) i=0 self.base = [] for t in np.linspace(3,4,256/4+1) : for j in range(4) : i+=1 self.base.append( rekN( 3 , j , t ) ) self.base = np.array( self.base , np.float32 ) if self.pts != [] : self.generate() self.get_geom().set_visibility( Bezier.CURVE , True ) # debug data self.trim_p0 = None self.trimming_curve = None
def new( self , pos , which ) : if len(self) >= 3 or len(self.pts) > 0 : return Points.new( self , pos ) if len(self) < 3 : return corners = [] for p in self : corners.append( np.array(( p[0] , p[1] , p[2] )) ) del self[:] corners.append( corners[2] + corners[0] - corners[1] ) self.make_pts( corners ) self.generate() self.get_geom().set_visibility( Bezier.CURVE , True )
def new(self, pos, which): if len(self) >= 3 or len(self.pts) > 0: return Points.new(self, pos) if len(self) < 3: return corners = [] for p in self: corners.append(np.array((p[0], p[1], p[2]))) del self[:] corners.append(corners[2] + corners[0] - corners[1]) self.make_pts(corners) self.generate() self.get_geom().set_visibility(Bezier.CURVE, True)
def __init__( self , data , pts_vis = True , curve_vis = True , polygon_vis = False ) : self.dens = data[1] self.gapsize = max(data[0][0],3) gm = Surface() Points.__init__( self , gm ) gm.set_visibility( Bezier.POINTS , pts_vis ) gm.set_visibility( Bezier.CURVE , False ) gm.set_visibility( Bezier.POLYGON , False ) self.pts = [] self.surfs = [] self.corners = [] self.set_data( (self,None) ) self.base_surfs = 0 self._fill_gap = None
def get_points(): matrix = [[[0, 0, 0], [0, 0, 0], [0, 0, 1]], [[0, 1 / 2, 0], [1 / 2, 0, 0], [0, 0, 0]], [[0, 0, 1 / 2], [0, 0, 0], [1 / 2, 0, 0]]] matrix2 = [[[0, 0, 0, 0, 1], [0, 0, 0, 1, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0]], [[0, 0, 0, 0, complex(0, -1)], [0, 0, 0, complex(0, -1), 0], [0, 0, complex(0, 1), 0, 0], [0, complex(0, 1), 0, 0, 0], [complex(0, 1), 0, 0, 0, 0]], [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, -1, 0], [0, 0, 0, 0, -1]]] points = Points(matrix, 3) generated_points = points.get_joint_numerical_range(1500) # qwe.qwe(generated_points) # qwe.qwe(helper.get_fibonacci_sphere_as_vectors(500)) return Response(dumps(generated_points), mimetype='text/json')
def getL(self, provis, obs, control): # print "=================================================================================" # print "====== Calculate Misclosure L ===========================================" count = obsCount(obs) L = numpy.zeros(shape=(count, 1)) Lnames = Points("L vector name pairs") i = 0 for sn1, station in obs.iteritems(): for tn1, target in station.iteritems(): tn2 = tn1 tn1 = tn1[0:-2] if target.type == "direction": if control.has_key(tn1): if provis.has_key(sn1): calc = provis[sn1].join(control[tn1]) elif control.has_key(sn1): calc = control[sn1].join(control[tn1]) elif provis.has_key(tn1): if provis.has_key(sn1): calc = provis[sn1].join(provis[tn1]) elif control.has_key(sn1): calc = control[sn1].join(provis[tn1]) else: print "error" calc = 0 observed = obs[sn1][tn2].direction target.setMisclosure(observed - calc) L[i][0] = (observed - calc) Lnames[sn1 + " to " + tn1 + " direc"] = L[i][0] i += 1 # continue elif target.type == "distance": if control.has_key(tn1): if provis.has_key(sn1): calc = provis[sn1].joinS(control[tn1]) elif control.has_key(sn1): calc = control[sn1].joinS(control[tn1]) elif provis.has_key(tn1): if provis.has_key(sn1): calc = provis[sn1].joinS(provis[tn1]) elif control.has_key(sn1): calc = control[sn1].joinS(provis[tn1]) else: print "error" observed = obs[sn1][tn2].distance target.setMisclosure(observed - calc) L[i][0] = round((observed - calc), 3) Lnames[sn1 + " to " + tn1 + " distance"] = L[i][0] i += 1 return L
def __init__( self ) : self.bz = Bezier() Points.__init__( self , self.bz ) self.bz.set_visibility( Curve.POINTS , False ) self.bz.set_visibility( Curve.CURVE , True ) self.bz.set_visibility( Curve.POLYGON , False ) self.bezier = [] self.powerx = [] self.powery = [] self.powerz = [] self.ptsx = [] self.ptsy = [] self.ptsz = [] self.set_data( self.bezier ) self.pow2bern()
def __init__(self, bzpts, bzcur, bzpol, bspts, bscur, bspol): self.bz = Bezier() self.bs = Bspline() Points.__init__(self, MultiGeom((self.bz, self.bs))) self.bezier_points = bzpts self.bspline_points = bspts self.bz.set_visibility(Curve.POINTS, bzpts) self.bz.set_visibility(Curve.CURVE, bzcur) self.bz.set_visibility(Curve.POLYGON, bzpol) self.bs.set_visibility(Curve.POINTS, bspts) self.bs.set_visibility(Curve.CURVE, bscur) self.bs.set_visibility(Curve.POLYGON, bspol) self.bezier = [] self.deboor = [] self.state = None self.set_data((self.bezier, self.deboor))
def main(planet): seed(planet) p = [] # equator for i in range(resolution): lat = i / resolution * pi - pi / 2 dots = int(cos(lat) * resolution) # reduce res around poles if dots < 1: continue for j in range(dots): long = j / dots * 2 * pi p.append(((long, lat), Color(rr(), rg(), rb()))) return Points(p)
def enlarge(quadrilateral, percent=0.05): ''' Quadrilateral.enlarge ''' x, y, width, height = cv2.boundingRect(quadrilateral) x_step = int(width * percent) y_step = int(height * percent) top_left, bottom_left, bottom_right, top_right = \ Quadrilateral.vertices(quadrilateral) top_left=(top_left[0]-x_step, top_left[1]-y_step) top_right=(top_right[0]+x_step, top_right[1]-y_step) bottom_right=(bottom_right[0]+x_step, bottom_right[1]+y_step) bottom_left=(bottom_left[0]-x_step, bottom_left[1]+y_step) return Points.to_contour((top_left, top_right, bottom_right, bottom_left))
def main(planet: Planet) -> list: seed(planet) p = [] # equator ratio = randint(1, 5), randint(1, 5) # water % must be >20% for water cycle for i in range(resolution): lat = i / resolution * pi - pi / 2 dots = int(cos(lat) * resolution) # reduce res around poles if dots < 1: continue for j in range(dots): long = j / dots * 2 * pi p.append(((long, lat), t2c(planet, ratio))) return Points(p)
def __init__( self , data , pts_vis = True , curve_vis = True , polygon_vis = False , pts = None ) : self.dv = np.zeros(3) self.size = data[0] self.dens = data[1] gm = Surface() self.pts = [] if pts == None else pts Points.__init__( self , gm ) gm.set_visibility( Bezier.POINTS , pts_vis ) gm.set_visibility( Bezier.CURVE , False ) gm.set_visibility( Bezier.POLYGON , False ) self.calc_size() self.allocate() self.set_data( (self.pts,self.bezy) ) if self.pts != [] : self.generate() self.get_geom().set_visibility( Bezier.CURVE , True )
def __init__(self, min_year, max_year): self.min_year=min_year self.max_year=max_year self.max_rank=60 self.topn = 5 self.path='../data' self.file_prefix='passing_' self.df = pd.DataFrame() self.to_int_vars = ['RK', 'COMP', 'ATT', 'YDS', 'LONG', 'TD', 'INT', 'SACK'] self.to_flt_vars = ['YDS/G', 'AVG', 'RATE', 'PCT'] self.funcs=Methods() self.points=Points() self.feature_vector=[u'RK', u'is_qb', u'games_played', u'n_years', u'td_per_game', u'comp_per_game', u'int_per_game', u'sack_per_game', u'log_yards', u'r_att_comp', u'r_yards_game', u'r_att_game', u'percent_comp', u'avg_career_rank', u'previous_rank1_clean', u'previous_rank2_clean', u'previous_rank3_clean', u'previous_rank4_clean', u'previous_rank5_clean', u'lst_rank_delta'] self.dep_var=[u'y_future_rank', u'y_top5', 'y_sqrt_future_rank', 'y_future_points', 'y_sqr_future_points']
def generate_example(self): # load training weights model = load_model(self.args.weights) # создаем экземпляр игры game = Points(self.args.field_width, self.args.field_height) game.reset(random_crosses=self.args.random_crosses) mcts = MCTSRootParallelizer(model, self.args.simulations, self.args.parallel, c_puct=1.2) positions = [] # game loop while not game.is_ended: mcts.search(game) policy = mcts.get_dirichlet_policy( game ) # all actions' probabilities (not possible actions with 0 probability) # print('policy', policy) a = int(np.random.choice(len(policy), p=policy)) # field, policy, value # don't have reward for now positions.append((game.points, game.owners, policy, game.player)) game.auto_turn(a) # do action # close mcts processes mcts.exit.set() v = np.int8(last_turn_player_reward(game)) # insert game reward to examples # for the last turned player reward = v for another reward = -v example = [] for position_index in range(len(positions) - 1, -1, -1): points, owners, policy, player = positions[position_index] example += symmetries(points, owners, player, policy, v) v = -v # TODO grounding support for policy example = np.array(example, dtype=[('field', '?', (game.width, game.height, 4)), ('policy', 'f8', (game.field_size, )), ('value', 'i1')]) return game, example
def main(): pygame.init() g_set = Settings() stats = Stats(g_set) screen = pygame.display.set_mode((g_set.width, g_set.height)) points = Points(g_set, screen, stats) pygame.display.set_caption(g_set.title) s_ship = Ship(screen) shoots = Group() ufos = Group() play_but = Button(g_set, screen, "Play") gf.ufo_fleet(g_set, screen, ufos, s_ship) while 1: gf.check_event(s_ship, g_set, screen, shoots, stats, play_but, ufos, points) if stats.game_on: s_ship.update(g_set) gf.update_shoot(shoots, ufos, g_set, screen, s_ship, points, stats) gf.update_ufo(g_set, ufos, s_ship, stats, screen, shoots, points) gf.update_screen(screen, g_set, s_ship, shoots, ufos, play_but, stats, points)
class Player(object): def __init__(self, game, point_config='STD_CONFIG', uid=1, max_turns=3): self.game = game self.id = uid self.turn = 0 self.points = Points(config=point_config) self.dice = Dice() self.max_turns = max_turns def save_dice(self, values): self.dice.save(values) def entry_points(self, field, column, values, preview=False): score = self.points.entry(field, column, values, self.game, preview=preview) if not preview: self.game.next_player() self.turn = 0 if all([all([i[1] for i in column.points.values()]) for column in self.points.columns]): raise PlayerFinishedException() return score def roll_dice(self): if self.turn >= self.max_turns: raise NoTurnsLeftException() self.dice.roll() self.turn += 1 def delete(self): if self.game.active_player == self: self.game.next_player() del self.game.players[self.game.players.index(self)] @classmethod def generate_players(cls, game, count, point_config): return [cls(game, point_config=point_config, uid=i) for i in range(1, count+1)]
def match(self): # load candidate and best network weights candidate_model = load_model(self.args.candidate_weights) best_model = load_model(self.args.best_weights) # определяем, кто ходит первым if self.args.candidate_turns_first: first_model, second_model = candidate_model, best_model else: first_model, second_model = best_model, candidate_model # setup MCTS for both nets first_mcts = MCTSRootParallelizer(first_model, self.args.simulations, self.args.parallel) second_mcts = MCTSRootParallelizer(second_model, self.args.simulations, self.args.parallel) MCTSs = [first_mcts, second_mcts] game = Points(self.args.field_width, self.args.field_height) game.reset() # match neural networks while not game.is_ended: cur_mcts = MCTSs[game.player] cur_mcts.search(game) pi = cur_mcts.get_dirichlet_policy(game) # best action a = int(np.argmax(pi)) game.auto_turn(a) first_mcts.exit.set() second_mcts.exit.set() return game
def delete( self , pos , dist = .05 ) : Points.delete( self , pos ,dist ) self.update_matrix() self.update_polynomianls()
def move_current( self , v ) : Points.move_current( self , v ) self.update_polynomianls()
def new( self , pos , data = None ) : Points.new( self , pos , data ) self.update_matrix() self.update_polynomianls()
class Routes: ''' Routes class acts as controller and collector for points and edges. It gets all the points and edges and convert them into usable form. Methods: get_routes: invokes with no parameters and returns a list of Route class instances. ''' _edges = dict() _routes = dict() _points = list() def __init__(self, filename=None): if filename != None: dump = self._get_from_file(filename) self._points, self._edges, self._routes = dump['points'], dump['edges'], dump['routes'] return self._points, self._edges = Points('points_dump_with_neighbors').get_points_edges() self._calculate_routes() @timed def _get_from_file(self, filename): return pickle.load(open(filename,'rb')) def save_to_file(self, filename='dump_routes'): sys.setrecursionlimit(1000000) pickle.dump(self._routes, open(filename, 'wb')) def _add_route(self, waypoints, id): edge = self._edges[id] route = Route(waypoints,edge) self._routes[id] = route def split_edges(self, new_point, points_arr): for item in points_arr: old_point = item route = self._routes[old_point.edge_id] result = route.split_edge(old_point=old_point, new_point=new_point) if result['changed']: self._edges[old_point.edge_id] = result[1]['edge'] self._routes[old_point.edge_id] = result[1]['route'] self._edges[result[1]['edge'].edge_id] = result[1]['edge'] self._edges[result[2]['edge'].edge_id] = result[2]['edge'] self._routes[result[1]['edge'].edge_id] = result[1]['route'] self._routes[result[2]['edge'].edge_id] = result[2]['route'] else: self._routes[result['edge'].edge_id] = result['route'] if old_point is not new_point: self._points[self._points.index(old_point)] = self._points[self._points.index(new_point)] def fix_intersection(self,segment1, segment2): # validating intersection classes, fix not work now! # if segment1[1].edge_id != segment1[0].edge_id: # return False # if segment2[1].edge_id == segment2[0].edge_id: # return False intersection_point = segment_intersection(segment1, segment2) new_point = CalculatedPoint(intersection_point[0], intersection_point[1], segment1[0].hierarchy) route1 = self._routes[segment1[0].edge_id] route2 = self._routes[segment2[1].edge_id] result1 = route1.split_edge_by_new_point(segment1, new_point) result2 = route2.split_edge_by_new_point(segment2, new_point) if result1: self._edges.pop(segment1[0].edge_id, None) self._routes.pop(segment1[0].edge_id, None) self._edges[result1[1]['edge'].edge_id] = result1[1]['edge'] self._edges[result1[2]['edge'].edge_id] = result1[2]['edge'] self._routes[result1[1]['edge'].edge_id] = result1[1]['route'] self._routes[result1[2]['edge'].edge_id] = result1[2]['route'] if result2: self._edges.pop(segment2[0].edge_id, None) self._routes.pop(segment2[0].edge_id, None) self._edges[result2[1]['edge'].edge_id] = result2[1]['edge'] self._edges[result2[2]['edge'].edge_id] = result2[2]['edge'] self._routes[result2[1]['edge'].edge_id] = result2[1]['route'] self._routes[result2[2]['edge'].edge_id] = result2[2]['route'] def check_one_by_one_order_in_path(self, point_start, point_end): if point_start.edge_id != point_end.edge_id: return False route = self._routes[point_start.edge_id] result = route.check_one_by_one_order(point_start, point_end) return result def check_points_accessability(self, point_start, point_end): if point_end in point_start.from_me: return True elif point_start in point_end.from_me: return True else: return False @timed def _calculate_routes(self): edge_id = 1 waypoints = [] for point in self._points: if point.edge_id != edge_id: print(edge_id) self._add_route(waypoints, edge_id) waypoints = [] edge_id = point.edge_id if point == self._points[-1]: # for collecting the last edge waypoints.append(point) print(edge_id) self._add_route(waypoints, edge_id) return True waypoints.append(point) def get_routes(self): return self._routes def get_points_edges(self): return self._points, self._edges
def Iterate(self,provis,OBS,control,unknowns): count=obsCount(OBS) L=self.getL(provis, OBS, control) # print "============== A Matrix =========================================" A = numpy.zeros(shape=(count,len(unknowns))) A[0][0]=3 i=0 j=0 for station_name,station in OBS.iteritems(): if control.has_key(station_name): current_station=control[station_name] elif provis.has_key(station_name): current_station=provis[station_name] for tname,target in station.iteritems(): tname=tname[0:-2] j=0 # tname=tname[0:-2] if target.type=='direction' or target.type=='distance' : for diff_wrt in unknowns: if diff_wrt[-1]=='o': if station_name==diff_wrt[0:-2]: A[i][j]=-1. j+=1 continue else: A[i][j]=0 j+=1 continue if not tname==diff_wrt[0:-2] and not station_name==diff_wrt[0:-2]: A[i][j]=0 j+=1 continue if control.has_key(tname):#if observing control if target.type=="direction": A[i][j]=equations(current_station,control[tname],diff_wrt,'direction') else : A[i][j]=equations(current_station,control[tname],diff_wrt,'distance') j+=1 continue else:#if observing provisional if target.type=="direction": A[i][j]=equations(current_station,provis[tname],diff_wrt,'direction') else: A[i][j]=equations(current_station,provis[tname],diff_wrt,'distance') j+=1 continue else: for diff_wrt in unknowns: if diff_wrt[-1]=='o': if station_name==diff_wrt[0:-2]: A[i][j]=-1. j+=1 continue else: A[i][j]=0 j+=1 continue if not tname==diff_wrt[0:-2] and not station_name==diff_wrt[0:-2]: A[i][j]=0 j+=1 continue if control.has_key(tname):#if observing control A[i][j]=equations(current_station,control[tname],diff_wrt,target.type) j+=1 else:#if observing provisional A[i][j]=equations(current_station,provis[tname],diff_wrt,target.type) j+=1 i+=1 names=[] for name,ob in OBS.iteritems(): for na,tar in ob.iteritems(): if tar.type=="both": names.append(name + "-" + na + "D") names.append(name + "-" + na + "d") else: names.append(name + "-" + na + "D") row_labels = ['SUR09-T013', 'Y', 'N', 'W'] # for row_label, row in zip(names, A): # print '%s [%s]' % (row_label, ' '.join('%01f' % i for i in row)) # print "============== Calculating Least squares =========================================" Pob= Weights() Pob.setDirectionWeight(1) Pob.setDistanceWeight(1) P=Pob.matrix(OBS,A) A=numpy.asmatrix(A) N= (((A.T)*A)**(-1))*A.T*L provUpdate=self.Provisional(N, provis, unknowns) Xtemp=Points("N correction pairs") i=0 for name in unknowns: Xtemp[name]=float64(N[i]) i+=1 V=A*N-L # print A.T*V posteriori=float((V.T*P*V)/(count-size(unknowns))) # print posteriori covarience_mat= posteriori*(A.T*A)**(-1) precisions=Points("Precisions of Unknowns") i=0 for name,value in Xtemp.iteritems(): precisions[name]=sqrt(float(covarience_mat[i,i])) i+=1 # print precisions # # for i,j in finalX.iteritems(): # print i + ": " # print("Y: %.2f" % j.y) # print("N: %.2f" % j.x) # print "Orientations :\n" # for i,ob in orientations.iteritems(): # # print str.format("{0} {1}", i, round(ob,1)) # return A,Xtemp , provUpdate , OBS , control , unknowns, V,P # if __name__ == '__main__': # Leas= LeastSqr() # A,Xdict,provis,OBS,control,unknowns,V,P=Leas.Read('control.csv','observations.csv')
class String_Simulation(): def __init__(self, parameters): """Assign some initial values and parameters --- Arguments --- parameters (dict): key: x, y, nl, K, length_limit, h, t_max, e, debug_mode See details for each values in Points's documentation. """ if type(parameters) != dict: raise TypeError("params should be dictionary") self.__dict__ = parameters self.t = 0. # debugging if self.debug_mode: log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG) else: log.basicConfig(format="%(levelname)s: %(message)s") self.point = Points(N=len(self.x), position_x=self.x, position_y=self.y, natural_length=self.nl, K=self.K, length_limit=self.length_limit) # 成長率の決定 # 累積的に成長する場合 # self.grow_func = lambda arr: arr * 1.01 # 一定の成長率で成長する場合 # self.grow_func = lambda arr: arr + 0.00025 self.grow_func = lambda arr: arr + 0.001 # 乱数を含める # import random # def glow_randomly(arr): # D = np.array([0.0005 + 0.001 * random.random() # for i in range(self.point.N)]) # return arr + D # self.grow_func = glow_randomly def grow_func_k(arr, old_nl, new_nl): return arr * old_nl / new_nl self.grow_func_k = grow_func_k self.fig, self.ax = plt.subplots() self.l, = self.ax.plot(np.array([]), np.array([]), 'bo-') self.ax.set_xlim([-30., 30.]) self.ax.set_ylim([-30., 30.]) # toggle pause/resume by clicking the matplotlib canvas region self.pause = False def run(self): # Launch onClick by button_press_event self.fig.canvas.mpl_connect('button_press_event', self.onClick) self.fig.canvas.mpl_connect('key_press_event', self.on_key) # In order to increase fps, decrease 'interval' arguments # (default value of animation.TimedAnimation is 200) # ani = animation.FuncAnimation(self.fig, self.animate, self.update, # interval=300, blit=True, repeat=False) ani = animation.FuncAnimation(self.fig, self.animate, self.update, interval=0, blit=True, repeat=False) # -- Save to mp4 file # -- Set up formatting for the movie files # TODO: 何故かシミュレーションの途中で終わってしまう。 # 要調査 # Writer = animation.writers['ffmpeg'] # writer = Writer(fps=25, metadata=dict(artist='Me'), bitrate=192000) # now = time.asctime() # ani.save("output_"+now+".mp4", writer=writer) # Show the window plt.show() def animate(self, data): """FuncAnimationから呼ぶ。ジェネレータupdateから返された配列を描画する """ self.l.set_data(data[0], data[1]) return self.l, def __force_create_matrix(self, t, X): """self.forceとself.force_with_more_viscosityで用いられる行列を計算 バネ弾性,曲げ弾性による力を計算するための変換行列を生成する。 """ distances = self.point.get_distances(X[0], X[1]) # 圧縮由来の力を表す行列Zを作成 if self.point.is_open: # 開曲線のとき,先頭はゼロにする zz = np.insert(self.point.natural_length / distances - 1., 0, 0) K = np.insert(self.point.K, 0, 0) else: # 閉曲線の場合 zz = self.point.natural_length / distances - 1. K = self.point.K # どちらの場合でも len(zz) = N zz = np.diag(zz) K = np.diag(K) z = np.dot(K, zz) zl = -np.roll(z, -1, axis=1) zu = -np.roll(z, -1, axis=0) zul = -np.roll(zu, -1, axis=1) Z = z + zl + zu + zul # 曲げ由来の力を表す行列Bを作成 if self.point.is_open: # 開曲線のとき,先頭,末尾はゼロにする ee = self.e * (distances[1:] ** (-3) + distances[:-1] ** (-3)) / 2 ee = np.insert(ee, 0, 0) ee = np.append(ee, 0) else: # 閉曲線の場合 ee = self.e * (distances ** (-3) + np.roll(distances, -1) ** (-3)) / 2 # どちらの場合でも len(ee) = N ee = np.diag(ee) el = np.roll(ee, -1, axis=1) er = np.roll(ee, 1, axis=1) eu = np.roll(ee, -1, axis=0) ed = np.roll(ee, 1, axis=0) eru = np.roll(er, -1, axis=0) erd = np.roll(er, 1, axis=0) elu = np.roll(el, -1, axis=0) eld = np.roll(el, 1, axis=0) B = -(eld + erd + elu + eru) / 4 + (el + ed + er + eu) / 2 - ee return Z, B def force(self, t, X): """各点にかかる力を,バネ弾性と曲げ弾性,粘性の効果を入れて計算 1タイムステップでの変化 @return X' X = [x, y, x', y'] X' = [x', y', f_x/m, f_y/m] """ # 必要な変換行列を計算 Z, B = self.__force_create_matrix(t, X) # 粘性項D, 質量m return np.array([X[2], X[3], (np.dot(Z, X[0]) + np.dot(B, X[0]) - self.D * X[2]) / self.m, (np.dot(Z, X[1]) + np.dot(B, X[1]) - self.D * X[3]) / self.m ]) def force_with_more_viscosity(self, t, X): """関数forceの変化形。粘性が優位な場合 1 タイムステップでの変化 @return X' X = [x, y, x', y'] 粘性が非常に大きい時,運動方程式 mx'' = f - D v のx''は殆ど無視できるとして,式を簡単にすると D v = f の式を解くことになる。(x''の項は考慮しなくて良くなる) X' = [f_x/D, f_y/D, dummy. dummy] """ # 必要な変換行列を計算 Z, B = self.__force_create_matrix(t, X) # 粘性項D return np.array([(np.dot(Z, X[0]) + np.dot(B, X[0])) / self.D, (np.dot(Z, X[1]) + np.dot(B, X[1])) / self.D, X[2], X[3] ]) def update_position_self_avoiding(self): """自己回避効果を取り入れ,他の線分要素との重なりを解消する cross_detect関数を用いて交差判定を行い,座標の交換を行う NOTE: 簡単に無限ループに入って抜け出せなくなるので, 別のアプローチを採るべき TODO: 運動方程式内でそれぞれの線分要素に短距離斥力ポテンシャルを与える """ crossing = True # while crossing: count = 0 lis = range(self.point.N - 1) # random.shuffle(lis) for i in lis: llis = range(i + 2, self.point.N - 2) # random.shuffle(llis) for k in llis: x_i = self.point.position_x[i] y_i = self.point.position_y[i] x_i1 = self.point.position_x[i+1] y_i1 = self.point.position_y[i+1] x_k = self.point.position_x[k] y_k = self.point.position_y[k] x_k1 = self.point.position_x[k+1] y_k1 = self.point.position_y[k+1] if self.cross_detect(x_i, x_i1, x_k, x_k1, y_i, y_i1, y_k, y_k1): # Update positions # distance_i_k1 = norm(np.array([x_i - x_k1, y_i - y_k1])) # distance_i1_k = norm(np.array([x_i1 - x_k, y_i1 - y_k])) distance_i_k1 = abs(x_i - x_k1) + abs(y_i - y_k1) distance_i1_k = abs(x_i1 - x_k) + abs(y_i1 - y_k) if distance_i_k1 > distance_i1_k: self.point.position_x[i+1] = 0.75 * x_k + 0.25 * x_i1 self.point.position_y[i+1] = 0.75 * y_k + 0.25 * y_i1 self.point.position_x[k] = 0.25 * x_k + 0.75 * x_i1 self.point.position_y[k] = 0.25 * y_k + 0.75 * y_i1 # 速度を反転 self.point.vel_x[i+1] = - self.point.vel_x[i+1] self.point.vel_y[i+1] = - self.point.vel_y[i+1] self.point.vel_x[k] = - self.point.vel_x[k] self.point.vel_y[k] = - self.point.vel_y[k] else: self.point.position_x[i] = 0.75 * x_k1 + 0.25 * x_i self.point.position_y[i] = 0.75 * y_k1 + 0.25 * y_i self.point.position_x[k+1] = 0.25 * x_k1 + 0.75 * x_i self.point.position_y[k+1] = 0.25 * y_k1 + 0.75 * y_i # 速度を反転 self.point.vel_x[i] = - self.point.vel_x[i] self.point.vel_y[i] = - self.point.vel_y[i] self.point.vel_x[k+1] = - self.point.vel_x[k+1] self.point.vel_y[k+1] = - self.point.vel_y[k+1] # self.point.position_x[i+1] = 0.55 * x_k + 0.45 * x_i1 # self.point.position_y[i+1] = 0.55 * y_k + 0.45 * y_i1 # self.point.position_x[k] = 0.45 * x_k + 0.55 * x_i1 # self.point.position_y[k] = 0.45 * y_k + 0.55 * y_i1 # self.point.position_x[i+1] = x_k # self.point.position_y[i+1] = y_k # self.point.position_x[k] = x_i1 # self.point.position_y[k] = y_i1 count += 1 if count == 0: crossing = False def cross_detect(self, x1, x2, x3, x4, y1, y2, y3, y4): """2つの線分の交差判定を行う @return True/False 線分1: (x1, y1), (x2,y2) 線分2: (x3, y3), (x4,y4) # 線分が接する場合にはFalseを返すこととする """ # まず,絶対に交差しない場合を除く # xについて if x1 < x2: if (x3 < x1 and x4 < x1) or (x3 > x2 and x4 > x2): return False else: if (x3 < x2 and x4 < x2) or (x3 > x1 and x4 > x1): return False # yについて if y1 < y2: if (y3 < y1 and y4 < y1) or (y3 > y2 and y4 > y2): return False else: if (y3 < y2 and y4 < y2) or (y3 > y1 and y4 > y1): return False if ((x1 - x2)*(y3 - y1) + (y1 - y2)*(x1 - x3)) * \ ((x1 - x2)*(y4 - y1) + (y1 - y2)*(x1 - x4)) >= 0: return False if ((x3 - x4)*(y1 - y3) + (y3 - y4)*(x3 - x1)) * \ ((x3 - x4)*(y2 - y3) + (y3 - y4)*(x3 - x2)) >= 0: return False # Else return True def update(self): """時間発展(タイムオーダーは成長よりも短くすること) 各点にかかる力は,それぞれに付いているバネから受ける力の合力。 Runge-Kutta法を用いて運動方程式を解く。 この内部でglow関数を呼ぶ --- Arguments --- point (class): 参照するPointクラスを指定する h (float): シミュレーションの時間発展の刻み t_max (float): シミュレーションを終了する時間 """ # 初期条件 X = np.array([self.point.position_x, self.point.position_y, self.point.vel_x, self.point.vel_y ]) # X = [[x0, x1, ... , xN-1], # [y1, y2, ... , yN-1], # [x'0, x'1, ... , x'N-1], # [y'1, y'2, ..., y'N-1]] # solver = RK4(self.force) # Runge-Kutta method # solver = RK4(self.force_with_more_viscosity) # Runge-Kutta method # solver = Euler(self.force) # Euler method solver = Euler(self.force_with_more_viscosity) # Euler method t_count, frame = 0, 0 while self.t < self.t_max: if not self.pause: X = solver.solve(X, self.t, self.h) # update values self.point.position_x, self.point.position_y = X[0], X[1] self.point.vel_x, self.point.vel_y = X[2], X[3] # 各バネの自然長を増加させる & バネ定数を変化させる self.point.grow(self.grow_func, self.grow_func_k) # 各点間の距離が基準値を超えていたら,間に新たな点を追加する X = self.point.divide_if_extended(X) # self avoiding if self.self_avoiding: self.update_position_self_avoiding() # 一定の間隔で描画を行う if self.t > self.h * 12 * frame: # TODO: 要検討 log.info(self.t) log.info("N: " + str(self.point.N)) log.info("x: " + str(self.point.position_x)) log.info("y: " + str(self.point.position_y)) log.info("d: " + str(self.point.get_distances( self.point.position_x, self.point.position_y))) log.info("nl: " + str(self.point.natural_length)) log.info("K: " + str(self.point.K)) if self.point.is_open: yield [self.point.position_x, self.point.position_y] else: yield [np.append(self.point.position_x, self.point.position_x[0]), np.append(self.point.position_y, self.point.position_y[0])] frame += 1 t_count += 1 self.t = self.h * t_count else: time.sleep(0.1) if self.point.is_open: yield [self.point.position_x, self.point.position_y] else: yield [np.append(self.point.position_x, self.point.position_x[0]), np.append(self.point.position_y, self.point.position_y[0])] print "Done!" def pause_simulation(self): """シミュレーションを一時停止""" if self.pause: print "Resume the simulation ..." else: print "[Paused] Please click the figure to resume the simulation" self.pause ^= True def onClick(self, event): """matplotlibの描画部分をマウスでクリックすると一時停止""" self.pause_simulation() def on_key(self, event): """キーを押すことでシミュレーション中に動作""" # i キーで情報表示 if event.key == "i": print "--- [information] ---" print "x: " + str(self.point.position_x) print "y: " + str(self.point.position_y) print "d: " + str(self.point.get_distances(self.point.position_x, self.point.position_y)) print "nl: " + str(self.point.natural_length) print "K: " + str(self.point.K) print "t: " + str(self.t) print "N: " + str(self.point.N) # ctrl+p キーでPause if event.key == "ctrl+p": self.pause_simulation()
groupRest=False, sort=False), legendString) path = '/backups/reset/1/1503159466' path = '/backups/reset/2/1503403069' path = "" chatevents = Events("." + path + "/chatevents.json") allchatevents = Events("." + path + "/chatevents.json") for dirname, dirnames, filenames in os.walk('./backups/reset/'): print(dirnames) for filename in filenames: if filename == 'chatevents.json': print(dirname + '/' + filename) allchatevents.addEventFile(dirname + '/' + filename) chatpoints = Points("." + path + "/chatlevel.json") chatpoints.save() #plotChattipsForName(chatevents, 'jarikboygangela') #plotChattipsForName(chatevents, 'MAI') #plotMost(chatpoints, "Chatroulette ", by='chatroulette', firstElements=6, lastElements=6, ignoreChannels=True, average=True) #plotGamblersTipreceivers(chatpoints, ignoreChannels=True, reversed=True) pltShow = False pltSave = True if True: plotMostPoints(chatpoints, firstElements=10, ignoreChannels=True) plotPointsWithoutInfluence(chatpoints, ignoreChannels=True, reversed=True) plotChattipsForName(chatevents, '#reset', firstElements=6, lastElements=0) plotMost(chatpoints, "Chattips",
def draw( self ) : Points.draw( self ) self.draw_debug_trim_curve()
def setUp(self): self.game = Points(15, 15) self.game.reset(random_crosses=False)
class PointsTest(unittest.TestCase): def setUp(self): self.game = Points(15, 15) self.game.reset(random_crosses=False) def test_empty_house(self): ##### ##.## #.#.# ##.## ##### self.game.make_move_coordinate(2, 1, 0) self.game.make_move_coordinate(3, 2, 0) self.game.make_move_coordinate(2, 3, 0) self.game.make_move_coordinate(1, 2, 0) self.game.surround_check() self.assertFalse(self.game.owners[2, 2, 0], 'House is not empty') self.assertFalse(self.game.owners[2, 2, 1], 'House is not empty') def test_suicide(self): ##### ##.## #.X.# ##.## ##### self.game.make_move_coordinate(2, 1, 0) self.game.make_move_coordinate(1, 2, 0) self.game.make_move_coordinate(3, 2, 0) self.game.make_move_coordinate(2, 3, 0) self.game.make_move_coordinate(2, 2, 1) self.game.surround_check(mode='suicide') self.assertTrue(self.game.owners[2, 2, 0], 'Suicide point is not surrounded.') self.assertEqual(self.game.score[0], 1, 'Wrong score.') def test_one_point_multiple_surrounds(self): """ ##### #.#.# .0.0. #.#.# ##### """ self.game.make_move_coordinate(1, 1, 0) self.game.make_move_coordinate(3, 1, 0) self.game.make_move_coordinate(0, 2, 0) self.game.make_move_coordinate(1, 2, 1) self.game.make_move_coordinate(3, 2, 1) self.game.make_move_coordinate(4, 2, 0) self.game.make_move_coordinate(1, 3, 0) self.game.make_move_coordinate(3, 3, 0) self.game.make_move_coordinate(2, 2, 0) self.game.surround_check() self.assertTrue(self.game.owners[1, 2, 0], 'First point is not surrounded.') self.assertTrue(self.game.owners[3, 2, 0], 'Second point is not surrounded.') self.assertEqual(self.game.score[0], 2, 'Wrong score.') self.assertEqual(self.game.score[1], 0, 'Wrong score.') def test_graph_while(self): """ .OOOO. O.X..O O.OOO. O....O .OOOO. """ self.game.make_move_coordinate(1, 0, 0) self.game.make_move_coordinate(2, 0, 0) self.game.make_move_coordinate(3, 0, 0) self.game.make_move_coordinate(4, 0, 0) self.game.make_move_coordinate(0, 1, 0) self.game.make_move_coordinate(2, 1, 1) self.game.make_move_coordinate(5, 1, 0) self.game.make_move_coordinate(0, 2, 0) self.game.make_move_coordinate(2, 2, 0) self.game.make_move_coordinate(3, 2, 0) self.game.make_move_coordinate(4, 2, 0) self.game.make_move_coordinate(0, 3, 0) self.game.make_move_coordinate(5, 3, 0) self.game.make_move_coordinate(1, 4, 0) self.game.make_move_coordinate(2, 4, 0) self.game.make_move_coordinate(3, 4, 0) self.game.make_move_coordinate(4, 4, 0) # TODO checks self.game.surround_check() def test_longest_chain(self): """ .O... O.O.. O.OO. OX..O .OOO. """ self.game.make_move_coordinate(1, 0, 0) self.game.make_move_coordinate(0, 1, 0) self.game.make_move_coordinate(2, 1, 0) self.game.make_move_coordinate(0, 2, 0) self.game.make_move_coordinate(2, 2, 0) self.game.make_move_coordinate(3, 2, 0) self.game.make_move_coordinate(0, 3, 0) self.game.make_move_coordinate(1, 3, 1) self.game.make_move_coordinate(4, 3, 0) self.game.make_move_coordinate(1, 4, 0) self.game.make_move_coordinate(2, 4, 0) self.game.make_move_coordinate(3, 4, 0) self.game.surround_check() # print(self.game) # self.game.print_owners() self.assertFalse(self.game.owners[2, 2, 0], 'Wrong chain.') def test_simple_surround(self): """ .0. OXO .O. """ self.game.make_move_coordinate(2, 1, 0) self.game.make_move_coordinate(1, 2, 0) self.game.make_move_coordinate(2, 2, 1) self.game.make_move_coordinate(3, 2, 0) self.game.make_move_coordinate(2, 3, 0) self.game.surround_check() # print(self.game) self.assertTrue(self.game.owners[2, 2, 0], 'Point is not surrounded.') self.assertEqual(self.game.score[0], 1, 'Wrong score.') def test_random_moves(self): while not self.game.is_ended: a = random.choice(list(self.game.free_dots)) self.game.auto_turn(a) def test_grounded(self): self.game.make_move_coordinate(2, 1, 0) self.game.make_move_coordinate(1, 1, 0) self.game.make_move_coordinate(0, 1, 0) self.game.grounding() self.game.change_turn() self.game.surround_check(mode='grounding') self.assertEqual(self.game.get_winner(), 0, 'Wrong winner') def test_surrounder_chain_grounding(self): self.game.make_move_coordinate(2, 1, 0) self.game.make_move_coordinate(1, 2, 0) self.game.make_move_coordinate(2, 2, 1) self.game.make_move_coordinate(3, 2, 0) self.game.make_move_coordinate(2, 3, 0) self.game.surround_check() self.game.grounding() self.game.change_turn() self.game.surround_check(mode='grounding') print()
def LeastSqrRead(inputControl,inputObservations): control = Points() control.read(inputControl) provis = Points() np.set_printoptions(precision=12) np.set_printoptions(suppress=True) np.set_printoptions(linewidth=2000) numpy.set_printoptions(threshold=1000) print "Reading Obs" obs = SurveyData() count=obs.read(inputObservations)#reads in file into the surveyData dictionary which contains Target object with two variables # determine adjustment information unknowns2 = set() # set of text items obsList=[] for i,sta in obs.iteritems(): for j,k in sta.iteritems(): if k.type=='both': obsList.append(i +"-"+ "direction-" +" "+ j) obsList.append(i +"-"+ "distance-" +" "+ j) else: obsList.append(i +"-"+ k.type +" "+ j) print obsList # knowns = [] for station_name, station in obs.iteritems(): unknowns2.add(station_name+'_o') for target_name, target in station.iteritems(): if not control.has_key(target_name): unknowns2.add(target_name+'_x') unknowns2.add(target_name+'_y') pass#print target_name, target.direction. unknowns=[] for i in unknowns2: unknowns.append(i) print unknowns G=nx.MultiGraph() G.add_node(2) G.add_node(5) G.add_edge(2,3) nx.draw(G) # Means all distances between points print "=== Calculate Mean Distance Observations ==================" # for sn1,station1 in obs.iteritems(): # for sn2,station2 in obs.iteritems(): # for tn1,target1 in station1.iteritems(): # for tn2,target2 in station2.iteritems(): # if (not target2.distance==None) and (not target1.distance==None) : # if tn1==sn2 and tn2==sn1: # print tn1,sn1,tn2,sn2 # print "distance 1: "+ str(target1.distance) + "\ndistance 2 :" + str(target2.distance) # temp=target1.distance # target1.distance = (target1.distance+target2.distance)/2.0 # target2.distance = (temp+target2.distance)/2.0 # print "mean: "+ str(target2.distance) print "=================================================================================" print "=== Calculate Provisional Coordinates ==================" #give stations coordinates if they're control points for name,obj in control.iteritems(): if obs.has_key(name): obs[name].setPoint(obj) for sn1,station1 in obs.iteritems(): for tn1,target1 in station1.iteritems(): if not control.has_key(tn1) and not station1[tn1].distance==None and not station1.point==None: # print "station :"+sn1 d= station1[tn1].distance t= station1[tn1].direction x,y,h=station1.point.polar(d,t) # print "target :" + tn1 provis.add(tn1,x,y,h,False) obs[tn1].setPoint(provis[tn1]) # print str(obs[tn1].point) # print str(tn1) + str(provis[tn1]) for i,j in provis.iteritems(): print i print j print "=================================================================================" print "====== Truncate Distances ===========================================================================" # temp=Points() # for i,obj in provis.iteritems(): # temp.add(i,obj.x,obj.y,obj.h,False) # for p,obj in temp.iteritems(): # provis.replace(p,floor(obj.x),floor(obj.y),floor(obj.h),False) # print provis[p] # # print "====================== TESTING =====================================================" # # provis.add('U1',58961.,49666.4,0.,False) # print provis['U1'] # provis.add('U2',59120.6,49687.0,0.,False) # print provis['U2'] # provis.add('U3',59295.0,49732.0,0.,False) # print provis['U3'] # # # # print Directions(control['SUR09'],'known',provis['U1trunc'],'unknown','y') # print Distances(control['SUR09'],'known',provis['U1trunc'],'unknown','x') # print obs['SUR09'].point.joinS(provis['test']) print "=================================================================================" print "====== Calculate Misclosure L ===========================================" L=numpy.zeros(shape=(count,1)) i=0 for sn1,station in obs.iteritems(): for tn1,target in station.iteritems(): if target.type=="both": if control.has_key(tn1): calc=obs[sn1].point.join(control[tn1]) elif provis.has_key(tn1): calc=obs[sn1].point.join(provis[tn1]) else: print "error" observed=obs[sn1][tn1].direction target.setMisclosure(observed-calc) L[i][0]=(observed-calc)*180.*3600./pi i+=1 L[i][0]=obs[sn1][tn1].distance-floor(obs[sn1][tn1].distance) print L[i][0] i+=1 continue else: if control.has_key(tn1): calc=obs[sn1].point.join(control[tn1]) elif provis.has_key(tn1): calc=obs[sn1].point.join(provis[tn1]) else: print "error" observed=obs[sn1][tn1].direction target.setMisclosure(observed-calc) L[i][0]=(observed-calc)*180.*3600./pi i+=1 print str(sn1) + " " + str(tn1) # print observed print ('%0.1f' % float64(target.misclosure*180./math.pi*3600.)) print "============== A Matrix =========================================" print count A = numpy.zeros(shape=(count,len(unknowns))) A[0][0]=3 i=0 j=0 doub=False print unknowns for at,station in obs.iteritems(): print at if control.has_key(at):station.point.setKnown(True) for atObserved,observ in station.iteritems(): print "target : " +atObserved +" " + observ.type j=0 if observ.type=='both': doub=True for at_wrt in unknowns: if at_wrt[-1]=='o': if at==at_wrt[0:-2]: A[i][j]=-1. print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) j+=1 continue else: A[i][j]=0 print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) j+=1 continue if not atObserved==at_wrt[0:-2] and not at==at_wrt[0:-2]: # print t # print at_wrt[0:-2] A[i][j]=0 print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) j+=1 continue if control.has_key(atObserved):#if observing control A[i][j]=equations(station.point,control[atObserved],at_wrt,'direction') print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) A[i+1][j]=equations(station.point,control[atObserved],at_wrt,'distance') print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) j+=1 else:#if observing provisional A[i][j]=equations(station.point,provis[atObserved],at_wrt,'direction') print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) A[i+1][j]=equations(station.point,provis[atObserved],at_wrt,'distance') print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) j+=1 else: for at_wrt in unknowns: if at_wrt[-1]=='o': if at==at_wrt[0:-2]: A[i][j]=-1. print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) j+=1 continue else: A[i][j]=0 j+=1 continue if not atObserved==at_wrt[0:-2] and not at==at_wrt[0:-2]: # print t # print at_wrt[0:-2] A[i][j]=0 print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) j+=1 continue if control.has_key(atObserved):#if observing control A[i][j]=equations(station.point,control[atObserved],at_wrt,observ.type) print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) j+=1 else:#if observing provisional A[i][j]=equations(station.point,provis[atObserved],at_wrt,observ.type) print str(i) +" "+ str(j)+ " :"+ str(A[i][j]) j+=1 if doub==True: i+=2 print "i: " +str(i) doub=False else: i+=1 print "i: " +str(i) print "" print " U1_y', 'U1_x', 'U3_y', 'U3_x', 'SUR12_o', 'U2_o', 'U2_x', 'U2_y', 'U1_o', 'U3_o', 'SUR09_o' " names=[] for name,ob in obs.iteritems(): for na,tar in ob.iteritems(): if tar.type=="both": names.append(name + "-" + na + "D") names.append(name + "-" + na + "d") else: names.append(name + "-" + na + "D") row_labels = ['SUR09-T013', 'Y', 'N', 'W'] for row_label, row in zip(names, A): print '%s [%s]' % (row_label, ' '.join('%01f' % i for i in row)) # except: # print "trying" # A[i][j]=equations(station.point,provis[t],at_wrt[-1],types[i]) # # # i+=1 # print A print "============== Calculate Least squares =========================================" Pob= Weights() Pob.setDirectionWeight(1) Pob.setDistanceWeight(1) P=Pob.matrix(obs,A) A=numpy.asmatrix(A) N= (((A.T)*A)**(-1))*A.T*L print "now" print A.T*P*L for row_label, row in zip(unknowns, N): print '%7s [%s]' % (row_label, ' '.join('%07f' % i for i in row)) j=0 # for name in unknowns: # print name[0:-2] + str(+N[i]) # # print name + str(ob.y+N[i]) # i+=1 # print ob.x # print ob.y print unknowns print provis finalX=Points() orientations={} for i in unknowns: name= i[0:-2] variable = i[-1] if variable=="o": orientations[name]= float64(N[j]) j+=1 continue x=provis[name].x y=provis[name].y h=provis[name].h if not finalX.has_key(name): finalX[name]= Point(0,0,0,False,name) if variable=="x": finalX[name].ChangeVariable(variable,float64(x+N[j])) j+=1 continue if variable=="y": finalX[name].ChangeVariable(variable,float64(y+N[j])) j+=1 continue if variable=="h": finalX[name].ChangeVariable(variable,float64(h+N[j])) j+=1 continue print finalX[name] # T=numpy.matrix([[1,2,3],[3,2,3],[3,2,1],[3,2,1]]) # S=numpy.matrix([[3,2,3],[3,2,1],[3,2,1],[1,2,3]]) # M=numpy.matrix([[3,2,3],[3,2,1],[1,2,3],[3,2,1]]) # print T # print T.T*T # print S.T*S # print M.T*M # print A.T*P*L # print T*T.T for i,j in finalX.iteritems(): print i + ": " print("Y: %.2f" % j.y) print("N: %.2f" % j.x) print "Orientations :\n" for i,ob in orientations.iteritems(): print str.format("{0} {1}", i, round(ob,1)) V=A*N-L for i in range(size(V)): print str(obsList[i]) +": " + str(V[i]) return finalX , obs,control
class TestGreeting(unittest.TestCase): def setUp(self): self.g = Points() def test_part_of_day_0offset_local_time0(self): test_time = timegm(strptime('2015-04-01 00:00', '%Y-%m-%d %H:%M')) user_tz_offset = 0 part_of_day = self.g.get_part_of_day(user_tz_offset, test_time) self.assertEqual('midnight', part_of_day) def test_part_of_day_0offset_local_time13(self): test_time = timegm(strptime('2015-04-01 13:05', '%Y-%m-%d %H:%M')) user_tz_offset = 0 part_of_day = self.g.get_part_of_day(user_tz_offset, test_time) self.assertEqual('afternoon', part_of_day) def test_part_of_day_minus9offset_local_time5(self): test_time = timegm(strptime('2012-02-29 14:20', '%Y-%m-%d %H:%M')) user_tz_offset = -9 part_of_day = self.g.get_part_of_day(user_tz_offset, test_time) self.assertEqual('dawn', part_of_day) def test_part_of_day_minus4offset_local_time22(self): test_time = timegm(strptime('2030-03-09 02:00', '%Y-%m-%d %H:%M')) user_tz_offset = -4 part_of_day = self.g.get_part_of_day(user_tz_offset, test_time) self.assertEqual('night', part_of_day) def test_part_of_day_11offset_local_time5(self): # 2015-04-25 05:00:00 (+11) test_time = timegm(strptime('2015-04-24 18:00', '%Y-%m-%d %H:%M')) user_tz_offset = 11 part_of_day = self.g.get_part_of_day(user_tz_offset, test_time) self.assertEqual('dawn', part_of_day) def test_choose_greeting_testuser_0_dawn(self): reply = 'Good early morning, TestUser.' self.assertEqual(reply, self.g.choose_greeting('TestUser', 0, 'dawn')) def test_choose_greeting_testuser_0_midnight(self): reply = 'Hi, TestUser.' self.assertEqual(reply, self.g.choose_greeting('TestUser', 0, 'midnight')) def test_choose_greeting_testuser_0_evening(self): reply = 'Good evening, TestUser123.' self.assertEqual(reply, self.g.choose_greeting('TestUser123', 0, 'evening')) def test_choose_greeting_testuser_1_afternoon(self): reply = 'Good afternoon, Level1User!' self.assertEqual(reply, self.g.choose_greeting('Level1User', 1, 'afternoon')) def test_choose_greeting_testuser_2_dusk(self): reply = 'Good afternoon Level2User!!' self.assertEqual(reply, self.g.choose_greeting('Level2User', 2, 'dusk')) def test_choose_greeting_testuser_2_morning(self): reply = 'Good morning Level2User!!' self.assertEqual(reply, self.g.choose_greeting('Level2User', 2, 'morning')) def test_choose_greeting_testuser_0_noon(self): reply = 'Hi, TestUser.' self.assertEqual(reply, self.g.choose_greeting('TestUser', 0, 'noon')) def test_choose_greeting_testuser_1_noon(self): reply = 'Hi, TestUser!' self.assertEqual(reply, self.g.choose_greeting('TestUser', 1, 'noon')) def test_choose_greeting_testuser_2_noon(self): reply = 'Hi Level2User!!' # no comma self.assertEqual(reply, self.g.choose_greeting('Level2User', 2, 'noon'))
def Read(self,inputControl,inputObservations): control = Points("control points") control.read(inputControl) # print control provis = Points("provisional points") # print provis np.set_printoptions(precision=12) np.set_printoptions(suppress=True) np.set_printoptions(linewidth=2000) numpy.set_printoptions(threshold=1000) print "Reading Obs" obs = SurveyData() count,N,pos=obs.read(inputObservations,control)#reads in file into the surveyData dictionary which contains Target object with two variables print obs edge_weight={} # for u,v,d in N.edges(data=True): # print u # print v # edge_weight[u][v]=d['direction'] # dict([((u,v,),int(d['distance'])) for u,v,d in N.edges(data=True)]) nx.draw_networkx_nodes(N,pos, node_color='y', node_size=800, alpha=0.8) nx.draw_networkx_nodes(N,pos, nodelist=control, node_color='r', node_size=800, alpha=0.8) edges={} for v,u,d in N.edges(data=True): # print d if d.has_key("distance") and d.has_key('direction'): edges[v,u]='b' nx.draw(N,pos) nx.draw_networkx_edges(N,pos, edgelist=edges, width=8,alpha=0.5,edge_color='b') plt.show() OBS=ObsSplit("Individual Observations 2014 Survey") OBS=OBS.read(obs,control) # print OBS # N.add_nodes_from(obs.keys()) # for n, p in control.iteritems(): # N.node[n]['pos'] = p # # nx.draw(N,'pos') # plt.show() # determine adjustment information unknowns2 = set() # set of text items obsList=[] for i,sta in obs.iteritems(): for j,k in sta.iteritems(): if k.type=='both': obsList.append(i +"-"+ "direction-" +" "+ j) obsList.append(i +"-"+ "distance-" +" "+ j) else: obsList.append(i +"-"+ k.type +" "+ j) # knowns = [] for station_name, station in obs.iteritems(): unknowns2.add(station_name+'_o') for target_name, target in station.iteritems(): if not control.has_key(target_name): unknowns2.add(target_name+'_x') unknowns2.add(target_name+'_y') pass unknowns=[] # print obsList for i in unknowns2: unknowns.append(i) # Means all distances between points # print "=== Calculate Mean Distance ObsSplit ==================" # for sn1,station1 in obs.iteritems(): # for sn2,station2 in obs.iteritems(): # for tn1,target1 in station1.iteritems(): # for tn2,target2 in station2.iteritems(): # if (not target2.distance==None) and (not target1.distance==None) : # if tn1==sn2 and tn2==sn1: # print tn1,sn1,tn2,sn2 # print "distance 1: "+ str(target1.distance) + "\ndistance 2 :" + str(target2.distance) # temp=target1.distance # target1.distance = (target1.distance+target2.distance)/2.0 # target2.distance = (temp+target2.distance)/2.0 # print "mean: "+ str(target2.distance) print "=================================================================================" print "=== Calculate Provisional Coordinates ==================" for sta,station in obs.iteritems(): if control.has_key(sta): continue else: provis.add(sta, station.point.x, station.point.y, station.point.h, False) # print provis #give stations coordinates if they're control points # for name,obj in control.iteritems(): # if obs.has_key(name): # obs[name].setPoint(obj) # # # for sn1,station1 in obs.iteritems(): # # for tn1,target1 in station1.iteritems(): # if not control.has_key(tn1) and not station1[tn1].distance==None and not station1[tn1].direction==None and not station1.point==None: # d= station1[tn1].distance # t= station1[tn1].direction # x,y,h=station1.point.polar(d,t) # provis.add(tn1,x,y,h,False) # obs[tn1].setPoint(provis[tn1]) print "=================================================================================" print "====== Truncate Distances ===========================================================================" temp=Points() for i,obj in provis.iteritems(): temp.add(i,obj.x,obj.y,obj.h,False) for p,obj in temp.iteritems(): provis.replace(p,floor(obj.x),floor(obj.y),floor(obj.h),False) # print provis[p] print "====================== TESTING =====================================================" # provis.add('SUR10',58961.,49666.4,0.,False) provis.add('RU4A',59120.6,49687.0,0.,False) provis.add('SUR11',59295.0,49732.0,0.,False) print "=================================================================================" print "====== Calculate Misclosure L ===========================================" L=numpy.zeros(shape=(count,1)) Lnames=Points("L vector name pairs") i=0 for sn1,station in OBS.iteritems(): for tn1,target in station.iteritems(): tn1=tn1[0:-2] # tn1=tn1[0:-2] if target.type=="direction": if control.has_key(tn1): calc=obs[sn1].point.join(control[tn1]) temp=obs[sn1].point elif provis.has_key(tn1): calc=obs[sn1].point.join(provis[tn1]) else: print "error" calc=0 observed=obs[sn1][tn1].direction target.setMisclosure(observed-calc) L[i][0]=((observed-calc)*3600.*180./pi) Lnames[sn1 + " to "+ tn1 + " direc"]=round(((observed-calc)*3600.*180./pi),1) i+=1 # continue elif target.type == "distance": if control.has_key(tn1): calc=obs[sn1].point.joinS(control[tn1]) elif provis.has_key(tn1): calc=obs[sn1].point.joinS(provis[tn1]) else: print "error" observed=obs[sn1][tn1].distance target.setMisclosure(observed-calc) L[i][0]=round((observed-calc),3) Lnames[sn1 + " to "+ tn1 + " distance"]=L[i][0] i+=1 # print str(sn1) + " " + str(tn1) # print observed # print ('%0.1f' % float64(target.misclosure*180./math.pi*3600.)) # print Lnames # print L print "============== A Matrix =========================================" A = numpy.zeros(shape=(count,len(unknowns))) A[0][0]=3 i=0 j=0 for station_name,station in OBS.iteritems(): if control.has_key(station_name): current_station=control[station_name] elif provis.has_key(station_name): current_station=provis[station_name] for tname,target in station.iteritems(): tname=tname[0:-2] j=0 # tname=tname[0:-2] if target.type=='direction' or target.type=='distance' : for diff_wrt in unknowns: if diff_wrt[-1]=='o'and target.type=='distance': A[i][j]=0 continue if diff_wrt[-1]=='o'and target.type=='direction': if station_name==diff_wrt[0:-2]: A[i][j]=-1. j+=1 continue else: A[i][j]=0 j+=1 continue if not tname==diff_wrt[0:-2] and not station_name==diff_wrt[0:-2]: A[i][j]=0 j+=1 continue if control.has_key(tname):#if observing control if target.type=="direction": A[i][j]=equations(current_station,control[tname],diff_wrt,'direction') else : A[i][j]=equations(current_station,control[tname],diff_wrt,'distance') j+=1 continue else:#if observing provisional if target.type=="direction": A[i][j]=equations(current_station,provis[tname],diff_wrt,'direction') else: A[i][j]=equations(current_station,provis[tname],diff_wrt,'distance') j+=1 continue else: for diff_wrt in unknowns: if diff_wrt[-1]=='o': if station_name==diff_wrt[0:-2]: A[i][j]=-1. j+=1 continue else: A[i][j]=0 j+=1 continue if not tname==diff_wrt[0:-2] and not station_name==diff_wrt[0:-2]: A[i][j]=0 j+=1 continue if control.has_key(tname):#if observing control A[i][j]=equations(current_station,control[tname],diff_wrt,target.type) j+=1 else:#if observing provisional A[i][j]=equations(current_station,provis[tname],diff_wrt,target.type) j+=1 i+=1 # print "i: " +str(i) #print "" print "SUR10_o', 'RU4A_y', 'RU4A_x', 'SUR11_x', 'SUR11_y', 'SUR12_o', 'SUR10_y', 'SUR10_x', 'RU4A_o', 'SUR11_o', 'SUR09_o'" # print A # print OBS names=[] for name,ob in obs.iteritems(): for na,tar in ob.iteritems(): if tar.type=="both": names.append(name + "-" + na + "D") names.append(name + "-" + na + "d") else: names.append(name + "-" + na + "D") row_labels = ['SUR09-T013', 'Y', 'N', 'W'] # for row_label, row in zip(names, A): #print '%s [%s]' % (row_label, ' '.join('%01f' % i for i in row)) # except: # print "trying" # A[i][j]=equations(station.point,provis[t],diff_wrt[-1],types[i]) # # # i+=1 # #print A print "============== Calculate Least squares =========================================" Pob= Weights() Pob.setDirectionWeight(1) Pob.setDistanceWeight(1) P=Pob.matrix(obs,A) A=numpy.asmatrix(A) N= (((A.T)*P*A)**(-1))*(A.T*P*L) Xtemp=Points("N correction pairs") i=0 for name in unknowns: Xtemp[name]=float64(N[i]) i+=1 finalX=Points("final Coordinates:") orientations={} j=0 for i in unknowns: name= i[0:-2] variable = i[-1] if variable=="o": orientations[name]= float64(N[j]) j+=1 continue x=provis[name].x y=provis[name].y h=provis[name].h if not finalX.has_key(name): finalX[name]= Point(0,0,0,False,name) if variable=="x": finalX[name].ChangeVariable(variable,float64(x+N[j])) j+=1 continue if variable=="y": finalX[name].ChangeVariable(variable,float64(y+N[j])) j+=1 continue if variable=="h": finalX[name].ChangeVariable(variable,float64(h+N[j])) j+=1 continue # print finalX V=A*N-L # print V # print A.T*V posteriori=float((V.T*P*V)/(count-size(unknowns))) # print posteriori covarience_mat= posteriori*(A.T*A)**(-1) precisions=Points("Precisions of Unknowns") i=0 # print "awek" # print N # print covarience_mat[1,1] for name,value in Xtemp.iteritems(): # print value # print N[i] precisions[name]=sqrt(float(covarience_mat[i,i])) i+=1 # print precisions print "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" return A, Xtemp,provis,OBS,control,unknowns,V,P
def setUp(self): self.g = Points()