def test_filter_rules(): rule1 = { 'applies': { 'positive': ['nasal'] }, 'conditions': { 'negative': ['nasal'], 'positive': ['syllabic'] }, 'name': 'nasalization' } rule2 = { 'applies': { 'positive': ['tonal'] }, 'conditions': { 'positive': ['syllabic'] }, 'name': 'valid' } word1 = Word( [Segment(['consonantal'], ['tonal']), Segment(['sonorant'], ['high'])]) word2 = Word( [Segment(['syllabic', 'low'], []), Segment(['high'], ['sonorant'])]) assert filter_rules([word1, word2], [rule1, rule2]) == [rule2]
def test_triangulation(self): list_of_points = [Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1)] list_of_triangulations1 = [[Segment(Point(0, 0), Point(1, 1))], [Segment(Point(1, 0), Point(0, 1))]] all_possible_triangulations(list_of_points) self.assertEqual(Structs.list_of_triangulations, list_of_triangulations1)
def generate_segments(self): segments = [] list_of_segments_in_rows = [] list_of_segments_in_columns = [] size = self.board.size for line_type, segment_direction, list_of_segments_in_line in [ (Utils.ROW, Segment.horizontal, list_of_segments_in_rows), (Utils.COLUMN, Segment.vertical, list_of_segments_in_columns) ]: for index in range(size): cells_in_current_segment = set() segments_in_line = [] for pos in Utils.get_positions_in_line(index, self.board.size, line_type): cell = self.board.get_cell(pos) if cell.is_blocked: if len(cells_in_current_segment) > 0: new_segment = Segment(cells_in_current_segment, segment_direction, size) segments.append(new_segment) segments_in_line.append(new_segment) cells_in_current_segment = set() else: cells_in_current_segment.add(cell) if len(cells_in_current_segment) > 0: new_segment = Segment(cells_in_current_segment, segment_direction, size) segments.append(new_segment) segments_in_line.append(new_segment) list_of_segments_in_line.append(segments_in_line) return segments, list_of_segments_in_rows, list_of_segments_in_columns
def __initialize_snakes(self): ''' Creates the snake that will be used in the game ''' self.live_snakes = self.snake_pop for i in range(self.snake_pop): #Initialize snake = None if self.first_run: snake = Neat_Snake(self.seg_size, NN_Scratch(12, 1, [30], 4), Snake) #snake = Neat_Snake(self.seg_size, NN_Scratch(8, 2, [20,50], 4),Snake)# network_filename = "Neat_Snake_Network_i8_h20_o4__2018-10-17_13.49.26"), Snake) for key in snake.network.network.keys(): if any(i in key for i in ["w", "b"]): snake.network.network[key] += np.random.uniform( -1, 1, size=snake.network.network[key].shape) de = ("%02x" % np.random.randint(0, 255)) re = ("%02x" % np.random.randint(0, 255)) we = ("%02x" % np.random.randint(0, 255)) snake.color = "#" + de + re + we #snake = Neat_Snake(self.seg_size, NN_Scratch(8, 1, [50], 4), Snake) else: snake = self.snakelist[i] # print(self.WIDTH - self.edge_buffer - 20) # print(self.edge_buffer) #Snake head creation at some random middle point (multiple of the seg_size) snake_head = Segment(450, 450) #Create snake by starting with head snake.addSegment(snake_head) #Everything references the location before it for i in range(1, self.snake_length): for j in self.seg_opts: #print(self.snake.body[i-1].x + j[0]*15) #print(self.snake.body[i-1].y + j[1]*15) if (self.__valid_position(snake.body[i - 1].x + j[0] * 15, snake.body[i - 1].y + j[1] * 15, snake)): newSeg = Segment(snake.body[i - 1].x + j[0] * 15, snake.body[i - 1].y + j[1] * 15) snake.addSegment(newSeg) #print("GOOD SPOT!") break #add the snake to the snakelist if self.first_run: self.snakelist.append(snake) if self.first_run: self.first_run = False
def create_segments(segment, ref=None): """Creates Segment list breaking the segment if direction [1, 0] intersects it. This function is used to avoid the case in which the points are sorted counterclockwise with reference to ref and theta1 > theta2. """ if ref is None: ref = np.array([0, 0]) p1 = segment.p1 p2 = segment.p2 x1 = p1[0] - ref[0] y1 = p1[1] - ref[1] x2 = p2[0] - ref[0] y2 = p2[1] - ref[1] if x1 * y2 - x2 * y1 < 0: p1, p2 = p2, p1 x1, y1, x2, y2 = x2, y2, x1, y1 theta1 = my_atan2(y1, x1) theta2 = my_atan2(y2, x2) hor = np.array([1, 0]) intersects, intersection = segment.intersect(ref, hor) if intersects: if abs(theta2) < EPS and abs(theta1) > EPS: return [Segment(p1, p2, theta1, 2 * math.pi, ref)] elif abs(theta1) < EPS and abs(theta2) > EPS: return [Segment(p1, p2, 0, theta2, ref)] return [ Segment(intersection, p2, 0, theta2, ref), Segment(p1, intersection, theta1, 2 * math.pi, ref), ] return [Segment(p1, p2, theta1, theta2, ref)]
def processReceiveAndSendRespond(self): segmentAck = Segment() # Segment acknowledging packet(s) received # This call returns a list of incoming segments (see Segment class)... listIncoming = self.receiveChannel.receive() # get the ack number for the last segment sent and save a copy of the data received # in a new list if (len(listIncoming) != 0): acknum = 0 incomingData = [] for item in listIncoming: acknum = item.seqnum + self.DATA_LENGTH incomingData.append(item.payload) boolChecksum = item.checkChecksum() if (boolChecksum == False): print("checksums don't match") #send back sequence number of corrupted segment for selective retransmission self.sendChannel.send(item.seqnum) #create the ack segment with a copy of the list of data received and an cumulative ack number ack = Segment() ack.setAck(acknum) for item in incomingData: self.seg.append(item) # Use the unreliable sendChannel to send the ack packet self.sendChannel.send(ack) print("sending ack:") ack.printToConsole()
def test_linejoin(self): points = [ Point(Fraction(0), Fraction(0)), Point(Fraction(0), Fraction(1)), Point(Fraction(0), Fraction(2)), Point(Fraction(0), Fraction(3)), Point(Fraction(1), Fraction(1)), Point(Fraction(2), Fraction(2)), Point(Fraction(3), Fraction(3)) ] tests = [ (None, [Segment(points[0], points[1]), Segment(points[2], points[3])]), (Segment(points[0], points[2]), [Segment(points[0], points[1]), Segment(points[1], points[2])]), (Segment(points[0], points[5]), [Segment(points[0], points[4]), Segment(points[4], points[5])]), (None, [Segment(points[0], points[4]), Segment(points[5], points[6])]) ] for (t_outcome, t_segments) in tests: got = solution.createLargerSegment(t_segments[0], t_segments[1]) print 'want', t_outcome, 'got', got, 'from', t_segments assert t_outcome == got
def resetRoad(self, variable): for x in range(1, 501): if math.floor(x / variable.rumbleLength) % 2 == 0: variable.segments.append(Segment(x, variable, "dark")) else: variable.segments.append(Segment(x, variable, "light")) variable.trackLength = len(variable.segments) * variable.segmentLength
def create_non_intersecting_segments(pts1, pts2, segs2, angles, ref): """Creates list with the Segments that are visible from ref for the case when the line segment in pts1 is in front of the line segment in pts2. Args: pts1 (list[list]): list of 2D points that are the intersection of the rays from ref in the directions indicated by angles with the Segment closest to ref pts2 (list[list]): list of 2D points that are the intersection of the rays from ref in the directions indicated by angles with the Segment farthest to ref segs2 (list[Segment]): list of Segment between the points in pts2 angles (list[float]): list of directions (radians) of the rays from ref the angles are obtained from the two extremes of each original Segment. The list always has 4 elements (even if repeated) ref (list): reference point """ segments = [] segment = Segment(pts1[1], pts1[2], angles[1], angles[2], ref) if pts1[0] is not None: segment.merge(Segment(pts1[0], pts1[1], angles[0], angles[1], ref)) if pts1[3] is not None: segment.merge(Segment(pts1[2], pts1[3], angles[2], angles[3], ref)) segments.append(segment) if segs2[0] is not None and segs2[0].length_sq > EPS_SQ: segments = [segs2[0]] + segments if segs2[2] is not None and segs2[2].length_sq > EPS_SQ: segments.append(segs2[2]) return segments
def __initialize_snake(self): ''' Creates the snake that will be used in the game ''' self.snake = Snake(self.seg_size) # print(self.WIDTH - self.edge_buffer - 20) # print(self.edge_buffer) #Snake head creation at some random middle point (multiple of the seg_size) snake_head = Segment(450,450) #Create snake by starting with head self.snake.addSegment(snake_head) #Create options for where the snake can attach seg_opts = [(1,0),(0,1),(-1,0),(0,-1)] #Everything references the location before it for i in range(1,self.snake_length): for j in seg_opts: #print(self.snake.body[i-1].x + j[0]*15) #print(self.snake.body[i-1].y + j[1]*15) if (self.__valid_position(self.snake.body[i-1].x + j[0]*15,self.snake.body[i-1].y + j[1]*15)): newSeg = Segment(self.snake.body[i-1].x + j[0]*15,self.snake.body[i-1].y + j[1]*15) self.snake.addSegment(newSeg) #print("GOOD SPOT!") break
def extent(self): """Timeline extent The extent of a timeline is the segment of minimum duration that contains every segments of the timeline. It is unique, by definition. The extent of an empty timeline is an empty segment. Returns ------- extent : Segment Timeline extent Examples -------- >>> timeline = Timeline(video="MyVideo.avi") >>> timeline += [Segment(0, 1), Segment(9, 10)] >>> print timeline.extent() [0 --> 10] """ if self: # The extent of a timeline ranges from the start time # of the earliest segment to the end time of the latest one. start_time = self.__segments[0].start end_time = self.__rsegments[-1].end return Segment(start=start_time, end=end_time) else: # The extent of an empty timeline is an empty segment return Segment()
def __intersecting(self, segment): """Sorted list of intersecting segments""" # if segment is empty, it intersects nothing. if not segment: return [] # any intersecting segment starts before segment ends # and ends after it starts dummy_end = Segment(segment.end-SEGMENT_PRECISION, \ segment.end-SEGMENT_PRECISION) index = self.__search(dummy_end, self.__segments) # property 1: # every segment in __segments[:index] starts before key ends dummy_start = RevSegment(Segment(segment.start+SEGMENT_PRECISION, \ segment.start+SEGMENT_PRECISION)) xedni = self.__search(dummy_start, self.__rsegments) # property 2: # every segment in __rsegments[xedni:] ends after key starts # get segments with both properties both = set(self.__segments[:index]) & set(self.__rsegments[xedni:]) # make sure every RevSegment is converted to Segment # and return their sorted list return sorted([rsegment.copy() for rsegment in both])
def handshake(self): # make + send SYN packet syn = Segment(self.c_port, self.s_port, self.win_size, self.next_seq) syn.set_syn_bit() syn.set_checksum() self.client_socket.sendto(syn.pkt.bytes, self.server) self.next_seq += 1 # advance TCP machine from CLOSED to SYN-SENT self.tcp_machine.snd_syn() # receive SYN-ACK packet, write SEQ number to y syn_ack = (self.client_socket.recvfrom(1472))[0] self.next_ack_num = PktReader.get_seq_num(syn_ack) y = PktReader.get_seq_num(syn_ack) # make ACK packet with ACK number = y + 1 ack = Segment(self.c_port, self.s_port, self.win_size, self.next_seq) ack.set_ack_bit() ack.set_ack_num(y + 1) ack.set_checksum() self.client_socket.sendto(syn.pkt.bytes, self.server) # advance TCP machine from SYN-SENT to ESTABLISHED self.tcp_machine.recv_syn_ack()
def isUnitSquare(rational_points): # xxx rpoints and points must correspond xxx points = [ p.toFloat() for p in rational_points ] hull = ConvexHull(points) hull_points = [ rational_points[i] for i in hull.vertices ] line1 = Segment(Point(hull_points[0][0],hull_points[0][1]), Point(hull_points[1][0], hull_points[1][1])) line2 = Segment(Point(hull_points[1][0],hull_points[1][1]), Point(hull_points[2][0], hull_points[2][1])) # hull_points are guaranteed to be in counterclockwise order angle = None if line1.no_slope() and (not line2.no_slope() and line2.slope() == 0): angle = pi / 2 elif line2.no_slope() and (not line1.no_slope() and line1.slope() == 0): angle = pi / 2 else: l1f = line1.toFloat() l2f = line2.toFloat() print "lines %s %s" % (l1f, l2f) l1d = FloatPoint(l1f[1][0]-l1f[0][0],l1f[1][1]-l1f[0][1]) l2d = FloatPoint(l2f[1][0]-l2f[0][0],l2f[1][1]-l2f[0][1]) angle = atan2(l2d[1], l2d[0]) - atan2(l1d[1], l1d[0]) area = poly_area_indexed(rational_points, hull.vertices) num_points = len(hull_points) angle_delta = fmod(angle - (pi/2), 2*pi) print "IsSquare: area:", area, "Num Points: ", num_points, "Angle Delta from 90 degrees, in radians: ", angle_delta return area == 1 and num_points == 4 and abs(angle_delta) < epsilon
def test_variable_turn_offset(self): arc = Segment(arc=math.radians(90), radius=10.0, end_radius=20.0) self.assertEqual(arc.get_offset((0, 0, 0)), (0, 0)) self.assertEqual(arc.get_offset((20, 10, math.radians(90))), (0, 0)) arc = Segment(arc=math.radians(-90), radius=10.0, end_radius=20.0) self.assertEqual(arc.get_offset((0, 0, 0)), (0, 0)) self.assertEqual(arc.get_offset((20, -10, math.radians(-90))), (0, 0))
def test_draw(self): line = Segment(length=100.0) arc = Segment(arc=math.radians(90), radius=50.0) track = Track([line, arc] * 4, width=20) fig = draw(track) with tempfile.TemporaryFile() as f: fig.savefig(f, format='png')
def _create_segments(self): """ Internal function to create Segment objects from entries in node list. """ # eliminate existing segments # unlink nodes from any existing segments for n in self.node_list: n.segment = None # clear segment list self._segment_lists = [] ########################## # assign nodes to segments # algorithm here should be resistant to poorly structured SWCs # segments are assigned based on a node's parent, and a parent # must be present before a node is, so nodes belonging to # a segment don't have to be listed sequentially in the SWC # branch order is calculated by traversing back to the soma # once all segments are created, so there's no dependency on # order or when segments are defined for tree in self._tree_list: seg_list = [] # add each non-soma node to its parent's segment unless # the parent is soma or a bifurcation, in which case # create a new segment for n in tree: if n.t == 1: continue if n.parent < 0: seg = Segment() seg_list.append(seg) else: par = self.node(n.parent) if par.t == 1 or len(par.children) > 1: seg = Segment() seg_list.append(seg) else: seg = par.segment seg.add_node(n) n.segment = seg # tell node what segment it belongs to # put each segment in proper order and calculate size for seg in seg_list: seg.setup(self) # assign branch order # trace back through segment hierarchy to get depth. count # number of jumps required to get to soma for seg in seg_list: order = 1 cur_seg = seg lead_node = self.node(cur_seg.node_list[0]) while lead_node.parent > 0 or lead_node.t != 1: par = self.node(lead_node.parent) if par is None or par.t == 1: break cur_seg = par.segment lead_node = self.node(cur_seg.node_list[0]) order += 1 seg.set_branch_order(order) self._segment_lists.append(seg_list)
def find_path(img, segments, roots, queue, seg_counter): # add Segments to segments list # return 1 if successfully added Segment object to segments # return 0 if there are no more paths in the image # return -1 if no more Segment objects to be found [rowMax, colMax] = img.shape # initial seed heuristic to find start of blood vessels # start at (rowMax, 0) # move to (rowMax, colMax), then move to (rowMax -1, 0)... # stop at (0, colMax) if not queue: for r in xrange(rowMax - 2, 1, -1): for c in xrange(2, colMax - 2, 1): if img[r][c] == 1: roots.append(seg_counter) seg = Segment(seg_counter) seg.add_to_path(r, c) if debug: print "seg_counter: %i" % (seg_counter) print "inside find_path double for loop: r: %i, c: %i" % ( r, c) # recursively add to seg until complete, erase paths from image search(seg, img, queue, r, c) if debug: print "size of seg: %i; seg.seg_id: %i" % (len( seg.path), seg.seg_id) segments[seg_counter] = seg seg_counter = seg_counter + 1 return [1, seg_counter] return [0, seg_counter] else: # perform BFS by popping queue while (queue): fork = queue.popleft() if debug: print "Parent: %i" % (fork["parent"]) seg = Segment(seg_counter) r = fork["point"][0] c = fork["point"][1] seg.add_to_path(r, c) seg.add_parent(segments[fork["parent"]]) if debug: print "seg.seg_id in find_path: %i" % (seg.seg_id) if debug: print "fork['id'] in find_path: %i" % (fork["id"]) search(seg, img, queue, r, c) # add children back to parent seg segments[fork["parent"]].add_to_children(seg) # add children's first coords to parent segments[fork["parent"]].add_to_path(r, c) # add current seg to segments dict segments[seg_counter] = seg seg_counter = seg_counter + 1 return [-1, seg_counter]
def test_add_two_segments(): visible = IntersectionFinder() segment1 = Segment(np.array([1, 0]), np.array([1, 1])) segment2 = Segment(np.array([-1, 0]), np.array([-1, -1])) visible.add_segment(segment2) visible.add_segment(segment1) segments = visible.segments assert len(segments) == 2 assert segments[0] == segment1 assert segments[1] == segment2
def test_equality(): word1 = Word( [Segment(['nasal'], ['syllabic']), Segment(['syllabic'], ['nasal'])]) word2 = Word( [Segment(['nasal'], ['syllabic']), Segment(['syllabic'], ['nasal'])]) assert word1 == word2
def read_Matrice(self, m, **kw): """Build from Matrice m, keeping at each position the descriptor number that is selected by a function. A segment is made for each run of identical descriptors numbers. The value of the each segment is the prediction of its descriptor. Keyword argument: func -- function func has two arguments, a Matrice and a position, and returns a tuple "descriptor number, floating point value" (default: returns the tuple best descriptor,best value (the first of the bests descriptors is returned if there are several bests)). """ if kw.has_key('func'): f = kw['func'] else: def f(m, i): d = m.line(i) mx = max(d.values()) for j in d: if mx == d[j]: return j, mx self.__init__() l = len(m) deb = 0 x, v = f(m, 0) i = 1 while i < l: y, w = f(m, i) if x != y: if len(self.__tab) != 0: self.__tab[-1].g_val(v) if len(x) == 1: num = ord(x) else: num = int(x[1:]) v = w self.__tab.append(Segment(deb=deb, fin=i - 1, num=[num], val=v)) x = y deb = i else: v += w i += 1 if len(x) == 1: num = ord(x) else: num = int(x[1:]) self.__tab.append(Segment(deb=deb, fin=i - 1, num=[num], val=v)) self.__val = sum([s.val() for s in self.__tab])
def test_variable_turn_step(self): s = Segment(arc=math.radians(90.0), radius=5.0, end_radius=6.0) x, y, heading = s.step() self.assertAlmostEqual(x, 6.0) self.assertAlmostEqual(y, 5.0) self.assertAlmostEqual(heading, math.radians(90.0)) s1 = Segment(arc=1.23, radius=10.0) s2 = Segment(arc=1.23, radius=10.0, end_radius=10.0) for a, b in zip(s1.step(), s2.step()): self.assertAlmostEqual(a, b)
def test_add_split(): visible = IntersectionFinder() p1 = np.array([1, -1]) p2 = np.array([1, 0]) p3 = np.array([1, 1]) segment = Segment(p3, p1) visible.add_segment(segment) segments = visible.segments assert len(segments) == 2 assert segments[0] == Segment(p2, p3) assert segments[1] == Segment(p1, p2)
def add_segment(self, n=0, **keyargs): last_segment = self.segments[-1] if len( self.segments) > 1 else self.segments[0] if len(self.segments) > 1: self.segments.append( Segment(last_segment.direction, np.add(last_segment.pos, -last_segment.direction))) else: self.segments.append( Segment(last_segment.direction, last_segment.pos)) # If if n > 1: self.add_segment(n - 1)
def test_turn_step(self): s = Segment(arc=math.radians(90.0), radius=5.0) x, y, heading = s.step() self.assertAlmostEqual(x, 5.0) self.assertAlmostEqual(y, 5.0) self.assertAlmostEqual(heading, math.radians(90.0)) s = Segment(arc=math.radians(-90.0), radius=5.0) x, y, heading = s.step() self.assertAlmostEqual(x, 5.0) self.assertAlmostEqual(y, -5.0) self.assertAlmostEqual(heading, math.radians(-90.0))
def handshake(self): while True: seq = Segment(source_port=self.client_port, SYN='b1', ACK='b1') res_seq = self.sendSeqment(seq) if res_seq.SYN == 'b1' and res_seq.ACK == 'b1': print 'send ACK for SYN' seq = Segment(source_port=self.client_port, SYN='b0', ACK='b1') self.sendSeqment(seq) self.establishConnection = True return else: continue
def generateBoard(self, rows: int, columns: int): _id = 0 for x in range(rows + 1): for y in range(columns + 1): if x < rows: self.available_segments.append( Segment((x, y), (x + 1, y), _id)) _id += 1 if y < columns: self.available_segments.append( Segment((x, y), (x, y + 1), _id)) _id += 1
def __init__(self, leg_name, offset, servos): self.leg_name = leg_name if not path.exists("config/" + leg_name): makedirs(leg_name) self.offset = offset self.upper_hip = Joint(servos["upper_hip"], "config/" + leg_name + "/upper_hip.json") self.hip = Segment("config/" + leg_name + "/hip.json") self.lower_hip = Joint(servos["lower_hip"], "config/" + leg_name + "/lower_hip.json") self.femur = Segment("config/" + leg_name + "/femur.json") self.knee = Joint(servos["knee"], "config/" + leg_name + "/knee.json") self.tibia = Segment("config/" + leg_name + "/tibia.json")
def test_arc_offset(self): arc = Segment(arc=math.radians(90), radius=10.0) self.assertEqual(arc.get_offset((0, 0, 0)), (0, 0)) self.assertEqual(arc.get_offset((10, 0, 0)), (-(math.sqrt(2)*10 - 10), math.radians(-45))) self.assertEqual(arc.get_offset((-1, 0, 0)), (None, None)) self.assertEqual(arc.get_offset((11, 11, 0)), (None, None)) arc = Segment(arc=math.radians(-90), radius=10.0) self.assertEqual(arc.get_offset((0, 0, 0))[0], 0) self.assertEqual(arc.get_offset((10, 0, 0))[0], math.sqrt(2)*10 - 10) self.assertEqual(arc.get_offset((-1, 0, 0))[0], None)
def test_index_applicable_boundaries(): start_boundary = {'conditions': {'positive': ['syllabic']}, 'first': True} word = Word( [Segment(['syllabic'], ['nasal']), Segment(['syllabic'], ['nasal'])]) assert word.index_applicable(0, start_boundary) assert not word.index_applicable(1, start_boundary) end_boundary = {'conditions': {'positive': ['syllabic']}, 'last': True} assert not word.index_applicable(0, end_boundary) assert word.index_applicable(1, end_boundary)