Beispiel #1
0
def is_compatible(signature1, signature2):
    assert isinstance(signature1, Signature)
    assert isinstance(signature2, Signature)
    if geo.distance(signature1.min_coordinate, signature2.min_coordinate) < 1e-3:
        if geo.distance(signature1.max_coordinate, signature2.max_coordinate) < 1e-3:
            if len(signature1) == len(signature2):
                return all([(len(signature1[i]) == len(signature2[i]))
                            for i in range(len(signature1))])
    return False
    def execute(self, registry):
        '''
        Evaluate move orders.

        #any existing move orders should be evaluated
        #(going round robin on submitting players, in order)
        #R1: No collision checking
        #R2: Stop short of offending segment
        #R3: Stop tangent to offending unit
        '''

        player_nums = sorted(self.player_move_list.keys())
        # "rotate" player nums based on the turn number, so 
        # a different player gets to go "first" every turn
        num_of_players = len(player_nums)
        if not num_of_players:
            return
        num_of_shuffles = self.turn_num % num_of_players
        for x in range(num_of_shuffles):
            player_num.append(player_num.pop(0))
        
        lists = [self.player_move_list[x] for x in player_nums]
        combined_list = swizzle(lists)
        
        self.results = {}
        
        for playerMove in combined_list:
            
            unit = registry.getById(playerMove.unitid)
            path_pairs = [(playerMove.path[i-1],playerMove.path[i]) for i in range(1,len(playerMove.path))]
            path_taken = [playerMove.path[0]]
            for start,end in path_pairs:
                intersecting = []
                for other in registry.getAllByType(Unit):
                    if unit!=other:
                        if geometry.shipsWillCollideOnSegment(start, end, unit, other):
                            intersecting.append(other)
                
                if not intersecting:
                    unit.setLocation(end)
                    path_taken.append(end)
                else:
                    shortest = geometry.distance(start,end)
                    shortest_point = end
                    
                    for other in intersecting:
                        pt = geometry.whereWillItStop(start, end, unit, other)
                        if geometry.distance(start,pt)<shortest:
                            shortest = geometry.distance(start,pt)
                            shortest_point = pt
                        
                    unit.setLocation(shortest_point)
                    path_taken.append(shortest_point)
                    break
            
            self.results[unit.gid] = path_taken
Beispiel #3
0
def merge_signature(signature1, signature2, operation="concat"):
    assert operation in {"concat", "max", "min", "add"}
    assert isinstance(signature1, Signature)
    assert isinstance(signature2, Signature)
    assert geo.distance(signature1.min_coordinate, signature2.min_coordinate) < 1e-3
    assert geo.distance(signature1.max_coordinate, signature2.max_coordinate) < 1e-3
    assert len(signature1) == len(signature2)
    msig = deepcopy(signature1)
    for i in range(len(signature2)):
        msig.append2list_(i, signature2[i], operation=operation)
    return msig
Beispiel #4
0
def get_points_of_interest(arr):
    """
    Expects a binary object in the array.
    FInds the two contour points that are the farthest apart, then determines which of
    them is the base point of the RV and returns this first and the other as second
    return value.
    """
    #########
    # 1: Find points in objects contour with the largest distance between them.
    #########
    # extract only outer contour
    arr = arr - binary_erosion(arr)

    # extract all positions of the objects contour
    points = scipy.asarray(arr.nonzero()).T

    # compute pairwise distances
    distances = squareform(pdist(points, 'euclidean'))

    # get positon of largest distance
    position = scipy.unravel_index(scipy.argmax(distances),
                                   (len(points), len(points)))

    # recompute between which points the largest distance was found
    first = points[position[0]]
    second = points[position[1]]

    #logger.debug('Longest distance found between {} and {}.'.format(first, second))

    #########
    # 2: Determine which of these is the base point
    #########
    # go along perpendicular lines, find intersections with contours and keep longest only
    intersection = False
    longest_length = 0
    longest_line = line_from_points(first, second)
    segment_points = split_line_to_sections(5, first, second)
    for sp in segment_points:
        sline = perpendicular_line(longest_line, sp)
        nearest = find_nearest(sline, points, 10)
        if distance(nearest[0], nearest[1]) > longest_length:
            longest_length = distance(nearest[0], nearest[1])
            intersection = sp

    # determine which of the first two points are nearest to the longest line and return them
    if distance(intersection, first) < distance(intersection, second):
        return (first, second)
    else:
        return (second, first)
Beispiel #5
0
def makeTetra():
    vertices = [
        Point( 1, 0, 0),
        Point(-1, 0, 0),
        Point( 0, 1, 0),
        Point( 0,-1, 0),
        Point( 0, 0, 1),
        Point( 0, 0,-1)
    ]
    faces = []
    for a,b,c in itertools.combinations(vertices, 3):
        if distance(a,b) == distance(b,c) and distance(a,b) == distance(a,c):
            poly = Polygon(a,b,c)
            faces.extend(subDivide(poly,2))
    return Body(*faces)
def get_points_of_interest(arr):
    """
    Expects a binary object in the array.
    FInds the two contour points that are the farthest apart, then determines which of
    them is the base point of the RV and returns this first and the other as second
    return value.
    """
    #########
    # 1: Find points in objects contour with the largest distance between them.
    #########
    # extract only outer contour
    arr = arr - binary_erosion(arr)
    
    # extract all positions of the objects contour
    points = scipy.asarray(arr.nonzero()).T
    
    # compute pairwise distances
    distances = squareform(pdist(points, 'euclidean'))
    
    # get positon of largest distance
    position = scipy.unravel_index(scipy.argmax(distances), (len(points), len(points)))
    
    # recompute between which points the largest distance was found
    first = points[position[0]]
    second = points[position[1]]
    
    #logger.debug('Longest distance found between {} and {}.'.format(first, second))
    
    #########
    # 2: Determine which of these is the base point
    #########
    # go along perpendicular lines, find intersections with contours and keep longest only
    intersection = False
    longest_length = 0
    longest_line = line_from_points(first, second)
    segment_points = split_line_to_sections(5, first, second)
    for sp in segment_points:
        sline = perpendicular_line(longest_line, sp)
        nearest = find_nearest(sline, points, 10)
        if distance(nearest[0], nearest[1]) > longest_length:
            longest_length = distance(nearest[0], nearest[1])
            intersection = sp
    
    # determine which of the first two points are nearest to the longest line and return them
    if distance(intersection, first) < distance(intersection, second):
        return (first, second)
    else:
        return (second, first)
Beispiel #7
0
 def is_in_range(self, radius: float, pos: dict) -> bool:
     """Находится ли точка на аэродроме"""
     if geometry.is_pos_correct(pos=self.pos) and geometry.is_pos_correct(
             pos=pos):
         return geometry.distance(self.pos, pos) <= radius
     else:
         return False
    def do_protect_goal_actions(self, env, gstrategy):
        if shortcuts.can_take_puck(env):
            puck_abs_speed = geometry.vector_abs(env.world.puck.speed_x, env.world.puck.speed_y)
            if shortcuts.take_puck_probability(env, puck_abs_speed) >= 1.:
                env.move.action = ActionType.TAKE_PUCK
                return

            if not assessments.puck_is_heading_to_my_net(env):
                env.move.action = ActionType.TAKE_PUCK
                return

        if shortcuts.can_strike_unit(env, env.world.puck):
            env.move.action = ActionType.STRIKE
            return

        for oh in shortcuts.opponent_field_hockeyists(env):
            if shortcuts.can_strike_unit(env, oh):
                env.move.action = ActionType.STRIKE
                return

        if self.its_dangerous(env) and env.me.get_distance_to_unit(self.precount.defence_point) < 100:
            basic_actions.turn_to_unit(env, env.world.puck)
            if geometry.distance(self.precount.defence_point, env.world.puck) <= 200:
                if basic_actions.turned_to_unit(env, env.world.puck):
                    env.move.speed_up = 1.
            return

        speed_abs = geometry.vector_abs(env.me.speed_x, env.me.speed_y)
        if env.me.get_distance_to_unit(self.precount.defence_point) >= 20:
            experiments.fast_move_to_point(env, self.precount.defence_point)
        elif speed_abs > 0.01:
            experiments.do_stop(env)
        else:
            basic_actions.turn_to_unit(env, env.world.puck)
Beispiel #9
0
def make_route_map(options):
    """Makes .svg map with all locations and routes."""
    if svgwrite is None:
        print 'Package "svgwrite" is required to generate a map!'
        return

    print 'Routes map is generating'
    locations_dict = {loc.name: loc for loc in LOCATIONS}
    name = 'FlightPlans.svg' if options.beacons else 'Routes.svg'
    route_map = svgwrite.Drawing(name, size=(utils.MAP_WIDTH, utils.MAP_HEIGHT))

    for route, contract in ROUTES.iteritems():
        from_loc = locations_dict[route[0]]
        to_loc = locations_dict[route[1]]
        contract.set_locations(from_loc, to_loc)
        if options.beacons and not contract.plane_allowed:
            continue
        utils.add_route_arrow(
            route_map, from_loc, to_loc,
            beacons=(contract.beacons if options.beacons else None),
            stroke=contract.route_color,
            stroke_width='{}px'.format(utils.MAP_LINE_WIDTH),
        )
    for loc in LOCATIONS:
        pt = utils.point_on_map(loc.position)
        right_text = (pt[0] < 0.9 * utils.MAP_WIDTH)
        text_y_offset = 2.25
        if loc.name == 'Ben Bay':
            # I don't know how to fix overlapping of Kerman Lake better.
            text_y_offset = -1.25
        displace = geometry.Vector(4 if right_text else -4, text_y_offset)
        route_map.add(route_map.circle(center=pt, r=utils.MAP_POINT_RADIUS))
        route_map.add(route_map.text(
            loc.name,
            insert=(pt + displace * utils.MAP_POINT_RADIUS),
            text_anchor=('start' if right_text else 'end'),
            font_size='{}px'.format(utils.MAP_FONT_SIZE),
        ))
    if options.beacons:
        for beacon_name, beacon_pos in BEACONS.iteritems():
            pt = utils.point_on_map(beacon_pos)
            utils.add_beacon(route_map, pt)
            if any(geometry.distance(beacon_pos, loc.position) < 25 for loc in LOCATIONS):
                continue
            right_text = (pt[0] < 0.9 * utils.MAP_WIDTH)
            text_y_offset = 2.25
            if beacon_name == 'ISLAND-NDB':
                # I don't know how to fix overlapping of KSC better.
                text_y_offset = 4.25
            if beacon_name == 'SCORPION-MOUNTAINS-NDB':
                # I don't know how to fix overlapping of LONELY-MOUNTAIN-NDB better.
                right_text = False
            displace = geometry.Vector(4 if right_text else -4, text_y_offset)
            route_map.add(route_map.text(
                beacon_name,
                insert=(pt + displace * utils.MAP_POINT_RADIUS),
                text_anchor=('start' if right_text else 'end'),
                font_size='{}px'.format(0.75 * utils.MAP_FONT_SIZE),
            ))
    route_map.save()
 def can_run(self, env):
     if abs(env.world.puck.y - shortcuts.rink_center(env).y) < 130:
         return False
     for oh in shortcuts.opponent_field_hockeyists(env):
         if geometry.distance(env.me, oh) < 150:
             return False
     return True
Beispiel #11
0
    def walk(self):
        if self.walker_path is None:
            return

        if self.walker_last_move_time is None:
            self.walker_last_move_time = time.time( )
            return

        current_time = time.time( )

        self.walker_path_position += ( current_time - self.walker_last_move_time ) * self.walker_speed_p_s

        current_leg_length = geometry.distance( self.walker_path[0], self.walker_path[1] )
        if self.walker_path_position >= current_leg_length:
            if len( self.walker_path ) == 2:
                self.walker_position = self.walker_path[1]
                self.stop_walk( )
                return
            else:
                self.walker_path_position -= current_leg_length
                self.walker_path.pop( 0 )

        self.walker_position = geometry.measure_out( self.walker_path[0], self.walker_path[1], self.walker_path_position )
        self.walker_last_move_time = current_time
        self.redraw = True
Beispiel #12
0
    def find_walk_path(self, dest):
        if self.is_line_walkable( geometry.LineSegment( self.walker_position, dest ) ):
            return [ self.walker_position, dest ]

        vertices = self.vertices + [ self.walker_position, dest ]
        vertice_count = len( vertices )
        edges = self.edges.copy( )
        for i in range( vertice_count - 2 ):
            if self.is_line_walkable( geometry.LineSegment( vertices[ i ], self.walker_position ) ):
                edges.append( ( i, vertice_count - 2 ) )
            if self.is_line_walkable( geometry.LineSegment( vertices[ i ], dest ) ):
                edges.append( ( i, vertice_count - 1 ) )

        graph = { i : dict( ) for i in range( len( vertices ) ) }
        for edge in edges:
            distance = geometry.distance( vertices[ edge[0] ], vertices[ edge[1] ] )
            graph[ edge[0] ][ edge[1] ] = distance
            graph[ edge[1] ][ edge[0] ] = distance

        start_time = time.time()
        path = pathfinder.find_cheapest_path_dijkstra( graph, vertice_count-2, vertice_count-1 )
        end_time = time.time()
        print( "dijkstra algorithm took {} seconds".format( end_time - start_time ) )
        if path is None:
            return None

        path_coordinates = [ vertices[ vertice_i ] for vertice_i in path["path"] ]
        return path_coordinates
    def test_distance(self):
        p1 = (-3, 5)
        p2 = (7, -1)
        result = geometry.distance(p1, p2)
        expected = np.sqrt(136)

        self.assertEquals(result, expected)
Beispiel #14
0
def cells_in_section(section_vertices,
                     cell_width_mean,
                     cell_width_variance=0.0001,
                     oriented_towards_centre=True,
                     secretory_cell_probability=0.5):
    """
    Traverse each pair of vertices forming the section.
    Get the section orientation using its normal
    Compute the number of cells fitting between both vertices.

    :param section_vertices:
    :param cell_width_mean: in millimetres
    :param cell_width_variance: in millimetres
    :param oriented_towards_centre:
    :param secretory_cell_probability: Probability for any cells of being a secretory cell. Usually 0.5
    :return: list of cells in the current section
    """
    cells = list()
    limit = len(section_vertices)
    for i in range(1, limit):
        distance_between_vertices = geo.distance(section_vertices[i - 1],
                                                 section_vertices[i])
        # compute the number of cells to generate
        n_cells = distance_between_vertices / cell_width_mean
    # then check the segment between the last and the first vertices

    return cells
Beispiel #15
0
def generateGcodeParallel(segmentGroups, outputFile, tolerance): # not used

	m = Machine()


	config = segmentGroups[0].operationConfig
	# Machine Settings
	safetyHeight = config['safetyHeight']	 # mm
	feedRate = config['feedRate']	 # mm/min
	plungeRate = config['plungeRate']	 # mm/min
	stepSize = config['stepSize']	 # mm
	targetDepth = config['targetDepth']	 # mm
	

	workingHeight = -stepSize

	
	m.setFeedrate(feedRate, feedRate,  plungeRate)
		
	
	workingHeight = 0
	while workingHeight > targetDepth:
		
		workingHeight = workingHeight - stepSize
		if workingHeight < targetDepth:
			workingHeight = targetDepth
	
	
		m.moveZ(safetyHeight)
		
			
		for segmentGroup in segmentGroups:
			
			curvePoints = segmentGroup.newCurvePoints
			
			if len(curvePoints) > 0:
				startPos = curvePoints[0]
	
				if distance( m.currentPos(), startPos) > tolerance :
					m.moveZ(safetyHeight)
	
				m.move(startPos)
				m.moveZ(workingHeight)
	
				
				for curvePoint in curvePoints:
					#line optimization
					
					m.move(curvePoint)
				
	
	m.moveZ(safetyHeight)

	gcode = m.getGcode()

	with open(outputFile, "w+") as outfile:
		outfile.write(gcode)

	print "Outputfile written !"
Beispiel #16
0
def solveTriangle(A,B, theta):
    c = distance(A,B)
    iota = math.pi - 2*theta
    a = b = c * math.sin(theta)/math.sin(iota)
    epsilon = theta + math.atan2(A.y - B.y, A.x - B.x)
    cx = A.x - math.cos(epsilon)*a
    cy = A.y - math.sin(epsilon)*a
    return Point(cx, cy)
Beispiel #17
0
def f_vector(database,choice):
    
    # CONSTRUCTING FEATURE VECTORS 

    if choice == 0:
    
        vector = []

        for i in range(len(database)):
        
            temp = []

            dist_d = geometry.distance(database[i][10],database[i][11],database[i][12],database[i][16],database[i][17],database[i][18])
            temp.append(dist_d)
            dist_D = geometry.distance(database[i][4],database[i][5],database[i][6],database[i][16],database[i][17],database[i][18])
            temp.append(dist_D)
            ang_th = geometry.angle(database[i][4]-database[i][10],database[i][5]-database[i][11],database[i][6]-database[i][12],database[i][16]-database[i][10],database[i][17]-database[i][11],database[i][18]-database[i][12])
            temp.append(ang_th) 
            
            if database[i][19] == 'YES':
                temp.append('YES')
                vector.append(temp)                    

            elif database[i][19] == 'NO':
                temp.append('NO')
                vector.append(temp)
            
        return vector     

    elif choice == 1:

        vector = []

        for i in range(len(database)):
            
            temp = []

            dist_d = geometry.distance(database[i][10],database[i][11],database[i][12],database[i][16],database[i][17],database[i][18])
            temp.append(dist_d)
            dist_D = geometry.distance(database[i][4],database[i][5],database[i][6],database[i][16],database[i][17],database[i][18])
            temp.append(dist_D)
            ang_th = geometry.angle(database[i][4]-database[i][10],database[i][5]-database[i][11],database[i][6]-database[i][12],database[i][16]-database[i][10],database[i][17]-database[i][11],database[i][18]-database[i][12])
            temp.append(ang_th)
            vector.append(temp)                   
             
        return vector
 def save_start_game_tick(self, env):
     puck = env.world.puck
     if geometry.distance(puck, shortcuts.rink_center(env)) > 0.1:
         return
     puck_abs_speed = geometry.vector_abs(puck.speed_x, puck.speed_y)
     if puck_abs_speed > 0.1:
         return
     self.game_start_tick = env.world.tick
def goalie_can_save_straight(env, puck=None, player=None, goalie=None):
    if puck is None:
        puck = env.world.puck
    if player is None:
        player = shortcuts.opponent_player(env)
    if goalie is None:
        goalie = shortcuts.goalie(env, player)

    goal_interval = shortcuts.goal_interval(env, player)

    intersection = geometry.ray_interval_intersection(
        puck.x, puck.y, puck.speed_x, puck.speed_y,
        goal_interval[0].x, goal_interval[0].y, goal_interval[1].x, goal_interval[1].y)

    # шайба не летит в ворота
    if intersection is None:
        return True

    if goalie is None:
        return False

    old_puck = puck
    old_goalie = goalie
    for i in range(50):
        next_puck = next_puck_position(env, old_puck)
        next_goalie = next_goalie_position(env, old_goalie, old_puck)
        # print 'next_puck', next_puck.x, next_puck.y
        # print 'next_goalie', next_goalie.x, next_goalie.y

        # HARDCODE
        if geometry.distance(old_puck, next_goalie) <= 50:
            return True
        if geometry.distance(next_puck, next_goalie) <= 50:
            return True

        if shortcuts.im_left(env):
            if next_puck.x > shortcuts.opponent_player(env).net_front:
                return False
        else:
            if next_puck.x < shortcuts.opponent_player(env).net_front:
                return False

        old_puck = next_puck
        old_goalie = next_goalie

    return True
Beispiel #20
0
def transform(
        wheel1: Point,
        wheel2: Point,
        tail: Point,
        scene_center: Point,
):
    """
    :return: (
        robot_position, # position against scene center;
        angle, # angle against scene center;
        distance, # distance to scene center;
        )
    """
    robot_center = midpoint(wheel1, wheel2)

    # finds the tail point's prime and its projection line - the main one
    tail_prime = two_points_90(wheel1, robot_center)
    intersection_line = line(wheel1, wheel2)
    if not pts_same_side(tail, tail_prime, intersection_line):
        tail_prime = two_points_90(wheel2, robot_center)
    main_projection_line = line(tail, tail_prime)

    # finds center line's prime
    center_line = line(scene_center, robot_center)
    side_line = line(tail, wheel1)
    side_intersection = intersection(center_line, side_line)
    if side_intersection:
        side_line_prime = line(tail_prime, wheel1)
    else:
        side_line = line(tail, wheel2)
        side_intersection = intersection(center_line, side_line)
        side_line_prime = line(tail_prime, wheel2)

    # noinspection PyTypeChecker
    side_intersection_projection_line = parallel_line(main_projection_line, side_intersection)
    side_intersection_prime = intersection(side_line_prime, side_intersection_projection_line)
    center_line_prime = line(robot_center, side_intersection_prime)

    # computes position, angle and distance
    center_line_projection = parallel_line(main_projection_line, scene_center)
    center_prime = intersection(center_line_projection, center_line_prime)
    dist = distance(center_prime, robot_center) / distance(robot_center, tail_prime)
    robot_position = robot_center - center_prime
    angle = math.degrees(normalize_angle(
        three_pts_angle(tail_prime, robot_center, center_prime) - math.pi))
    return Object(robot_position, angle, (dist * ROBOT_UNIT))
Beispiel #21
0
def threshold_shape_sizes(shapes):
    # Detect if any corners are within a few pixels of each other. If so,
    # we've screwed up somewhere.
    for shape in shapes:
        for v1, v2 in itertools.combinations(shape.get_vertices(), 2):
            if geometry.distance(v1, v2) < 10:
                shapes.delete_shape_with_vertex(v1)
                break
Beispiel #22
0
 def formatPosition(self, pos, ownPos=None):
     if (ownPos and ownPos['valid']):
         a = (ownPos['lat'], ownPos['lon'])
         b = pos
         return("%1.2fkm %s" % \
           (geometry.distance(a,b),
           geometry.compassPoint(geometry.bearing(a,b))))
     else:
         return ("%f,%f" % (self.lat, self.lon))
Beispiel #23
0
 def formatPosition(self,pos, ownPos = None):
   if(ownPos and ownPos['valid']):
     a = (ownPos['lat'], ownPos['lon'])
     b = pos
     return("%1.2fkm %s" % \
       (geometry.distance(a,b),
       geometry.compassPoint(geometry.bearing(a,b))))
   else:
     return("%f,%f" % (self.lat,self.lon))
Beispiel #24
0
    def _generate_vertices(self):
        # Generate a cylinder centered at axis 0
        length = distance(self.start, self.end)

        # First two points
        self.vertices.append(np.array([self.radius, 0.0, 0.0]))
        self.vertices.append(np.array([self.radius, 0.0, length]))

        z_axis = np.array([0.0, 0.0, 1.0])
        for i in range(1, self.cloves):
            rotmat = rotation_matrix(i * 2 * np.pi / self.cloves,
                                     z_axis)[:3, :3]

            nextbottom = np.dot(rotmat, self.vertices[0])
            nextup = np.dot(rotmat, self.vertices[1])
            self.vertices.append(nextbottom)
            self.vertices.append(nextup)

        # Last two points
        self.vertices.append(np.array([self.radius, 0.0, 0.0]))
        self.vertices.append(np.array([self.radius, 0.0, length]))

        self.vertices = np.array(self.vertices)
        self.indices = xrange(len(self.vertices.flatten()))

        # Normals, this is quite easy they are the coordinate with
        # null z
        for vertex in self.vertices:
            self.normals.append(
                normalized(np.array([vertex[0], vertex[1], 0.0])))

        self.normals = np.array(self.normals)  # Numpyize

        ang = angle_between_vectors(z_axis, self.axis)
        rotmat = rotation_matrix(-ang, vector_product(z_axis,
                                                      self.axis))[:3, :3]

        # Rototranslate the cylinder to the real axis
        self.vertices = np.dot(self.vertices, rotmat.T) - self.end
        self.normals = np.dot(self.normals, rotmat.T)
        # for i, vertex in enumerate(self.vertices):
        #     self.vertices[i] = np.dot(rotmat, vertex) - self.start
        #     self.normals[i] = np.dot(rotmat, self.normals[i])

        # Now for the indices let's generate triangle stuff
        n = self.cloves * 2 + 2
        # Draw each triangle in order to form the cylinder
        a0 = np.array([0, 1, 2, 2, 1, 3])  # first two triangles
        a = np.concatenate([a0 + 2 * i for i in xrange(self.cloves)])
        self.indices = a
        n = self.cloves * 2 * 3
        self.tri_vertex = self.vertices[a].flatten()
        self.tri_normals = self.normals[a].flatten()

        self.vertex_list = pyglet.graphics.vertex_list(
            n, ("v3f", self.tri_vertex), ("n3f", self.tri_normals),
            ("c3B", self.tri_color))
def add_circle_layer(circle_data, ref_point):
    circle_layer = folium.FeatureGroup(name="Reference point " +
                                       str(ref_point))
    for i, crl in enumerate(circle_data):
        circle_layer.add_child(
            folium.Circle(
                location=[crl['Lat'], crl['Lon']],
                fill=False,
                weight=5,
                opacity=0.75,
                radius=geo.distance(crl['ESP-mean']),
                popup="Gateway: " + str(crl['EUI']) + "<br/>" + "Variance: " +
                str(geo.deltax(crl['ESP-mean'], crl['ESP-var'])) + "<br/>" +
                "+1 sigma: " +
                str(geo.distance(crl['ESP-mean']) - crl['ESP-var']) +
                "m<br/>" + "-1 sigma: " +
                str(geo.distance(crl['ESP-mean']) + crl['ESP-var']) +
                "m<br/>"))

        circle_layer.add_child(
            folium.Circle(
                location=[crl['Lat'], crl['Lon']],
                fill=False,
                weight=3,
                opacity=0.5,
                radius=geo.distance(crl['ESP-mean'] - 3 * crl['ESP-var']),
                popup="Gateway: " + str(crl['EUI']) + "<br/>" + "+3Sigma"))
        circle_layer.add_child(
            folium.Circle(
                location=[crl['Lat'], crl['Lon']],
                fill=False,
                weight=3,
                opacity=0.5,
                radius=geo.distance(crl['ESP-mean'] + 3 * crl['ESP-var']),
                popup="Gateway: " + str(crl['EUI']) + "<br/>" + "-3Sigma"))

    #add trilateration point
    circle_layer.add_child(
        folium.Marker(location=coord_list[ref_point - 3],
                      popup="Ref point: " + str(ref_point),
                      icon=folium.Icon(color='darkred',
                                       prefix='fa',
                                       icon='angle-double-down')))
    map.add_child(circle_layer)
Beispiel #26
0
    def intersection(self):
        """Este método se encarga de recopilar toda la información, para posteriormente
           aplicarle la lógica del plugin.

           Para que el usuario pueda realizar esta operación, necesariamente, tienen
           que estar cargadas la capa de ejes, y la capa de secciones transversales.
        """
        try:
            secciones = QgsMapLayerRegistry.instance().mapLayersByName(
                "secciones")[0]
            eje = QgsMapLayerRegistry.instance().mapLayersByName("ejes")[0]
        except IndexError:
            self.errorDialog(
                u'No se encontraron algunas de las capas necesarias para realizar esta operación.',
                u'Asegurate de agregar la capa de secciones, y la capa del eje con la opción Configurar Fondo.'
            )
            return

        work_layer = self.addFeature(secciones)

        try:
            """En caso de que existan secciones temporales, se combinaran con la
               capa de secciones, para crear la capa work_layer"""
            temp = QgsMapLayerRegistry.instance().mapLayersByName("temp")[0]

            for new_feature in temp.getFeatures():
                segements = geometry.getSegments(work_layer)
                point = geometry.intersectionLayerGeometry(
                    eje, new_feature.geometry())
                if point is None: continue
                idx = self.place(segements, point)
                # print 'IDX: ', idx
                work_layer = self.addFeature(work_layer, new_feature, idx)

        except IndexError:
            pass

        #Mostrar la capa de trabajo work_layer
        QgsMapLayerRegistry.instance().addMapLayer(work_layer)

        #Crar un DataFrame de pandas con la tabla de atributos de la capa de trabajo
        table = [row.attributes() for row in work_layer.getFeatures()]
        field_names = [field.name() for field in work_layer.pendingFields()]
        pd_frame = pandas.DataFrame(table, columns=field_names)
        print pd_frame

        #Crear un DataFrame de pandas con las distancias de la sucesión de secciones
        points = geometry.intersectionPoints(eje, work_layer)

        distances = [0]
        for i in xrange(len(points) - 1):
            distances.append(geometry.distance(points[i], points[i + 1]))
        # print distances

        pd_dataframe = pandas.DataFrame(distances, columns=['Distancia'])
        print pd_dataframe
Beispiel #27
0
    def _generate_vertices(self):
        # Generate a cylinder centered at axis 0
        length = distance(self.start, self.end)
        
        # First two points
        self.vertices.append(np.array([self.radius, 0.0, 0.0]))
        self.vertices.append(np.array([self.radius, 0.0, length]))
        
        z_axis = np.array([0.0, 0.0, 1.0])
        for i in range(1, self.cloves):
            rotmat = rotation_matrix( i * 2*np.pi/self.cloves, z_axis)[:3,:3]
            
            nextbottom = np.dot(rotmat, self.vertices[0])
            nextup = np.dot(rotmat, self.vertices[1])
            self.vertices.append(nextbottom)
            self.vertices.append(nextup)
        
        # Last two points
        self.vertices.append(np.array([self.radius, 0.0, 0.0]))
        self.vertices.append(np.array([self.radius, 0.0, length]))
        
        self.vertices = np.array(self.vertices)
        self.indices = xrange(len(self.vertices.flatten()))

        # Normals, this is quite easy they are the coordinate with
        # null z
        for vertex in self.vertices:
            self.normals.append(normalized(np.array([vertex[0], vertex[1], 0.0])))
        
        self.normals = np.array(self.normals) # Numpyize
        
        ang = angle_between_vectors(z_axis, self.axis)
        rotmat = rotation_matrix(-ang, vector_product(z_axis, self.axis))[:3,:3]
        
        # Rototranslate the cylinder to the real axis
        self.vertices = np.dot(self.vertices, rotmat.T) - self.end
        self.normals = np.dot(self.normals, rotmat.T)
        # for i, vertex in enumerate(self.vertices):
        #     self.vertices[i] = np.dot(rotmat, vertex) - self.start
        #     self.normals[i] = np.dot(rotmat, self.normals[i])
        
        # Now for the indices let's generate triangle stuff
        n = self.cloves * 2 + 2
        # Draw each triangle in order to form the cylinder
        a0 = np.array([0,1,2, 2,1,3]) # first two triangles
        a = np.concatenate([a0 + 2*i for i in xrange(self.cloves)])
        self.indices = a
        n = self.cloves * 2 * 3
        self.tri_vertex = self.vertices[a].flatten()
        self.tri_normals = self.normals[a].flatten()
        
        self.vertex_list = pyglet.graphics.vertex_list(n,
                                                       ("v3f", self.tri_vertex),
                                                       ("n3f", self.tri_normals),
                                                       ("c3B", self.tri_color))
Beispiel #28
0
    def pro(self):
        """Cálcula las distancias entre los puntos de intersección de la capa de ejes, y la capa de secciones."""
        points = geometry.intersectionPoints(self.eje, self.secciones)
        distances = [0]
        for i in xrange(1, len(points)):
            #Precisión de 4 digitos, para evitar problemas con matplotlib
            dist = geometry.distance(points[i],
                                     points[i - 1]) + distances[i - 1]
            distances.append(float(format(dist, '.4f')))

        return points, distances
Beispiel #29
0
 def update_bullets(self, elapsed_time):
     self.bullets = [b for b in self.bullets if b.active]
     for obj in self.bullets:
         obj.update(elapsed_time)
         for enemy in self.enemies:
             if enemy.alive and geometry.distance(obj.position, enemy.position) < 30:
                 obj.active = False
                 enemy.take_damages(obj.power)
                 if not enemy.alive:
                     self.player.money += 30
                 break
 def f(point):
     nfc = shortcuts.net_front_center(env, shortcuts.opponent_player(env))
     angles = [
         min(geometry.degree_to_rad(110), geometry.ray_ray_angle(oh, env.me, point))
         for oh in shortcuts.opponent_field_hockeyists(env)
         if geometry.distance(oh, nfc) > 300
     ]
     ticks_to_reach_point = assessments.ticks_to_reach_point(env, env.me, point)
     if not angles:
         return -ticks_to_reach_point
     return geometry.rad_to_degree(min(angles)) - ticks_to_reach_point / 100
Beispiel #31
0
def get_std(stddev_factor, points, std_is_distance):
    p_near = points[0, :-1].reshape(-1, 1)
    p_far = points[-1, :-1].reshape(-1, 1)
    if std_is_distance:
        dists = distance(p_near, p_far)
        std = stddev_factor * dists / len(points)
    else:
        std = stddev_factor * ((p_near - p_far)**2).sum()
        std /= len(points)

    return std
Beispiel #32
0
def gaussianVolume(shape, position, amplitude, sigma):
    """Returns 3D volume with Gaussian function values written into it."""
    # sigma is fatness
    volume = zeros(shape, defaultType)
    for x in range(0, shape[0]):
        for y in range(0, shape[1]):
            for z in range(0, shape[2]):
                dist = geometry.distance(position, array([x,y,z]))
                #volume[x,y,z] = dist * 20
                volume[x,y,z] = gaussian(dist, amplitude, sigma)
    return volume
def ticks_to_reach_point(env, hockeyist, point):
    distance = geometry.distance(hockeyist, point)
    if distance < 0.01:
        return 0
    angle = hockeyist.get_angle_to_unit(point)
    v0 = (
        hockeyist.speed_x * (point.x - hockeyist.x) +
        hockeyist.speed_y * (point.y - hockeyist.y)
    ) / distance

    a = env.game.hockeyist_speed_up_factor
    ticks_for_move = prediction.count_n_by_x(0, v0, a, distance)
    return abs(angle) / env.game.hockeyist_turn_angle_factor + ticks_for_move
    def pass_condition(self, env, strike_point):
        if env.world.tick - self.history.game_start_tick <= 75:
            return True

        pass_taker = self.count_pass_taker(env)
        if geometry.distance(self.hwp, pass_taker) > 200:
            for oh in shortcuts.opponent_field_hockeyists(env):
                if geometry.interval_point_distance(self.hwp, strike_point, oh) < 60:
                    return True

        if any(geometry.point_in_convex_polygon(self.hwp, p) for p in self.precount.dead_polygons):
            return True

        return False
Beispiel #35
0
    def __init__(self, plu, pru, pld, prd, center, diagonal):
        """Receives the four corners of the cell, center point and diagonal.

        If center or diagonal are None, they are automatically computed
        from the values of the corners.

        """
        self.plu = plu
        self.pru = pru
        self.pld = pld
        self.prd = prd
        if center is not None:
            self.center = center
        else:
            self.center = geometry.rect_center(plu, pru, pld, prd)
        if diagonal is not None:
            self.diagonal = diagonal
        else:
            self.diagonal = geometry.distance(plu, prd)
Beispiel #36
0
    def __init__(self, plu, pru, pld, prd, center, diagonal):
        """Receives the four corners of the cell, center point and diagonal.

        If center or diagonal are None, they are automatically computed
        from the values of the corners.

        """
        self.plu = plu
        self.pru = pru
        self.pld = pld
        self.prd = prd
        if center is not None:
            self.center = center
        else:
            self.center = geometry.rect_center(plu, pru, pld, prd)
        if diagonal is not None:
            self.diagonal = diagonal
        else:
            self.diagonal = geometry.distance(plu, prd)
Beispiel #37
0
def database(dirs,path):

    # ITERATING OVER FILES 

    database_ = []

    for file in dirs:
        
        files = []
        dfNH=[]
        dfSEG=[]

        # PARSING DATA FILES
        
        data = parser.parse_data(os.path.join(path,file))
        files.append(file)
        
        for i in range(len(data)):
            if data[i][0] == 'N':
                res_id = data[i][2]
                for j in range(len(data)):
                    if data[j][0] == 'H' and data[j][2] == res_id : 
                        dfNH.append(data[j] + data[i]) 
                        break
                        
        for j in range(len(data)):
            if data[j][0] == 'SD': 
                dfSEG.append(files+data[j])

        # REMOVING IRRELEVANT DATA ENTRIES

        for i in range(len(dfSEG)):
            for j in range(len(dfNH)):
                dist= geometry.distance(dfSEG[i][4],dfSEG[i][5],dfSEG[i][6],dfNH[j][3],dfNH[j][4],dfNH[j][5])
                if dist < 4.2: 
                    database_.append(dfSEG[i]+dfNH[j])


    fve = f_vector(database_,1)
    rv = [database_,fve]
    return rv
Beispiel #38
0
    def gps_listener(self, data):
        """ROS callback for the gps topic"""
        #Important fields from data
        latitude = data.data[0]  # In degrees
        longitude = data.data[1]
        self.time_step = [data.data[10]]
        #psi = data.data[7] # psi = heading in radians
        #velocity = data.data[8] #GPS velocity
        # Converts lat long to x,y
        x, y = requestHandler.math_convert(float(latitude), float(longitude))

        #Only update if distance from last gps point is less than 20
        count = count + 1
        old_xy = (self.gps_xy)
        #print ("old xy ", old_xy)
        #print ("new xy ", (x,y))
        #print ("distance ", geometry.distance(old_xy, (x,y)))
        if count < 10:
            self.gps_xy = [x, y]
        elif (old_xy != [101, 3]) and geometry.distance(old_xy, (x, y)) < 20:
            self.gps_xy = [x, y]
Beispiel #39
0
    def on_touch_move(self, touch):
        if self.parent is None:
            return

        if touch.grab_current is self:
            next_node = [
                touch.pos[0] - nodesize / 2,
                touch.pos[1] - nodesize / 2
            ]

            if next_node[0] <= self.x:
                self.node.pos = [self.x, next_node[1]]
            elif next_node[0] >= self.right:
                self.node.pos = [self.right, next_node[1]]
            else:
                self.node.pos = next_node

            ball = self.parent.ball.circle.pos

            if distance(ball, self.node.pos) <= ballsize + nodesize:
                self.parent.update()
Beispiel #40
0
    def get_cell_clicked(self, point):
        """Determines the cell to which the given point corresponds.

        Returns (num_question, num_choice) or None if no cell corresponds.

        """
        min_dst = float('inf')
        num_question = None
        num_choice = None
        closest_cell = None
        for i, cells in enumerate(self.answer_cells):
            for j, cell in enumerate(cells):
                dst = geometry.distance(point, cell.center)
                if dst < min_dst:
                    min_dst = dst
                    num_question = i
                    num_choice = j + 1
                    closest_cell = cell
        if closest_cell is not None and min_dst <= closest_cell.diagonal / 2:
            return (num_question, num_choice)
        else:
            return (None, None)
Beispiel #41
0
    def get_cell_clicked(self, point):
        """Determines the cell to which the given point corresponds.

        Returns (num_question, num_choice) or None if no cell corresponds.

        """
        min_dst = float('inf')
        num_question = None
        num_choice = None
        closest_cell = None
        for i, cells in enumerate(self.answer_cells):
            for j, cell in enumerate(cells):
                dst = geometry.distance(point, cell.center)
                if dst < min_dst:
                    min_dst = dst
                    num_question = i
                    num_choice = j + 1
                    closest_cell = cell
        if closest_cell is not None and min_dst <= closest_cell.diagonal / 2:
            return (num_question, num_choice)
        else:
            return (None, None)
Beispiel #42
0
    def pos(self, vel_name, conc_name, flag=0):
        """Aplica el modelo matemático sobre la información.

        :param vel_name: Nombre de la columna en la que se encuetra la información de la velocidad.
        :type vel_name: str

        :param conc_name: Nombre de la columna en la que se encuetra la información de los puntos de concentracion.
        :type conc_name: str

        :param flag: Bandera que indica que gráfica se va a desplegar.
        :type falg: bool
        """

        #Obtener los valores de concentración de la columna de concentración
        self.concentration_values = self.get_float_column(
            self.work_layer, conc_name)
        #Obtener los valores de concentración de la columna de velocidad
        self.vel_values = self.get_float_column(self.work_layer, vel_name)

        points = geometry.intersectionPoints(self.eje, self.work_layer)
        distances = []
        for i in xrange(len(points)):
            #Precisión de 4 digitos, para evitar problemas con matplotlib
            dist = geometry.distance(points[0], points[i])
            distances.append(float(format(dist, '.4f')))

        dx = np.array(distances)
        cn = np.array(self.concentration_values)

        c_i = np.array([dx, cn]).T
        va = np.array(self.vel_values)
        cd = np.array([1.5 for x in self.vel_values])

        c_i_copy = copy.deepcopy(c_i)
        va_copy = copy.deepcopy(va)
        cd_copy = copy.deepcopy(cd)

        self.apply_modelling(c_i_copy, va_copy, cd_copy, flag)
    def pass_condition(self, env, strike_point):
        if env.world.tick - self.game_start_tick <= 75:
            return True

        collega = filter(lambda h: h.id != env.me.id, shortcuts.my_field_hockeyists(env))[0]
        net_center = shortcuts.net_front_center(env, shortcuts.opponent_player(env))
        if geometry.distance(collega, env.me) > 200:
            for oh in shortcuts.opponent_field_hockeyists(env):
                # my_angle = geometry.ray_ray_angle(env.me, strike_point, net_center)
                # o_angle = geometry.ray_ray_angle(oh, strike_point, net_center)
                # my_distance = geometry.distance(env.me, strike_point)
                # o_distance = geometry.distance(oh, strike_point)

                # if my_angle > o_angle and my_distance > o_distance:
                #     return True

                if geometry.interval_point_distance(env.me, strike_point, oh) < 60:
                    return True

        if any(geometry.point_in_convex_polygon(env.me, p) for p in self.dead_polygons):
            return True

        return False
Beispiel #44
0
    def _generate_vertices(self):
        length = distance(self.start, self.end)
        # Generate the arrow along z-axis and then rotate it

        #   ____|\
        #  |____  *
        #       |/

        
        # First the arrow rectangle
        width = self.width
        headl = width*2.0
        headw = width*2.0
        
        a = np.array([-width/2, 0.0, 0.0])
        b = np.array([+width/2, 0.0, 0.0])
        
        c = np.array([-width/2, 0.0, length - headl])
        d = np.array([+width/2, 0.0, length - headl])
        
        # Now the arrow head
        t1 = np.array([-headw/2, 0.0, length - headl])
        t2 = np.array([+headw/2, 0.0, length - headl])
        t3 = np.array([0.0, 0.0, length])
        
        self.vertices = np.array([a,b,c,d,t1,t2,t3])
        self.normals =  np.array([[0.0, 1.0, 0.0]]*len(self.vertices))

        # Orient it
        self.rotate([0.0, 0.0, 1.0], self.orientation)
        
        # Align with start-end direction
        ang = angle_between_vectors(np.array([0.0, 0.0, 1.0]), self.axis)
        
        normal = np.cross(self.axis, np.array([0.0, 0.0, 1.0]))
        self.rotate(normal, ang)
        self.translate(self.end)
Beispiel #45
0
    def _generate_vertices(self):
        length = distance(self.start, self.end)
        # Generate the arrow along z-axis and then rotate it

        #   ____|\
        #  |____  *
        #       |/

        # First the arrow rectangle
        width = self.width
        headl = width * 2.0
        headw = width * 2.0

        a = np.array([-width / 2, 0.0, 0.0])
        b = np.array([+width / 2, 0.0, 0.0])

        c = np.array([-width / 2, 0.0, length - headl])
        d = np.array([+width / 2, 0.0, length - headl])

        # Now the arrow head
        t1 = np.array([-headw / 2, 0.0, length - headl])
        t2 = np.array([+headw / 2, 0.0, length - headl])
        t3 = np.array([0.0, 0.0, length])

        self.vertices = np.array([a, b, c, d, t1, t2, t3])
        self.normals = np.array([[0.0, 1.0, 0.0]] * len(self.vertices))

        # Orient it
        self.rotate([0.0, 0.0, 1.0], self.orientation)

        # Align with start-end direction
        ang = angle_between_vectors(np.array([0.0, 0.0, 1.0]), self.axis)

        normal = np.cross(self.axis, np.array([0.0, 0.0, 1.0]))
        self.rotate(normal, ang)
        self.translate(self.end)
Beispiel #46
0
 def touching_point(self, point):
     if geometry.distance((self.x, self.y), point) < self.radius:
         return True
     return False
Beispiel #47
0
# 載入內建的 sys 模組並取得資訊
# import sys as system
# print(system.platform)
# print(system.maxsize)
# 建立geometry模組, 載入並使用
# import geometry
# result=geometry.distance(1,1,5,5)
# print(result)
# result=geometry.slope(1,2,5,6)
# print(result)
# 調整搜尋模組的路徑
import sys
sys.path.append("mod")  #在模組的搜尋紀錄中心新增
print(sys.path)  #印出模組的搜尋路徑
import geometry
print(geometry.distance(3, 3, 3, 3))
print(geometry.slope(1, 2, 5, 6))
def do_distance(x1, y1, x2, y2):
    print(end="The distance between ")
    print_point(x1, y1)
    print(end=" and ")
    print_point(x2, y2)
    print("is ", distance(x1, y1, x2, y2))
Beispiel #49
0
def preview_detection(img, g):
    gf = np.float32(g)

    dst = cv2.cornerHarris(gf,th+8,BSHD,kHD)
    dst = cv2.dilate(dst,None)

    g[dst>0.02*dst.min()]=0

    line_endpoints = []
    ellipses = []

    x = 0

    contours, hierarchy = cv2.findContours(g, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for c in contours:
        if cv2.contourArea(c) > 100:
            ellipse = cv2.fitEllipse(c)

            (x,y), (minor_axis, major_axis), angle = ellipse
            ecc = major_axis/minor_axis

            if ecc > 5:
                if abs(angle-90) > 30:
                    # Vertical
                    # cv2.drawContours(img, c, -1, (0, 0, 255), 1)

                    # Find extrema points
                    # via http://opencv-python-tutroals.readthedocs.org/en/...
                    #       latest/py_tutorials/py_imgproc/py_contours/...
                    #       py_contour_properties/py_contour_properties.html
                    topmost = tuple(c[c[:,:,1].argmin()][0])
                    bottommost = tuple(c[c[:,:,1].argmax()][0])

                    line_endpoints.append((topmost, bottommost))

                    # cv2.line(img, topmost, bottommost, (255, 255, 0), 1)
                else:
                    # Horizontal
                    # cv2.drawContours(img, c, -1, (0, 255, 255), 1)

                    leftmost = tuple(c[c[:,:,0].argmin()][0])
                    rightmost = tuple(c[c[:,:,0].argmax()][0])

                    line_endpoints.append((leftmost, rightmost))

                    # cv2.line(img, leftmost, rightmost, (0, 255, 255), 1)
            elif ecc < 1.5: # Need to draw pretty carefully to not pass 1.5
                # Circles
                # cv2.drawContours(img, c, -1, (255, 0, 0), 1)
                cv2.ellipse(img, ellipse, (0, 255, 255), 2)
                # ellipses.append(ellipse)

                maj_x = x + major_axis/2*np.sin(np.radians(angle))
                maj_y = y + major_axis/2*np.cos(np.radians(angle))
                min_x = x + minor_axis/2*np.sin(np.radians(90+angle))
                min_y = y + minor_axis/2*np.cos(np.radians(90+angle))
                cv2.line(img, (int(x), int(y)), (int(maj_x), int(maj_y)), (255, 0, 0), 2)
                cv2.line(img, (int(x), int(y)), (int(min_x), int(min_y)), (0, 255, 0), 2)

                e = ((x, y), (maj_x, maj_y), (min_x, min_y))
                ellipses.append(e)
            else:
                # Some weird line shape
                #cv2.drawContours(img, c, -1, (255, 0, x), 2)
                x += 125
                pass
        else:
            # Small objects
            # cv2.drawContours(img, c, -1, (0, 255, 0), 1)
            pass

    linear_shapes = ShapeList()

    for (a, b) in line_endpoints:
        cv2.line(img, a, b, (255, 255, 0), 1)
        for (c, d) in line_endpoints:
            if (a, b) != (c, d):
                for (m, n) in itertools.combinations([a, b, c, d], 2):
                    if geometry.distance(m, n) < DSTCONNECT:
                        # Likely found two line segments that should connect
                        (x1, y1) = np.float32(a)
                        (x2, y2) = np.float32(b)
                        (x3, y3) = np.float32(c)
                        (x4, y4) = np.float32(d)

                        # Detect the intersection point (surely can be nicer!)
                        px_n = np.linalg.det(np.array(
                            [[np.linalg.det(np.array([[x1, y1], [x2, y2]])),
                              np.linalg.det(np.array([[x1, 1 ], [x2, 1 ]]))],
                             [np.linalg.det(np.array([[x3, y3], [x4, y4]])),
                              np.linalg.det(np.array([[x3, 1 ], [x4, 1 ]]))]]))
                        py_n = np.linalg.det(np.array(
                            [[np.linalg.det(np.array([[x1, y1], [x2, y2]])),
                              np.linalg.det(np.array([[y1, 1 ], [y2, 1 ]]))],
                             [np.linalg.det(np.array([[x3, y3], [x4, y4]])),
                              np.linalg.det(np.array([[y3, 1 ], [y4, 1 ]]))]]))
                        p_d  = np.linalg.det(np.array(
                            [[np.linalg.det(np.array([[x1, 1 ], [x2, 1]])),
                              np.linalg.det(np.array([[y1, 1 ], [y2, 1 ]]))],
                             [np.linalg.det(np.array([[x3, 1 ], [x4, 1]])),
                              np.linalg.det(np.array([[y3, 1 ], [y4, 1 ]]))]]))

                        # Should probably validate that there is an intersection
                        # before crashing here by division with zero. It is
                        # extraordinarily unlikely, though.
                        p = tuple(np.int32((px_n/p_d, py_n/p_d)))
                        if geometry.distance(m, p) < DSTCONNECT and geometry.distance(n, p) < DSTCONNECT:
                            cv2.line(img, m, p, (0, 0, 255), 1)
                            cv2.line(img, n, p, (0, 0, 255), 1)
                            # linear_shapes.add((a, b), (c, d), extra=p)
                            linear_shapes.add((a, b), (c, d), p)

    recognize_linear_shapes(img, linear_shapes)

    return (linear_shapes, ellipses)
         
         unit = registry.getById(playerMove.unitid)
         path_pairs = [(playerMove.path[i-1],playerMove.path[i]) for i in range(1,len(playerMove.path))]
         path_taken = [playerMove.path[0]]
         for start,end in path_pairs:
             intersecting = []
             for other in registry.getAllByType(Unit):
                 if unit!=other:
                     if geometry.shipsWillCollideOnSegment(start, end, unit, other):
                         intersecting.append(other)
             
             if not intersecting:
                 unit.setLocation(end)
                 path_taken.append(end)
             else:
                 shortest = geometry.distance(start,end)
                 shortest_point = end
                 
                 for other in intersecting:
                     pt = geometry.whereWillItStop(start, end, unit, other)
                     if geometry.distance(start,pt)<shortest:
                         shortest = geometry.distance(start,pt)
                         shortest_point = pt
                     
                 unit.setLocation(shortest_point)
                 path_taken.append(shortest_point)
                 break
         
         self.results[unit.gid] = path_taken
     
 def getResults(self):
 def classify(self, test_point):
     nearest_tuple = min(
         self.st, key=lambda tup: distance(tup[0], test_point))
     return nearest_tuple[0]
Beispiel #52
0
import sys
print(sys.platform)
print(sys.maxsize)
print(sys.path)
sys.path.append("modules")
print(sys.path)
import geometry
result = geometry.distance(1, 1, 5, 5)
print(result)
result = geometry.slope(1, 2, 5, 6)
print(result)
 def its_dangerous(self, env):
     return (
         any(geometry.point_in_convex_polygon(env.world.puck, p) for p in self.weak_polygons)
         or geometry.distance(env.world.puck, self.defence_point) < 120
     )
 def leave_goal_condition(self, env):
     return geometry.distance(self.defence_point, env.world.puck) <= 200
Beispiel #55
0
 def dist_to_bike(path):
     """Returns the distance between a path and the given point"""
     nearest_pt = geometry.nearest_point_on_path(path, point)
     return geometry.distance(nearest_pt, point)
Beispiel #56
0
def rectify_shapes(img, shapes, ellipses):
    largest = find_largest_container(shapes)

    if not largest:
        return None

    # Order the vertices
    vs = reorder_quadrilater_vertices(largest.get_vertices())

    (x0, y0) = vs[0]
    (x1, y1) = vs[1]
    (x2, y2) = vs[2]
    (x3, y3) = vs[3]

    X0 = X1 = 0
    X2 = X3 = 10
    Y0 = Y2 = 8
    Y1 = Y3 = 0

    g = np.matrix(
        [
            [x0, y0, 1, 0, 0, 0, -X0 * x0, -X0 * y0],
            [0, 0, 0, x0, y0, 1, -Y0 * x0, -Y0 * y0],
            [x1, y1, 1, 0, 0, 0, -X1 * x1, -X1 * y1],
            [0, 0, 0, x1, y1, 1, -Y1 * x1, -Y1 * y1],
            [x2, y2, 1, 0, 0, 0, -X2 * x2, -X2 * y2],
            [0, 0, 0, x2, y2, 1, -Y2 * x2, -Y2 * y2],
            [x3, y3, 1, 0, 0, 0, -X3 * x3, -X3 * y3],
            [0, 0, 0, x3, y3, 1, -Y3 * x3, -Y3 * y3],
        ]
    )
    v = np.matrix([X0, Y0, X1, Y1, X2, Y2, X3, Y3]).T
    M = g.I * v

    # Rebuild new shapes with rectified vertices
    rectified_linear_shapes = []
    for shape in shapes:
        if shape.is_complete():
            new_shape = []
            for v in shape.get_vertices():
                new_shape.append(apply_homography(M, v))
            rectified_linear_shapes.append(new_shape)

    rectified_ellipses = []
    for ellipse in ellipses:
        c, majp, minp = ellipse

        c_h = apply_homography(M, c)
        majp_h = apply_homography(M, majp)
        minp_h = apply_homography(M, minp)

        majlen = geometry.distance(c_h, majp_h)
        minlen = geometry.distance(c_h, minp_h)

        theta = 0
        dy = majp_h[1] - c_h[1]
        dx = majp_h[0] - c_h[0]
        if dx != 0:
            theta = np.degrees(np.arctan(dy / dx))

        recte = (c_h, (majlen, minlen), theta)
        print recte
        rectified_ellipses.append(recte)

    return (rectified_linear_shapes, rectified_ellipses)
Beispiel #57
0
def make_route_waypoints(from_loc, to_loc, flight_level, beacons):
    """Makes all route waypoints in Kramax AutoPilot format."""
    def add_intermediate_points(
        position,
        prev_beacon_name,
        beacon_name,
        beacon,
        beacon_alt,
        min_distance=0,
    ):
        """Helper function to add beacon altitude change point."""
        def normalize_beacon_name(name):
            if not name:
                return ''
            if name.endswith('-NDB'):
                return name[:-3]
            return name + '-'

        alt = position[2]
        if alt < beacon_alt:
            slope_name, tang = 'ASC', ASC_TANG
            fl_level_needed = (alt < flight_level
                               and flight_level <= beacon_alt)
        else:
            slope_name, tang = 'DESC', -DESC_TANG
            fl_level_needed = (alt > flight_level
                               and flight_level >= beacon_alt)
        if fl_level_needed:
            name = normalize_beacon_name(prev_beacon_name) + 'FL-{}'.format(
                slope_name)
            intermediate = geometry.step_to(position, beacon,
                                            (flight_level - alt) / tang)
            points.append(point_to_params(name, intermediate,
                                          alt=flight_level))
            alt = flight_level
        if beacon_alt != alt:
            name = normalize_beacon_name(beacon_name) + slope_name
            distance = max(min_distance, (beacon_alt - alt) / tang)
            intermediate = geometry.step_to(beacon, position, distance)
            points.append(point_to_params(name, intermediate, alt=alt))

    points = []

    runway = from_loc.runways[0]
    takeoff_asl = runway[1][2]
    points.append(
        point_to_params('TAKEOFF',
                        runway[1],
                        alt=(takeoff_asl + TAKEOFF_ALTITUDE)))

    position = geometry.step_to(runway[1], runway[0],
                                -TAKEOFF_STRAIGHT_UNTIL_ALTITUDE / ASC_TANG)
    position = position + type(position)(
        [takeoff_asl + TAKEOFF_STRAIGHT_UNTIL_ALTITUDE])
    points.append(point_to_params('ASCENT', position))

    last_beacon_position = beacons[-1][1] if beacons else position
    landing_point, opposite_end = utils.select_runway(to_loc,
                                                      last_beacon_position)

    iaf_point, iaf_alt = _make_glideslope_point(landing_point, opposite_end,
                                                IAF_DISTANCE)
    faf_point, faf_alt = _make_glideslope_point(landing_point, opposite_end,
                                                FAF_DISTANCE)
    flare_point, flare_alt = _make_glideslope_point(landing_point,
                                                    opposite_end,
                                                    FLARE_DISTANCE)

    beacon_distances = []
    dist_position = runway[1]
    for _, beacon in beacons:
        beacon_distances.append(geometry.distance(dist_position, beacon))
        dist_position = beacon
    beacon_distances.append(geometry.distance(dist_position, landing_point))

    if not beacons:
        asc_dist = (flight_level - position[2] - 0.1) / ASC_TANG
        fake_beacon = geometry.step_to(position, iaf_point, asc_dist)
        beacons = [('FL-ASC', fake_beacon + type(fake_beacon)([0]))]

    prev_beacon_name = None
    for beacon_name, beacon in beacons:
        asc_alt = position[2] + ASC_TANG * geometry.distance(position, beacon)
        desc_alt = position[2] - DESC_TANG * geometry.distance(
            position, beacon)
        faf_asc_alt = faf_alt + DESC_TANG * geometry.distance(
            faf_point, beacon)
        beacon_alt = max(beacon[2], desc_alt,
                         min(asc_alt, faf_asc_alt, flight_level))
        if ((beacon_alt > position[2] and beacon_alt < asc_alt)
                or (beacon_alt < position[2] and beacon_alt > desc_alt)):
            add_intermediate_points(position, prev_beacon_name, beacon_name,
                                    beacon, beacon_alt)
        position = beacon[:2] + type(beacon)([beacon_alt])
        points.append(point_to_params('{}'.format(beacon_name), position))
        prev_beacon_name = beacon_name

    if geometry.distance(position, landing_point) > 1.25 * IAF_DISTANCE:
        desc_alt = position[2] - DESC_TANG * geometry.distance(
            position, iaf_point)
        iaf_alt = max(desc_alt, min(iaf_alt, flight_level))
        if iaf_alt > desc_alt:
            add_intermediate_points(
                position,
                prev_beacon_name,
                'IAF',
                iaf_point,
                iaf_alt,
                min_distance=MIN_IAF_LEVEL_DISTANCE,
            )
        points.append(
            point_to_params('IAF', iaf_point, alt=iaf_alt, marker='IAF'))
    else:
        points[-1].append(('IAF', 'true'))

    points.append(point_to_params('FAF', faf_point, alt=faf_alt, marker='FAF'))
    points.append(
        point_to_params('FLARE', flare_point, alt=flare_alt, marker='RW'))
    points.append(point_to_params('STOP', opposite_end, marker='Stop'))
    return points, beacon_distances
Beispiel #58
0
 def distanceFrom(self, pos):
     a = (pos['lat'], pos['lon'])
     b = (self.lat, self.lon)
     self.d = geometry.distance(a, b)
     return (self.d)
Beispiel #59
0
 def distanceFrom(self,pos):
   a = (pos['lat'], pos['lon'])
   b = (self.lat,self.lon)
   self.d = geometry.distance(a,b)
   return(self.d)
Beispiel #60
0
# 載入內建的 sys 模組並取得資訊
# import sys as system
# print(system.platform)
# print(system.maxsize)

# 建立 geometry 模組, 載入使用
# import geometry
# result=geometry.distance(1,1,5,5)
# print(result)
# result=geometry.slope(1,2,5,6)
# print(result)

# 調整搜尋模組的路徑
import sys
sys.path.append("modules")  # 在模組的搜尋路徑列表中【新增路徑】
print(sys.path)  # 印出模組的搜尋路徑列表
print("-" * 50)
import geometry
print(geometry.distance(1, 1, 5, 5))