def main(argv): input_file = "" output_file = "" # First we attempt to get the options from the command line try: options, args = getopt.getopt(argv, "i:o:h") except getopt.GetoptError: print( """Call via `python poly_calc.py -i <input_file> -o <output_file>`\n Use `python poly_calc.py -h` for help""") # exit status 2 for command line error sys.exit(2) # Now we check what options were entered and act appropriately for option, argument in options: if option == "-h": print("Call the script using:") print(" python poly_calc.py -i <input_file> -o <output_file>") print("The following flags are used:") print(" -i must be by the input file name") print(" -o can be followed by the output file name if desired") if option == "-i": input_file = argument if option == "-o": output_file = argument # Ensure that there is input data if input_file == "": print("An input file must be specified") else: data = Vector() # Holds all of the lines out of the input file stack = Stack() # Used to store the Polynomials and perform operations # Read all of the lines out of the file with open(input_file) as f: for line in f: data.append(line.strip()) for line in data: if line == "+": p1 = stack.top() stack.pop() p2 = stack.top() stack.pop() stack.push(p1 + p2) elif line == "-": p1 = stack.top() stack.pop() p2 = stack.top() stack.pop() stack.push(p1 - p2) elif line == "*": p1 = stack.top() stack.pop() p2 = stack.top() stack.pop() stack.push(p1 * p2) else: stack.push(Polynomial(line)) if output_file != "": with open(output_file, 'w+') as f: print(stack.top(), file=f) else: print(stack.top())
def main(argv): input_file = "" output_file = "" # First we attempt to get the options from the command line try: options, args = getopt.getopt(argv, "i:o:h") except getopt.GetoptError: print("""Call via `python poly_calc.py -i <input_file> -o <output_file>`\n Use `python poly_calc.py -h` for help""") # exit status 2 for command line error sys.exit(2) # Now we check what options were entered and act appropriately for option, argument in options: if option == "-h": print("Call the script using:") print(" python poly_calc.py -i <input_file> -o <output_file>") print("The following flags are used:") print(" -i must be by the input file name") print(" -o can be followed by the output file name if desired") if option == "-i": input_file = argument if option == "-o": output_file = argument # Ensure that there is input data if input_file == "": print("An input file must be specified") else: data = Vector() # Holds all of the lines out of the input file stack = Stack() # Used to store the Polynomials and perform operations # Read all of the lines out of the file with open(input_file) as f: for line in f: data.append(line.strip()) for line in data: if line == "+": p1 = stack.top() stack.pop() p2 = stack.top() stack.pop() stack.push(p1 + p2) elif line == "-": p1 = stack.top() stack.pop() p2 = stack.top() stack.pop() stack.push(p1 - p2) elif line == "*": p1 = stack.top() stack.pop() p2 = stack.top() stack.pop() stack.push(p1 * p2) else: stack.push(Polynomial(line)) if output_file != "": with open(output_file, 'w+') as f: print(stack.top(), file=f) else: print(stack.top())
def test_vector_setters_exception(value, exception_type): vector = Vector() with pytest.raises(exception_type): vector.x = value with pytest.raises(exception_type): vector.y = value
def test_vector_setters(): vector = Vector() vector.x = 42.0 vector.y = 42.0 assert vector.x == 42.0 assert vector.y == 42.0
def test_vector_equality(): v1 = Vector() v2 = Vector() v3 = Vector(2, 10) assert v1 == v2 assert not v1 == v3 assert not v1 != v2 assert v1 != v3
def test_vector_increment_decrement(): v1 = Vector(1.2, 2.3) v2 = Vector(3.4, 4.5) v1 += v2 assert v1.x == 4.6 and v1.y == 6.8 v1 -= v2 assert round(v1.x, 1) == 1.2 and round(v1.y, 1) == 2.3
def test_vector_multiplication_eq_len(): v1 = Vector([3, 5, 6]) v2 = Vector([1, 3, 5]) try: res = (v1 * v2) except: res = 0 assert res == 48
def create_straight_line(length, lane_data, quad_number=10): """ Gives the chord line set of points for a straight road""" tangent = Vector(1, 0, 0) pt = Vector(0, 0, 0) tot_lane_vertices = [] for i in range(quad_number + 1): lane_verts = generate_lane_verts(pt, tangent, lane_data) tot_lane_vertices.append(lane_verts) pt = pt + tangent * (length / quad_number) return tot_lane_vertices
def __add__(self, other): """Overloaded addition operator""" temp = Vector() for term in self.terms: temp.append(term) for term in other.terms: temp.append(term) new_poly = Polynomial() new_poly.terms = temp new_poly.combine_like_terms() new_poly.sort_terms() return new_poly
def get_vectors_from_ant_to_walls(ant): """ Get a list of vectors pointing to each wall in the game area. :param ant: The ant whose position is used to calculate wall vectors. :return: A list of vectors pointing from 'ant' to the walls of the game area. """ return [ Vector((-ant.x, 0)), Vector((game_rules.GAME_AREA_WIDTH - ant.x, 0)), Vector((0, -ant.y)), Vector((0, game_rules.GAME_AREA_HEIGHT - ant.y)) ]
def test_vector_multiplication_diff_len(): """ :return: Векторы разной длины не должны умножаться. """ v1 = Vector([3, 5, 6]) v2 = Vector([1, 3, 5, 7]) try: res = (v1 * v2) except: res = 'error' assert res != 'error'
def __mul__(self, other): """Overloaded multiplication operator""" temp = Vector() for term in self.terms: for item in other.terms: new_coef = term.coef * item.coef new_exp = term.exponent + item.exponent temp.append(Term(new_coef, new_exp)) new_poly = Polynomial() new_poly.terms = temp new_poly.combine_like_terms() new_poly.sort_terms() return new_poly
def sort_terms(self): """Sorts the terms of the polynomial in O(n^2) time""" temp = Vector() for i in range(len(self.terms)): max_exp = self.terms[0].exponent max_exp_index = 0 for index, term in enumerate(self.terms): if term.exponent > max_exp: max_exp = term.exponent max_exp_index = index temp.append(self.terms[max_exp_index]) self.terms.erase(max_exp_index) self.terms = temp
def combine_like_terms(self): max_exponent = 0 temp = Vector() for term in self.terms: max_exponent = max(max_exponent, term.exponent) for exponent in range(max_exponent + 1): new_coef = 0 for term in self.terms: if term.exponent == exponent: new_coef += term.coef if (new_coef != 0): temp.append(Term(new_coef, exponent)) self.terms = temp self.sort_terms
def create_straight_line(length,current_road,start_s,hardCode = False,quad_number = 10): """ Gives the chord line set of points for a straight road""" tangent = Vector(1,0,0) pt= Vector(0,0,0) tot_lane_vertices = [] s = -0.1 for i in range(quad_number+1): lane_data = current_road.get_lane_data(s+start_s) # print(lane_data) current_pt = pt + Vector(0,0,current_road.get_elevation(s + start_s)) lane_verts = generate_lane_verts(current_pt, tangent, lane_data,hardCode) tot_lane_vertices.append(lane_verts) pt = pt + tangent * (length/quad_number) s = s + length/quad_number return tot_lane_vertices
def __init__(self, poly_string=""): """Builds a polynomial If a string is given in the right format it will split it to build the polynomial""" self.terms = Vector() if poly_string != "": poly_pieces = Vector() poly_pieces.build_from_list(poly_string.split(" ")) for i in range(0, len(poly_pieces), 2): coef = poly_pieces[i] exponent = poly_pieces[i + 1] self.terms.insert_rear(Term(int(coef), int(exponent))) #condense similar terms self.combine_like_terms() # Sort the terms self.sort_terms()
def sum_vectors(vectors): """ Calculates the sum of the given vectors. It is assumed that all vectors have the same dimensions :param vectors: The vectors to sum :return: Sum of the given vectors """ if len(vectors) == 0: return Vector((0, 0)) if len(vectors) == 1: return vectors[0] return Vector( tuple( sum(coordinate) for coordinate in zip(*(vector.values for vector in vectors))))
def create_spiral_road(length, curvStart, curvEnd, current_road, start_s, hardCode=False, quad_number=10): # if(curvStart==0): # return spiral_line_to_curve(length,curvEnd,lane_data) # else: # return spiral_curve_to_line(length,curvStart,lane_data) origin = Vector(0, 0, 0) hdg = 0 if curvStart == 0: ltoc = True R = 1 / curvEnd else: ltoc = False R = 1 / curvStart anti_clockwise = 1 if R < 0: anti_clockwise = -1 a = 1 / math.sqrt(2 * length * abs(R)) # Scale factor RESOLUTION = 0.1 num_sections = 100 distance = 0 ahead = 1 done = False scaling = 1 dx = length / num_sections prev_point = origin total_pts = [] for i in range(num_sections): if ltoc: pt_hdg = anti_clockwise * (distance * a)**2 + hdg else: pt_hdg = anti_clockwise * ((length * a)**2 - ((length - distance) * a)**2) + hdg tangent = Vector(math.cos(pt_hdg), math.sin(pt_hdg), 0) t_norm = tangent.normalize() pt = prev_point + ahead * dx * t_norm prev_point = pt distance += ahead * dx lane_data = current_road.get_lane_data(distance + start_s) current_pt = pt + Vector( 0, 0, current_road.get_elevation(distance + start_s)) total_pts.append( generate_lane_verts(current_pt, tangent, lane_data, hardCode)) return total_pts
def _update_correspondence_reprojected_coords(self): if self.editor.layer_manager.trajectory_layer() is None: return if self.editor.layer_manager.correspondence_layer( create_new_layer=False) is None: return unreprojected_correspondences = \ self.editor.layer_manager.correspondence_layer().correspondences() if len(unreprojected_correspondences) == 0: return camera_intrinsics = \ self.editor.layer_manager.trajectory_layer().camera_config() vector_reprojector = VectorReprojector() vector_reprojector.set_intrinsics(camera_intrinsics) for correspondence in unreprojected_correspondences: camera_extrinsic = self.editor.layer_manager.trajectory_layer() \ .get_node_by_timestamp(correspondence.timestamp()).T_camera_to_world() vector_reprojector.set_extrinsic(camera_extrinsic) reprojected_shape = vector_reprojector.reproject( Vector(correspondence.reprojected_shape().origin_vertices())) if reprojected_shape is not None: correspondence.set_reprojected_shape(reprojected_shape)
def generate_lane_mark_verts(pt, tangent, lane_data, width, lane_marking = False): result_pts= [] tangent = tangent.normalize() left_normal = tangent.rotate(90) right_normal = tangent.rotate(-90) #print(lane_data) pt = pt + Vector(0,0,0.02) result_pts.append(pt + (-1*width)*left_normal) result_pts.append(pt + (width)*left_normal) new_pt = pt for x in lane_data['left']: new_pt = new_pt + x*left_normal new_pt1 = new_pt + (-1*width)*left_normal new_pt2 = new_pt + (width)*left_normal result_pts.append(new_pt1) result_pts.append(new_pt2) result_pts = list(reversed(result_pts)) new_pt=pt for x in lane_data['right']: new_pt = new_pt + x*right_normal new_pt1 = new_pt + (-width)*right_normal new_pt2 = new_pt + (+width)*right_normal result_pts.append(new_pt1) result_pts.append(new_pt2) return result_pts
def match(self, queryWords, docWords): words = self.sharedWords(queryWords, docWords) idf = [self.invDocFreq(w) for w in words] docVec = self.wordVector(words, docWords) maxFreq = docVec.largest() docVec = Vector([docVec[i] / maxFreq * idf[i] for i in range(len(words))]) queryVec = self.wordVector(words, queryWords) maxFreq = queryVec.largest() queryVec = Vector([0 if idf[i] == 0 else \ (0.5 + (0 if maxFreq == 0 else 0.5*queryVec[i]/maxFreq)) \ * idf[i] for i in range(len(words))]) return queryVec.dot(docVec) / \ (queryVec.length() * docVec.length())
def vector_between_points(p1, p2): """ Get a vector pointing from p1 to p2. :param p1: The first point, as tuple of coordinates. :param p2: The second point, as a tuple of coordinates. :return: A new vector pointing from p2 to p1. """ return Vector(tuple((x2 - x1 for x1, x2 in zip(p1, p2))))
class Stack: """An implementation of the typical stack data structure""" def __init__(self, *args): self.storage = Vector() if len(args) != 0: for item in args: self.storage.append(item) def clear(self): """Clears the entire contents of the stack""" self.storage = Vector() def is_emtpy(self): return self.is_emtpy @property def is_empty(self): if len(self.storage) == 0: return True else: return False def push(self, item): """Adds an item to the top of the stack""" self.storage.append(item) def pop(self): """Removes an item from the top of the stack""" self.storage.erase_rear() def top(self): """Returns the item at the top of the stack""" return self.storage.back()
def get_sugar_vector(ant, entities): sugar_and_vectors = [(sugar, (util.vector_between_entities(ant, sugar))) for sugar in entities.sugar] sorted_sugar_vectors = [vector for sugar, vector in sorted(sugar_and_vectors, key=lambda sugar_and_vector: get_sugar_score(ant, sugar_and_vector[0], sugar_and_vector[1], entities))] if not sorted_sugar_vectors: return Vector((0, 0)) return sorted_sugar_vectors[0].normalize().multiply(1 / 50)
class Entity(pygame.sprite.Sprite): def __init__(self, size, start_pos, move_speed): super().__init__() self.surf = pygame.Surface(size) self.rect = self.surf.get_rect(center=start_pos) self.move_direction = Vector((0, 0)) self.speed = move_speed def update(self): if not self.alive(): return new_direction = self.get_move_direction().normalize().multiply( self.speed) if game_rules.USE_ACCELERATION: self.move_direction = self.move_direction.multiply( game_rules.ACCELERATION_DECAY).plus(new_direction) else: self.move_direction = new_direction self.rect.move_ip(self.move_direction.values) @abstractmethod def get_move_direction(self): pass def draw(self, surface): rotation = get_image_rotation_from_direction(self.move_direction) if self.get_image(): image = pygame.transform.rotate(self.get_image(), rotation) surface.blit(image, self.rect) @abstractmethod def get_image(self): pass @staticmethod def load_scaled_image(image_path, scale): image = pygame.image.load(image_path) return pygame.transform.scale(image, scale) @property def x(self): return self.rect.centerx @property def y(self): return self.rect.centery def get_size(self): return self.rect.size
def __init__(self,geom): self.length = float(geom.attrib.get('length')) self.hdg = float(geom.attrib['hdg']) # tangent = Vector(math.sin(self.hdg), math.cos(self.hdg),0) # self.hdg = math.radians(tangent.argument()) self.s = float(geom.attrib['s']) self.origin = Vector(float(geom.attrib['x']), float(geom.attrib['y']), 0) for child in geom: self.type = child.tag if(self.type == 'arc'): self.curvature = float(child.attrib['curvature']) if(self.type == 'spiral'): self.init_curvature = float(child.attrib['curvStart']) self.final_curvature = float(child.attrib['curvEnd'])
def reproject(self, vector: Vector, boundary=500, filter=True) -> Union[Shape, None]: original_vertices = vector.vertices().copy() # Convert to camera coord. projected_vertices = \ original_vertices.dot(self._T_world_to_camera[:3, :3].T) + \ self._T_world_to_camera[:3, 3].T # Filter backward vertices. if filter: forward_mask = projected_vertices[:, 2] > 0.0 projected_vertices = projected_vertices[forward_mask] original_vertices = original_vertices[forward_mask] # Project to image coord. projected_vertices = projected_vertices.dot(self._K.T) projected_vertices = \ projected_vertices[:, :2] / projected_vertices[:, [2]] # Clipping. if filter and boundary > 0: clipping_mask = \ (projected_vertices[:, 0] >= -boundary) & \ (projected_vertices[:, 1] >= -boundary) & \ (projected_vertices[:, 0] < self._image_width + boundary) & \ (projected_vertices[:, 1] < self._image_height + boundary) projected_vertices = projected_vertices[clipping_mask] original_vertices = original_vertices[clipping_mask] if isinstance(vector, (Polyline3D, Polygon3D)) and \ len(projected_vertices) < 2: # Make sure at least show a segment of polyline and polygon # vector. return elif isinstance(vector, Point3D) and len(projected_vertices) == 0: # Make sure the point correspondence in the screen. return shape_class = self.get_shape_class(vector.__class__) shape = shape_class(projected_vertices) shape.set_origin_vertices(original_vertices) return shape
def test_smallest(self): vec = Vector([1,2,3]) smallest = vec.smallest() self.assertEqual(1, smallest)
def test_pearson_correlation(self): vec = Vector([1,2,3]) pair = Vector([4,6,8]) dist = vec.pearsonCorrelation(pair) self.assertEqual((4/3)/(math.sqrt(2/3) * math.sqrt(8/3)), dist)
def test_std_dev(self): vec = Vector([1,2,3]) stdDev = vec.stdDev() self.assertEqual(math.sqrt(2/3), stdDev)
def test_covariance(self): vec = Vector([1,2,3]) pair = Vector([4,6,8]) cov = vec.covariance(pair) self.assertEqual(4/3, cov)
class Polynomial: """Represents a polynomial as a collection of terms and stores in a Vector""" def __init__(self, poly_string=""): """Builds a polynomial If a string is given in the right format it will split it to build the polynomial""" self.terms = Vector() if poly_string != "": poly_pieces = Vector() poly_pieces.build_from_list(poly_string.split(" ")) for i in range(0, len(poly_pieces), 2): coef = poly_pieces[i] exponent = poly_pieces[i + 1] self.terms.insert_rear(Term(int(coef), int(exponent))) #condense similar terms self.combine_like_terms() # Sort the terms self.sort_terms() def __add__(self, other): """Overloaded addition operator""" temp = Vector() for term in self.terms: temp.append(term) for term in other.terms: temp.append(term) new_poly = Polynomial() new_poly.terms = temp new_poly.combine_like_terms() new_poly.sort_terms() return new_poly def __radd__(self, other): return self.__add__(other) def __sub__(self, other): """Overlaoded subtraction operator""" p = Polynomial("-1 0") return (self + (p * other)) def __mul__(self, other): """Overloaded multiplication operator""" temp = Vector() for term in self.terms: for item in other.terms: new_coef = term.coef * item.coef new_exp = term.exponent + item.exponent temp.append(Term(new_coef, new_exp)) new_poly = Polynomial() new_poly.terms = temp new_poly.combine_like_terms() new_poly.sort_terms() return new_poly def __rmul__(self, other): return self.__mul__(other) def sort_terms(self): """Sorts the terms of the polynomial in O(n^2) time""" temp = Vector() for i in range(len(self.terms)): max_exp = self.terms[0].exponent max_exp_index = 0 for index, term in enumerate(self.terms): if term.exponent > max_exp: max_exp = term.exponent max_exp_index = index temp.append(self.terms[max_exp_index]) self.terms.erase(max_exp_index) self.terms = temp def combine_like_terms(self): max_exponent = 0 temp = Vector() for term in self.terms: max_exponent = max(max_exponent, term.exponent) for exponent in range(max_exponent + 1): new_coef = 0 for term in self.terms: if term.exponent == exponent: new_coef += term.coef if (new_coef != 0): temp.append(Term(new_coef, exponent)) self.terms = temp self.sort_terms def __str__(self): """Returns a string representation of the polynomial""" temp = "" if len(self.terms) > 0: if self.terms[0].coef < 0: temp += "-" temp += str(abs(self.terms[0].coef)) if self.terms[0].exponent != 0: temp += "x^" + str(self.terms[0].exponent) for i in range(1, len(self.terms)): if self.terms[i].coef > 0: temp += " + " else: temp += " - " temp += str(abs(self.terms[i].coef)) if self.terms[i].exponent != 0: temp += "x^" + str(self.terms[i].exponent) return temp
def test_vector_sum_diff(): v1 = Vector(1.2, 2.3) v2 = Vector(3.4, 4.5) assert (v1 + v2) == Vector(4.6, 6.8) assert (v2 - v1) == Vector(2.2, 2.2)
def __init__(self, *args): self.storage = Vector() if len(args) != 0: for item in args: self.storage.append(item)
def test_vector_to_string(): vector = Vector() assert str(vector) == '(0.0, 0.0)'
def testCosineSimilarity(self): matcher = matching.CosineSimilarity({ 'docFreq': { 'a': 4, 'b': 2, 'c': 1, }, 'docCount': 16 }) # ---- test one ----- docWords = {'a': 13, 'c': 9} queryWords = {'a': 7, 'b': 4} idf = {w: matcher.invDocFreq(w) for w in ['a', 'b', 'c']} docVec = Vector([13/13*idf['a'], 0, 9/13*idf['c']]) queryVec = Vector([(0.5+0.5*7/7)*idf['a'], (0.5+0.5*4/7)*idf['b'], 0.5*idf['c']]) scoreComputed = docVec[0]*queryVec[0] + docVec[1]*queryVec[1] + \ docVec[2]*queryVec[2] scoreComputed = scoreComputed / docVec.length() scoreComputed = scoreComputed / queryVec.length() score = matcher.match(queryWords, docWords) self.assertApproxEqual(score, scoreComputed) # ---- test two ----- docWords = {'a': 13, 'b': 9, 'c': 1} queryWords = {'a': 7, 'b': 4} docVec = Vector([13/13*idf['a'], 9/13*idf['b'], 1/13*idf['c']]) queryVec = Vector([(0.5+0.5*7/7)*idf['a'], (0.5+0.5*4/7)*idf['b'], 0.5*idf['c']]) scoreComputed = docVec[0]*queryVec[0] + docVec[1]*queryVec[1] + \ docVec[2]*queryVec[2] scoreComputed = scoreComputed / docVec.length() scoreComputed = scoreComputed / queryVec.length() score = matcher.match(queryWords, docWords) self.assertApproxEqual(score, scoreComputed) # ---- test three ----- docWords = {'a': 13, 'b': 9} queryWords = {'a': 7, 'b': 4, 'c': 1} docVec = Vector([13/13*idf['a'], 9/13*idf['b'], 0]) queryVec = Vector([(0.5+0.5*7/7)*idf['a'], (0.5+0.5*4/7)*idf['b'], (0.5+0.5*1/7)*idf['c']]) scoreComputed = docVec[0]*queryVec[0] + docVec[1]*queryVec[1] + \ docVec[2]*queryVec[2] scoreComputed = scoreComputed / docVec.length() scoreComputed = scoreComputed / queryVec.length() score = matcher.match(queryWords, docWords) self.assertApproxEqual(score, scoreComputed)
def test_manhattan(self): vec = Vector([1,2]) pair = Vector([3,4]) dist = vec.manhattanDist(pair) self.assertEqual(4, dist)
def test_vector_len(): vector = Vector(2, 4) assert vector.len() == 4.47213595499958
def clear(self): """Clears the entire contents of the stack""" self.storage = Vector()
def test_vector_constructor(x, y): vector = Vector(x, y) assert vector.x == x assert vector.y == y
def test_length(self): vec = Vector([3,4]) length = vec.length() self.assertEqual(length, 5)
def test_check_type_exception(): with pytest.raises(TypeError): v1 = Vector() v1 == dir
def test_largest(self): vec = Vector([1,2,3]) lrg = vec.largest() self.assertEqual(3, lrg)
def test_euclidian(self): vec = Vector([-1,2]) pair = Vector([3,5]) dist = vec.euclidDist(pair) self.assertEqual(5, dist)
def test_dot_product(self): vec = Vector([1,2]) by = Vector([3,4]) dot = vec.dot(by) self.assertEqual(11, dot)
__author__ = 'Kumar_Garg' from vector.vector import Vector v1 = Vector([8.218, -9.341]) v2 = Vector([-1.129, 2.111]) print v1.plus(v2) v3 = Vector([7.119, 8.215]) v4 = Vector([-8.223, 0.878]) print v3.minus(v4) v5 = Vector([1.671, -1.012, -0.318]) print v5.scalar(7.41) v6 = Vector([-0.221, 7.437]) print v6.magnitude() v7 = Vector([8.813, -1.331, -6.247]) print v7.magnitude() v8 = Vector([5.581, -2.136]) print v8.direction() v9 = Vector([1.996, 3.108, -4.554]) print v9.direction()
def test_median(self): vec = Vector([1,2,3]) median = vec.median() self.assertEqual(2, median)