コード例 #1
0
ファイル: som_v4.py プロジェクト: suraj813/SOMClassifier
 def classify(self, dirname):  # dirname = location of json
     filelist = os.listdir(dirname)
     for idx, json_doc in enumerate(filelist):
         this_file = os.path.join(dirname, json_doc)
         remaining = len(filelist) - idx
         logger.info("Classifying File:%s. %d files left.", json_doc,
                     remaining)
         try:
             with open(this_file) as f:
                 file = json.load(f)
                 kw = Counter(file['keyword_frequency'])
                 top_kw = kw.most_common(round(
                     len(kw) /
                     10))  # top 10% (arbitrary) of keywords [(w,f),..]
                 vec_dict = file['vectors']
         except IsADirectoryError:
             continue
         neurons = self._neurons
         for neuron in neurons:
             doc_vec = 0
             tot_freq = 0
             for (w, f) in top_kw:
                 try:
                     doc_vec += dot(
                         f, distance(vec_dict[w], neuron.get_weights(
                         )))  # sum(freq*similarity(keyword,neuron))
                 except KeyError:
                     continue
                 tot_freq += f
                 neuron.write_keylist(w,
                                      distance(vec_dict[w],
                                               neuron.get_weights())
                                      )  # {word:similarity_to_this_neuron}
             doc_vec /= tot_freq  # weighted average of cosine similarity of all keywords in this_file to this neuron
             neuron.write_doclist(this_file, doc_vec)
コード例 #2
0
ファイル: som_v4.py プロジェクト: suraj813/SOMClassifier
 def classify(self,dirname): # dirname = location of json
     filelist = os.listdir(dirname)
     for idx, json_doc in enumerate(filelist):
         this_file = os.path.join(dirname,json_doc)
         remaining = len(filelist) - idx
         logger.info("Classifying File:%s. %d files left.", json_doc,remaining)
         try:
             with open(this_file) as f:
                 file = json.load(f)
                 kw = Counter(file['keyword_frequency'])
                 top_kw = kw.most_common(round(len(kw)/10)) # top 10% (arbitrary) of keywords [(w,f),..]
                 vec_dict = file['vectors']
         except IsADirectoryError:
             continue
         neurons = self._neurons
         for neuron in neurons:
             doc_vec=0
             tot_freq=0
             for (w,f) in top_kw:
                 try:
                     doc_vec += dot(f, distance(vec_dict[w],neuron.get_weights())) # sum(freq*similarity(keyword,neuron))
                 except KeyError:
                     continue
                 tot_freq += f
                 neuron.write_keylist(w,distance(vec_dict[w], neuron.get_weights())) # {word:similarity_to_this_neuron}
             doc_vec /= tot_freq # weighted average of cosine similarity of all keywords in this_file to this neuron
             neuron.write_doclist(this_file,doc_vec)
コード例 #3
0
def handle_click(x, y):
    global option_selected
    print(x, y)
    # select tree option
    if ut.distance(145, 310, x, y) <= 15:
        select_options(145.0, 310.0)
        ut.option_selected = 1
        ut.draw_circle(230, 310.0, 10, 'black', 'pink')
    #select bird option
    if ut.distance(230, 310, x, y) <= 15:
        select_options(230, 310)
        ut.option_selected = 2
        ut.draw_circle(145.0, 310.0, 10, 'black',
                       'pink')  # Unselect Tree option
        create_bird()
    # If option 1 is select then draw tree
    if y < 300 and y > -320 and x < 340 and x > -350:
        if ut.option_selected == 1:
            factor = ut.random_scale_factor(
            )  #Get a new scale factor at each click drawing
            ut.draw_rectangle(x, y, WIDTH_STEM * factor, HEIGHT_STEM * factor,
                              'brown', 'brown')  #Draw STEM
            ut.draw_triangle(ut.posx, ut.posy, WIDTH * factor, HEIGHT * factor,
                             'green', 'green')
        # If option 2 is selected draw Bird
        elif ut.option_selected == 2:
            ut.stamp_turtle(x, y, 'purple')
コード例 #4
0
ファイル: som_v4.py プロジェクト: suraj813/SOMClassifier
    def search(self, search_str, search_dir, depth=2):
        # Depth -> number of top nodes to search. Default 2 (arbitrary) has been sufficient so far.
        results = Counter()  # {url:score}
        dist_neu_searchq = Counter(
        )  # {nid:dist} Contains the similarity of each neuron to the aggregated search query
        neuron_lookup = self._neu_index
        neuron_labels = [[
            k for (k, n) in Counter(neuron.get_keylist()).most_common()[:10]
        ] for neuron in self._neurons]
        glomat = self._glomat  # Global matrix. Contains similarity of each search term in the query to all neurons. Something like a cache.

        conn = SQLCon()
        searchvecs = [(x, list(conn.read(x))) for x in search_str.split()
                      if not conn.read(x) is None
                      ]  # Obtain (word,vec) of search terms
        search_len = len(searchvecs)
        for (w, v) in searchvecs:  # For colour coding the map
            try:
                for nid in glomat[w]:
                    if glomat[w][nid] > dist_neu_searchq[nid]:
                        dist_neu_searchq[nid] += glomat[w][nid] / search_len
            except KeyError:
                glomat[w] = {}
                for nid, neuron in enumerate(self._neurons):
                    glomat[w][nid] = distance(
                        neuron.get_weights(), v
                    )  # cosine similarity, hence 1 is best. 0 is bleh. -1 is opposite.
                    if glomat[w][nid] > dist_neu_searchq[nid]:
                        dist_neu_searchq[nid] += glomat[w][nid] / search_len

            # Union of all doclists with minimum dist_from_neuron.
            doclist = {}
            for nid in dist_neu_searchq.most_common()[:depth]:
                neuron = neuron_lookup[nid[0]]
                doclist.update(neuron.get_top_docs(30))
            files = (open(doc) for doc in doclist)
            for json_file in files:
                data = json.load(json_file)
                centroids = data['centroids']
                url = data['url']
                json_file.close()
                wc_sim = [distance(v, c) for c in centroids]
                max_wc_sim = max(wc_sim)
                results[url] += max_wc_sim / len(searchvecs)

        results = OrderedDict(results.most_common(20))
        htmlVars = {'query': search_str, 'results': results}
        htmlCode = template.render(htmlVars)
        result_path = os.path.join(search_dir, search_str + '.html')
        map_path = os.path.join(search_dir, search_str + '_map.html')

        with open(result_path, 'w') as f:
            f.write(htmlCode)
        self.draw_SOM(search_str, dist_neu_searchq, neuron_labels, map_path)

        result_path = "file://{}".format(pathname2url(result_path))
        map_path = "file://{}".format(pathname2url(map_path))
        webbrowser.open(result_path)
コード例 #5
0
ファイル: som_v4.py プロジェクト: suraj813/SOMClassifier
 def find_bmu(self,input_vec):
     neurons = self._neurons
     wt_vec = neurons[0].get_weights()
     shortest_dist = distance(input_vec, wt_vec)
     bmu_neuron = None
     for i in range(len(neurons)):
         tmp_dist = distance(input_vec, neurons[i].get_weights())
         if tmp_dist >= shortest_dist:
             shortest_dist = tmp_dist
             bmu_neuron = neurons[i]
     return bmu_neuron
コード例 #6
0
ファイル: som_v4.py プロジェクト: suraj813/SOMClassifier
 def find_bmu(self, input_vec):
     neurons = self._neurons
     wt_vec = neurons[0].get_weights()
     shortest_dist = distance(input_vec, wt_vec)
     bmu_neuron = None
     for i in range(len(neurons)):
         tmp_dist = distance(input_vec, neurons[i].get_weights())
         if tmp_dist >= shortest_dist:
             shortest_dist = tmp_dist
             bmu_neuron = neurons[i]
     return bmu_neuron
コード例 #7
0
ファイル: forest1.py プロジェクト: MarvinKweyu/Forest_Drawing
def main():
    import turtle
    draw_triangle()
    draw_circle()
    draw_rectangle()
    stamp_turtle()
    distance()
    save_state()
    restore_state()
    turtle.setup(window_width, window_height)
    turtle.listen(handle_click())
コード例 #8
0
ファイル: som_v4.py プロジェクト: suraj813/SOMClassifier
    def search(self,search_str,search_dir,depth=2):
        # Depth -> number of top nodes to search. Default 2 (arbitrary) has been sufficient so far.
        results = Counter()        # {url:score}
        dist_neu_searchq=Counter()  # {nid:dist} Contains the similarity of each neuron to the aggregated search query
        neuron_lookup = self._neu_index
        neuron_labels = [[k for (k,n) in Counter(neuron.get_keylist()).most_common()[:10]] for neuron in self._neurons]
        glomat = self._glomat # Global matrix. Contains similarity of each search term in the query to all neurons. Something like a cache.

        conn = SQLCon()
        searchvecs = [(x,list(conn.read(x))) for x in search_str.split() if not conn.read(x) is None] # Obtain (word,vec) of search terms
        search_len = len(searchvecs)
        for (w,v) in searchvecs:        # For colour coding the map
            try:
                for nid in glomat[w]:
                    if glomat[w][nid] > dist_neu_searchq[nid]:
                        dist_neu_searchq[nid] += glomat[w][nid]/search_len
            except KeyError:
                glomat[w]={}
                for nid,neuron in enumerate(self._neurons):
                    glomat[w][nid] = distance(neuron.get_weights(),v) # cosine similarity, hence 1 is best. 0 is bleh. -1 is opposite.
                    if glomat[w][nid] > dist_neu_searchq[nid]:
                        dist_neu_searchq[nid] += glomat[w][nid]/search_len


            # Union of all doclists with minimum dist_from_neuron. 
            doclist = {}
            for nid in dist_neu_searchq.most_common()[:depth]:
                neuron = neuron_lookup[nid[0]]
                doclist.update(neuron.get_top_docs(30))
            files = (open(doc) for doc in doclist)
            for json_file in files:
                data = json.load(json_file)
                centroids = data['centroids']
                url = data['url']
                json_file.close()
                wc_sim = [distance(v,c) for c in centroids]
                max_wc_sim = max(wc_sim)
                results[url] += max_wc_sim/len(searchvecs)

        results = OrderedDict(results.most_common(20))
        htmlVars = {'query': search_str, 'results':results}
        htmlCode = template.render(htmlVars)
        result_path = os.path.join(search_dir,search_str+'.html')
        map_path = os.path.join(search_dir,search_str+'_map.html')

        with open(result_path,'w') as f:
            f.write(htmlCode)
        self.draw_SOM(search_str,dist_neu_searchq,neuron_labels,map_path)


        result_path = "file://{}".format(pathname2url(result_path))
        map_path = "file://{}".format(pathname2url(map_path))
        webbrowser.open(result_path)
コード例 #9
0
def rectangle_dimensions(l1, l2, l3, l4):
    p1 = Line.find_intersection(l1, l3)
    p2 = Line.find_intersection(l2, l4)
    p3 = Line.find_intersection(l1, l4)
    p4 = Line.find_intersection(l2, l3)
    log.debug("Rectangle points: %s, %s, %s, %s." % (p1, p2, p3, p4))

    # p1 and p2 are diagonally opposite.
    w = utilities.distance(p1, p3)
    l = utilities.distance(p2, p3)
    log.debug("Length, Width: %f, %f." % (l, w))

    return ((p1, p2, p3, p4), (w, l))
コード例 #10
0
def rectangle_dimensions(l1, l2, l3, l4):
  p1 = Line.find_intersection(l1, l3)
  p2 = Line.find_intersection(l2, l4)
  p3 = Line.find_intersection(l1, l4)
  p4 = Line.find_intersection(l2, l3)
  log.debug("Rectangle points: %s, %s, %s, %s." % (p1, p2, p3, p4))

  # p1 and p2 are diagonally opposite.
  w = utilities.distance(p1, p3)
  l = utilities.distance(p2, p3)
  log.debug("Length, Width: %f, %f." % (l, w))

  return ((p1, p2, p3, p4), (w, l))
コード例 #11
0
 def calcul(self):
     
     self.centroid = estimate_centroid(self.data, self.label)
     label_new = np.argmin(distance(self.data, self.centroid), axis=1)
     
     # Complete the loop (steps 1 and 2 of Slide 18)
     while # Condition formalizing convergence of k-means!
         self.label = label_new
         # Step 2
         # Step 1
         
     self.label = label_new
     self.objective = np.mean(np.min(distance(self.data, self.centroid), axis=1)) 
コード例 #12
0
 def calcdisplaypoints(
     self
 ):  #//Calculate the location on the screen for the properties of the stream that is going to be displayed
     #//on the stream
     longestp0 = self.points[
         0]  #//Need to have a value accordingto compiler. point object, locar var
     longestp1 = self.points[1]  #point object, locar var
     tempp0 = point.point(0.0, 0.0)  #point object, locar var
     tempp1 = point.point(0.0, 0.0)  #point object, locar var
     distancebetweenpoints = 0.0  #double, local var
     furthestdistancebetweenpoints = 0.0  #double, local var
     if (len(self.inbetweenpoints) == 0):
         longestp0 = self.points[0]
         longestp1 = self.points[1]
     else:
         tempp0 = self.points[0]
         tempp1 = self.inbetweenpoints[0]
         distancebetweenpoints = utilities.distance(tempp0, tempp1)
         if (distancebetweenpoints > furthestdistancebetweenpoints):
             furthestdistancebetweenpoints = distancebetweenpoints
             longestp0 = self.points[0]
             longestp1 = self.inbetweenpoints[0]
         for i in range(len(self.inbetweenpoints)):
             tempp0 = self.inbetweenpoints[i - 1]
             tempp1 = self.inbetweenpoints[i]
             distancebetweenpoints = utilities.distance(tempp0, tempp1)
             if (distancebetweenpoints > furthestdistancebetweenpoints):
                 furthestdistancebetweenpoints = distancebetweenpoints
                 longestp0 = self.inbetweenpoints[i - 1]
                 longestp1 = self.inbetweenpoints[i]
         tempp0 = self.inbetweenpoints[-1]
         tempp1 = self.points[1]
         distancebetweenpoints = utilities.distance(tempp0, tempp1)
         if (distancebetweenpoints > furthestdistancebetweenpoints):
             furthestdistancebetweenpoints = distancebetweenpoints
             longestp0 = self.inbetweenpoints[-1]
             longestp1 = self.points[1]
     if (abs(longestp1.x - longestp0.x) > abs(longestp1.y - longestp0.y)):
         deltax = longestp1.x - longestp0.x  #double, local var
         for i in range(globe.StreamNrPropDisplay):
             self.displaypoints[i].x = longestp0.x + (i + 1) * deltax / (
                 globe.StreamNrPropDisplay + 1)
             self.displaypoints[i].y = longestp1.y
     else:
         deltay = longestp1.y - longestp0.y  #double local var
         for i in range(globe.StreamNrPropDisplay):
             self.displaypoints[i].x = longestp1.x
             self.displaypoints[i].y = longestp0.y + (i + 1) * deltay / (
                 globe.StreamNrPropDisplay + 1)
コード例 #13
0
def process_tile_data(game_map, previous_tile, current_tile, new_cost,
                      target_tile, closest_tile, frontier):
    tile_neighbors = tile_operations.get_adjacent_tiles(current_tile, game_map)
    for each in tile_neighbors:
        distance_to_target = utilities.distance(each.column, each.row,
                                                target_tile.column,
                                                target_tile.row)
        priority = distance_to_target + new_cost + each.cost
        frontier.put((priority, each, current_tile))
    distance_to_target = utilities.distance(current_tile.column,
                                            current_tile.row,
                                            target_tile.column,
                                            target_tile.row)
    if distance_to_target < closest_tile[0]:
        closest_tile = [distance_to_target, current_tile]
    return (new_cost, previous_tile)
コード例 #14
0
    def update_frontier(self, map_object):
        # floats.  closer to zero is a heavier weighting, greater than 0 is a higher weighting

        evaluated_tiles = {}
        self.frontier = queue.PriorityQueue()
        # print(len(self.settled_tiles))
        for settled_tile in self.settled_tiles:
            neighbors = tile_operations.get_adjacent_tiles(
                settled_tile, map_object)

            for neighbor_tile in neighbors:
                if neighbor_tile not in evaluated_tiles:
                    if not neighbor_tile.settlement:
                        neighboring_settlements = 0
                        new_neighbors = tile_operations.get_adjacent_tiles(
                            neighbor_tile, map_object)
                        for each in new_neighbors:
                            if each.settlement:
                                neighboring_settlements += 1
                        distance_from_center = utilities.distance(
                            self.x, self.y, neighbor_tile.column,
                            neighbor_tile.row)
                        central_place_score = distance_from_center * constants.CENTRAL_PLACE_WEIGHT * (
                            random.randint(1, constants.FUZZINESS))
                        open_space_score = (neighboring_settlements +
                                            1) * constants.OPEN_SPACE_WEIGHT
                        total_score = open_space_score + central_place_score
                        self.frontier.put((total_score, neighbor_tile))
                        evaluated_tiles[neighbor_tile] = True
                    else:
                        evaluated_tiles[neighbor_tile] = False
コード例 #15
0
ファイル: slam.py プロジェクト: djpetti/neato-software
  def check_landmark(self, location):
    # Check distance between this and all the known landmarks.
    best_landmark = None
    best_distance = sys.maxint
    for landmark in self.landmarks + self.new_landmarks:
      # Find the landmark that it's closest to.
      distance = utilities.distance(landmark.last_location, location)
      if distance < best_distance:
        best_distance = distance
        best_landmark = landmark

    if (best_landmark and best_landmark.validation_gate(location)):
      log.debug("Landmark at %s corresponds to landmark at %s." % \
          (location, best_landmark.last_location))

      best_landmark.sightings += 1
      best_landmark.last_location = location
      self.seen_this_cycle.append(landmark)

    else:
      log.debug("Found a new landmark at %s." % (str(location)))

      landmark = Landmark()
      landmark.last_location = location
      self.new_this_cycle.append(landmark)
コード例 #16
0
ファイル: goblin.py プロジェクト: z-van-baars/fishtank
 def find_pit(self):
     possible_homes = []
     for possible_home in self.current_room.entity_list[pit.Pit]:
         home_dist = utilities.distance(possible_home.rect.x, possible_home.rect.y, self.rect.x, self.rect.y)
         possible_homes.append((home_dist, possible_home))
     possible_homes = sorted(possible_homes)
     self.pit = possible_homes[0][1]
コード例 #17
0
ファイル: exit.py プロジェクト: noelano/Portal
    def update(self):
        """
        Check if the player has won
        """
        self.counter += 1

        # Check for menu selection
        if games.keyboard.is_pressed(games.K_m):
            self.game.levelMenu()

        if self.counter % 25 == 0:
            # Update score and timer each half second
            self.time = int(self.counter / 50)

        # Check if the player has reached the exit
        for sprite in self.overlapping_sprites:
            if sprite == self.game.player and self.active:
                if distance(self, sprite) < 20 and not self.message:
                    message = games.Message(value=self.end_message,
                                            size=30,
                                            color=color.white,
                                            x=games.screen.width/2,
                                            y=games.screen.height/2,
                                            lifetime=2 * games.screen.fps,
                                            after_death=self.game.levelComplete)
                    self.message = message
                    games.screen.add(message)
コード例 #18
0
def closestNodes(target):
    name1, ip1, coord1 = target
    # Get closest 10 PL Nodes
    distances = map(lambda node: (distance(coord1, (node.lat, node.lon)), node), pl_nodes)
    distances.sort()
    distances = map(lambda x: x[1], distances)
    return distances[:10]
コード例 #19
0
def perProcess():
    thread_queue = Queue.Queue(num_threads)
    threads = []
    for i in range(num_threads):
        t = threading.Thread(target=perThread, args=(thread_queue,))
        t.daemon = True
        t.start()
        threads.append(t)

    for i in range(round_length):
        while True:
            t1, t2 = select_random_points()
            dist = distance(t1[2], t2[2])
            if args.max and dist > args.max:
                continue
            elif dist <= args.min:
                continue
            else:
                break
        closest_nodes1 = closestNodes(t1)
        closest_nodes2 = closestNodes(t2)
        for node in closest_nodes1:
            thread_queue.put((t1, t2, node))
        for node in closest_nodes2:
            thread_queue.put((t2, t1, node))
コード例 #20
0
ファイル: app.py プロジェクト: fazlerahmanejazi/GIS-API
	def get(self, lat, lon, radius):
		Session = sessionmaker(db)
		session = Session()
		allData = session.query(data).all()
		new = data('-', '-', '-', lat, lon, 0)
		result = [i.pin for i in allData if distance(new, i) <= radius]
		return result
コード例 #21
0
ファイル: entity.py プロジェクト: z-van-baars/embark
 def using(self, game_state, my_coordinates, target_coordinates, target):
     self.moving(my_coordinates, target, target_coordinates)
     if utilities.distance(self.target_coordinates[0],
                           self.target_coordinates[1],
                           my_coordinates[0],
                           my_coordinates[1]) < 1.5:
         self.target_object.use(game_state)
         self.action = Action.idle
コード例 #22
0
ファイル: ogre.py プロジェクト: z-van-baars/fishtank
 def find_home(self):
     possible_homes = []
     for possible_home in self.current_room.entity_list[hut.Hut]:
         home_dist = utilities.distance(possible_home.rect.x + 20, possible_home.rect.y + 15, self.rect.x + 10, self.rect.y + 10)
         possible_homes.append((home_dist, possible_home))
     possible_homes = sorted(possible_homes)
     self.home_hut = possible_homes[0][1]
     self.home_hut.entity_list[Ogre].add(self)
コード例 #23
0
ファイル: agent.py プロジェクト: z-van-baars/leap
 def find_closest_station(self, target, station_group):
     closest_station = (None, None)
     for each in station_group.members:
         distance_from_target = utilities.distance(self.target[0], self.target[1], each.x, each.y)
         if not closest_station[0]:
             closest_station = (each, distance_from_target)
         if closest_station[0] and distance_from_target < closest_station[1]:
             closest_station = (each, distance_from_target)
     return closest_station
コード例 #24
0
 def set_central_places(self):
     central_tiles = queue.PriorityQueue()
     for each in self.settled_tiles:
         if each.settlement and each.settlement.size < 5:
             distance_from_center = utilities.distance(
                 self.x, self.y, each.column, each.row)
             priority = distance_from_center * (random.randint(
                 0, constants.CENTRAL_FUZZINESS))
             central_tiles.put((priority, each))
     return central_tiles
コード例 #25
0
ファイル: entity.py プロジェクト: z-van-baars/embark
 def moving(self, my_coordinates, target, target_coordinates):
     if self.time_since_last_move >= self.speed:
         self.time_since_last_move = 0
         change_x, change_y = self.calculate_step(my_coordinates, target, target_coordinates)
         self.move(change_x, change_y)
     if utilities.distance(self.target_coordinates[0],
                           self.target_coordinates[1],
                           my_coordinates[0],
                           my_coordinates[1]) < 1:
             self.action = Action.idle
コード例 #26
0
def find_deflections(table, arm, puck_pose, deflections=[]):
    """
    Calculates the full trajectory of a puck including all its different
    deflections from wall sides. NOTE: modifies the puck_pose, so need to
    pass in a deep copy at the start. NOTE: requires the cartesian coordinate
    frame, so need to transform graphics coordinates to cartesian.
    Cases:
        - puck bounces off wall like normal
        - puck never bounces off wall before reaching arm
        - puck reaches final bounce location in which case:
            - its distance from arm base is within reach of arm
            - OR its next deflection_y is beyond the table bounds
    :param deflections: list of tuples that contain the (x, y, vx, vy, time) of
    deflection
    """
    p_copy = copy.deepcopy(puck_pose)
    reach_radius = arm.link_length * arm.num_links
    assert (0 <= p_copy.x <= table.width)
    # (vx == 0) implies puck moving straight down, no wall deflections
    if p_copy.vx == 0:  # avoid division by zero error first
        return deflections
    elif p_copy.vx > 0:  # moving right
        assert (table.width > p_copy.x)
        time_deflection = (table.width - p_copy.x) / p_copy.vx
        p_copy.x = table.width  # next x position right after deflection
    else:  #   moving left
        time_deflection = (0 - p_copy.x) / p_copy.vx
        p_copy.x = 0
    p_copy.vx *= -1
    assert (time_deflection > 0)
    p_copy.y = p_copy.y + p_copy.vy * time_deflection

    # angle too shallow, will never collide with wall before reaching arm
    if p_copy.y < arm.y:
        return deflections
    dist_from_base = util.distance(arm.x, arm.y, p_copy.x, p_copy.y)
    # no need to transform or keep, previous pose will lead puck to arms
    if dist_from_base <= reach_radius:
        return deflections
    if len(deflections) > 0: prev_time = deflections[-1][4]
    else: prev_time = 0
    try:
        collision = vector_circle_intersect(arm, puck_pose)
        deflections.append([
            collision.x, collision.y, puck_pose.vx, puck_pose.vy,
            prev_time + collision.time_to_collision
        ])
        return deflections
    except util.NoSolutionError:
        # -1 to account for collided puck, simply have puck move in opposite dir
        deflections.append([
            p_copy.x, p_copy.y, p_copy.vx, p_copy.vy,
            prev_time + time_deflection
        ])
        return find_deflections(table, arm, p_copy, deflections)
コード例 #27
0
ファイル: surfaces.py プロジェクト: noelano/Portal
 def handleBottom(self, sprite):
     if self.orientation == 3 and Surface.bluePortal and Surface.orangePortal:
         sprite.dy += 0.02
         if distance(self, sprite) <= 10:
             if self.colour == 0:
                 self.teleportBlue(sprite)
             else:
                 self.teleportOrange(sprite)
     else:
         sprite.dy = 0
         sprite.top = self.bottom
コード例 #28
0
ファイル: groups.py プロジェクト: z-van-baars/leap
 def new_station(self, tile):
     closest_station = 10000
     for each in self.members:
         station_distance = utilities.distance(tile.column, tile.row,
                                               each.x, each.y)
         if station_distance < closest_station:
             closest_station = station_distance
     if closest_station >= constants.MIN_STATION_DISTANCE:
         new_station = buildings.TrainStation(tile.column, tile.row)
         tile.train_station = new_station
         self.members.append(new_station)
コード例 #29
0
ファイル: organism.py プロジェクト: z-van-baars/fishtank
    def pick_target_local(self):
        nearby_targets = self.current_chunk.entity_list[self.food_type]

        targets_to_sort = []
        for target in nearby_targets:
            dist = utilities.distance(target.rect.x, target.rect.y, self.rect.x, self.rect.y)
            targets_to_sort.append((dist, target))

        possible_targets = sorted(targets_to_sort)
        if possible_targets:
            return possible_targets[0][1]
コード例 #30
0
ファイル: agent.py プロジェクト: z-van-baars/leap
    def set_vector(self, a, b, x, y):
        # A B pair is Target Coordinates
        # X Y pair is Agent Coordinates
        speed = 1
        distance_to_target = utilities.distance(a, b, x, y)
        factor = distance_to_target / speed
        x_dist = a - x
        y_dist = b - y
        change_x = x_dist / factor
        change_y = y_dist / factor

        return (change_x, change_y)
コード例 #31
0
ファイル: goblin.py プロジェクト: z-van-baars/fishtank
    def go_home(self):
        home_x = self.pit.rect.x + 15
        home_y = self.pit.rect.y + 15

        home_dist = utilities.distance((home_x), (home_y), self.rect.x, self.rect.y)
        if home_dist > 38:
            changes = utilities.get_vector(self, home_x, home_y, self.rect.x + 10, self.rect.y + 10)
            self.change_x = changes[0]
            self.change_y = changes[1]
        else:
            self.give_coins()

        self.coin_pickup(self.current_room)
コード例 #32
0
ファイル: surfaces.py プロジェクト: noelano/Portal
 def handleTop(self, sprite):
     if self.orientation == 0 and Surface.bluePortal and Surface.orangePortal and abs(self.x - sprite.x) < 30:
         sprite.x = self.x
         if sprite.dy == 0:
             sprite.dy += 0.5
         if distance(self, sprite) <= 10:
             if self.colour == 0:
                 self.teleportBlue(sprite)
             else:
                 self.teleportOrange(sprite)
     else:
         sprite.dy = 0
         sprite.bottom = self.top + 1
コード例 #33
0
ファイル: surf.py プロジェクト: gablank/UNIK4690
        def filter_pig_detected_as_playing_ball(kps, pig):
            if pig is None:
                return kps
            res = []
            for kp in kps:
                pig_r = pig[1]
                d = utilities.distance(kp.pt, pig[0])
                # Reject kps that overlap with the pig
                # A bit conservative? Maybe only reject kp if its center is within the pig radius?
                if kp.size/2+pig_r < d:
                    res.append(kp)

            return res
コード例 #34
0
    def mouseover(self, x,
                  y):  #public override bool mouseover(double x, double y)
        streamover = False  #default bool local var
        pixelstoclosestpoint = 999999999.0  #double local var
        pixelstopoint = 0  #local var

        for i in range(2):
            pixelstopoint = utilities.distance(
                x - self.points[i].x, y - self.points[i].y) * globe.GScale
            if (pixelstopoint < pixelstoclosestpoint):
                pixelstoclosestpoint = pixelstopoint
        for i in range(len(self.inbetweenpoints)):
            pixelstopoint = utilities.distance(
                x - self.inbetweenpoints[i].x,
                y - self.inbetweenpoints[i].y) * globe.GScale
            if (pixelstopoint < pixelstoclosestpoint):
                pixelstoclosestpoint = pixelstopoint
        if (pixelstoclosestpoint <= globe.MinDistanceFromStream):
            streamover = True
        else:
            streamover = False
        return streamover
コード例 #35
0
def explore_frontier_to_target(game_map, visited, target_tile, closest_tile,
                               frontier):
    while not frontier.empty():
        priority, current_tile, previous_tile = frontier.get()
        new_cost = visited[previous_tile][0] + 1
        if current_tile not in visited or new_cost < visited[current_tile][0]:
            tile_neighbors = tile_operations.get_adjacent_tiles(
                current_tile, game_map)
            for each in tile_neighbors:
                distance_to_target = utilities.distance(
                    each.column, each.row, target_tile.column, target_tile.row)
                priority = (distance_to_target *
                            each.cost) + new_cost + each.cost
                frontier.put((priority, each, current_tile))
            distance_to_target = utilities.distance(current_tile.column,
                                                    current_tile.row,
                                                    target_tile.column,
                                                    target_tile.row)
            if distance_to_target < closest_tile[0]:
                closest_tile = [distance_to_target, current_tile]
            visited[current_tile] = (new_cost, previous_tile)
        if target_tile in visited:
            break
    return visited, closest_tile
コード例 #36
0
 def __init__(self, data, k, seed=None):
     """
     Args:
         data: unlabeled data
         k: number of cluster
     Class Attributes:
         self.data: unlabeled data
         self.centroid: cluster centers
         self.label: label 
         self.iteration: number of iteration before k-means converges
     """
     
     self.data = data
     self.centroid = initiate(data, k)
     self.label = np.argmin(distance(self.data, self.centroid ), axis=1)
コード例 #37
0
    def get_vehicles_in_radius(self, radius):
        """
        Returns the list of vehicles in the radius given of this member.
        """

        ids = []
        gathered_vehicles = []

        for i, v in enumerate(platoon_member.search_vehicles):
            if utilities.distance(self.v.get_coordinates(),
                                  v.get_coordinates()) <= radius:
                ids.append(i)
                gathered_vehicles.append(v)

        for i in reversed(ids):
            platoon_member.search_vehicles.pop(i)

        return gathered_vehicles
コード例 #38
0
def optimize(data, timer, tracer:Tracer):
    remaining_cities = list(data)
    first_city = random.choice(remaining_cities)
    greedy_path = [first_city]
    current_cost = utilities.tour_cost(remaining_cities)

    while len(remaining_cities) > 0 and timer(q=current_cost):
        best_city_index = None
        best_score = float('inf')
        for i, city in enumerate(remaining_cities):
            score = utilities.distance(greedy_path[-1], city)
            if score < best_score:
                best_city_index = i
                best_score = score
        greedy_path.append(remaining_cities.pop(best_city_index))
        current_cost = utilities.tour_cost(greedy_path + remaining_cities)
        tracer.next_result(current_cost)

    final_cost = utilities.tour_cost(greedy_path)
    return final_cost, greedy_path
コード例 #39
0
ファイル: organism.py プロジェクト: ChadSki/fishtank
    def pick_target(self, neighbors):
        nearby_targets = self.current_chunk.entity_list[self.food_type]
        for chunk in neighbors:
            for target in chunk.entity_list[self.food_type]:
                nearby_targets.add(target)

        targets_to_sort = []
        for target in nearby_targets:
            dist = utilities.distance(target.rect.x, target.rect.y, self.rect.x, self.rect.y)
            targets_to_sort.append((dist, target))
            
        possible_targets = sorted(targets_to_sort)
        if possible_targets:
            return possible_targets[0][1]
        else:
            far_afield = list(self.current_room.entity_list[self.food_type])
            if far_afield:
                return random.choice(far_afield)
            else:
                return None
コード例 #40
0
ファイル: ogre.py プロジェクト: z-van-baars/fishtank
        def go_home(self, home_x, home_y):

            home_dist = utilities.distance((home_x + 20), (home_y + 15), self.rect.x + 10, self.rect.y + 10)
            if home_dist > 75:
                changes = utilities.get_vector(self, self.home_hut.rect.x + 20, self.home_hut.rect.y + 15, self.rect.x + 10, self.rect.y + 10)
                self.change_x = changes[0]
                self.change_y = changes[1]
            else:
                action = random.randint(0, 800)
                if action <= 10:
                    self.change_x = (self.speed / 2)
                elif 10 < action <= 20:
                    self.change_x = -(self.speed / 2)
                elif 20 < action <= 30:
                    self.change_y = (self.speed / 2)
                elif 30 < action <= 40:
                    self.change_y = -(self.speed / 2)
                elif action > 750:
                    self.change_x = 0
                    self.change_y = 0
コード例 #41
0
ファイル: pgoapi.py プロジェクト: 05-032/PokemonGo-Bot
    def walk(self, speed, lat, lng, alt,walking_hook):
        dist = distance(i2f(self._position_lat), i2f(self._position_lng), lat, lng)
        steps = (dist+0.0)/(speed+0.0) # may be rational number
        intSteps = int(steps)
        residuum = steps - intSteps
        print '[#] Walking from ' + str((i2f(self._position_lat), i2f(self._position_lng))) + " to " + str(str((lat, lng))) + " for approx. " + str(ceil(steps)) + " seconds"

        if steps != 0:
            dLat = (lat - i2f(self._position_lat)) / steps
            dLng = (lng - i2f(self._position_lng)) / steps

            for i in range(intSteps):
                self.set_position(i2f(self._position_lat) + dLat + self.random_lat_long(), i2f(self._position_lng) + dLng + self.random_lat_long(), alt)
                self.heartbeat()
                if walking_hook:
                    walking_hook(i)
                time.sleep(1 + self.random_sleep()) # sleep one second plus a random delta

            self.set_position(lat, lng, alt)
            self.heartbeat()
        print "[#] Finished walking to " + str(str((lat, lng)))
コード例 #42
0
def getNeighborPoints(center_point, radius, curve_type, pose_number):
    vertices_data = PlyData.read('./Mesh/results/8 frames/' + curve_type +
                                 pose_number + '.ply')['vertex']
    count = vertices_data.count
    vertices = np.empty((count, 5))
    vertices[:, 0] = vertices_data['x']
    vertices[:, 1] = vertices_data['y']
    vertices[:, 2] = vertices_data['z']
    vertices[:, 3] = vertices_data['quality']
    vertices[:, 4] = vertices_data['nz']
    try:
        ctr = vertices[center_point]
    except:
        print("center point's outside the data")
        return False
    temp = []
    index = []
    for i in range(count):
        if uti.distance(vertices[i][:3], ctr) <= radius and vertices[i][4] > 0:
            temp.append(vertices[i])
            index.append(i)
    return np.asarray(temp), index
コード例 #43
0
ファイル: organism.py プロジェクト: z-van-baars/fishtank
    def pick_target(self, neighbors, backup_list):
        nearby_targets = pygame.sprite.Group()
        for chunk in neighbors:
            for target in chunk.entity_list[self.food_type]:
                nearby_targets.add(target)

        targets_to_sort = []
        for target in nearby_targets:
            dist = utilities.distance(target.rect.x, target.rect.y, self.rect.x, self.rect.y)
            targets_to_sort.append((dist, target))

        possible_targets = sorted(targets_to_sort)
        if possible_targets:
            return possible_targets[0][1]
        else:
            far_afield = None
            if backup_list is not None:
                far_afield = list(backup_list.entity_list[self.food_type])
            if far_afield:
                return random.choice(far_afield)
            else:
                return None
コード例 #44
0
ファイル: ogre.py プロジェクト: z-van-baars/fishtank
    def do_thing(self):
        if not self.home_hut:
            if self.current_room.entity_list[hut.Hut]:
                self.find_home()
        self.age += 1
        self.ticks_without_food += 1
        home_dist = 0
        if not self.dead():
            if self.current_chunk_row is None or \
               self.current_chunk_column is None:
                self.place_in_chunk(self.current_room)
            if self.home_hut:
                home_x = self.home_hut.rect.x + 20
                home_y = self.home_hut.rect.y + 15
                home_dist = utilities.distance(home_x, home_y, self.rect.x + 10, self.rect.y + 10)
                if home_dist < 200:
                    if self.home_hut.entity_list[goblin.Goblin]:
                        if self.target_goblin is None or self.target_goblin not in self.home_hut.entity_list[goblin.Goblin]:
                            if home_dist < 80:
                                self.target_goblin = self.pick_target(self.home_hut.neighbors, None)
                        else:
                            self.chase(self.current_room)
                    else:
                        self.idle()
                if home_dist >= 200:
                    self.idle()
                    self.target_goblin = None
            else:
                if self.current_room.entity_list[goblin.Goblin]:
                    self.target_goblin = self.pick_target(self.neighbors, self.current_room)
                    self.chase(self.current_room)
                else:
                    self.idle()
            self.get_frame()

            self.move(self.current_room, self.current_chunk)
            if self.goblins_eaten > 39:
                self.reproduce(self.current_room)
コード例 #45
0
ファイル: slam.py プロジェクト: avappel/neato-software
    def check_landmark(self, location):
        # Check distance between this and all the known landmarks.
        best_landmark = None
        best_distance = sys.maxint
        for landmark in self.landmarks + self.new_landmarks:
            # Find the landmark that it's closest to.
            distance = utilities.distance(landmark.last_location, location)
            if distance < best_distance:
                best_distance = distance
                best_landmark = landmark

        if (best_landmark and best_landmark.validation_gate(location)):
            log.debug("Landmark at %s corresponds to landmark at %s." % \
                (location, best_landmark.last_location))

            best_landmark.sightings += 1
            best_landmark.last_location = location

        else:
            log.debug("Found a new landmark at %s." % (str(location)))

            landmark = Landmark()
            landmark.last_location = location
            self.new_this_cycle.append(landmark)
コード例 #46
0
 def updatedirection(self):
     self.direction = utilities.calcdirection(
         self.points[1].y - self.points[0].y,
         self.points[1].x - self.points[0].x)
     self.distance = utilities.distance(self.points[0], self.points[1])
コード例 #47
0
    def _generate_bounding_rect(self):
        if self.link.link_num % 2 == 0:
            targetDistance = self.link.link_num * 5
        else:
            targetDistance = (-self.link.link_num + 1) * 5
        # hours of calculation and still can't figure out where it's wrong
        n1_p = Vector(*self.source_node.get_position())
        n2_p = Vector(*self.link.target.get_position())
        x1_x0 = n2_p[0] - n1_p[0]
        y1_y0 = n2_p[1] - n1_p[1]

        if y1_y0 == 0:
            x2_x0 = 0
            y2_y0 = targetDistance
        else:

            angle = math.atan((x1_x0) / (y1_y0))
            x2_x0 = -targetDistance * math.cos(angle)
            y2_y0 = targetDistance * math.sin(angle)

        d0x = n1_p[0] + (1 * x2_x0)
        d0y = n1_p[1] + (1 * y2_y0)
        d1x = n2_p[0] + (1 * x2_x0)
        d1y = n2_p[1] + (1 * y2_y0)

        dx = (d1x - d0x,)
        dy = (d1y - d0y,)

        dr = math.sqrt(dx[0] * dx[0] + dy[0] * dy[0])

        endX = (d1x + d0x) / 2
        endY = (d1y + d0y) / 2

        len1 = dr - ((dr / 2) * math.sqrt(3))
        endX = endX + (len1 / dr)
        endY = endY + (len1 / dr)

        n1_p = Vector(d0x, d0y)
        n2_p = Vector(endX, endY)

        uv = (n2_p - n1_p).unit()
        d = distance(n1_p, n2_p)
        r = self.link.target.get_radius()
        arrow_head_pos = n2_p
        d = distance(n1_p, arrow_head_pos)
        uv_arrow = (arrow_head_pos - n1_p).unit()
        arrow_base_pos = n1_p + uv_arrow * (d - 2 * 2)
        nv_arrow = uv_arrow.rotated(math.pi / 2)
        # text
        if endX - d0x > 0:
            link_paint = QLineF(QPointF(d0x, d0y), QPointF(endX, endY))
        else:
            link_paint = QLineF(QPointF(endX, endY), QPointF(d0x, d0y))

        mid = (arrow_base_pos + n1_p) / 2
        w_len = len(str(self.link.metric)) / 3 * r + r / 3
        weight_v = Vector(w_len, 2)
        weight_rectangle = QRectF(*(mid - weight_v), *(2 * weight_v))
        center_of_rec_x = weight_rectangle.center().x()
        center_of_rec_y = weight_rectangle.center().y()

        new_rec = QRectF(
            center_of_rec_x - 10, center_of_rec_y - 10, 20, 20
        ).normalized()
        return new_rec
コード例 #48
0
    def paint(self, painter, option, widget=None):
        super(Link, self).paint(painter, option, widget)
        util = self.link.utilization()
        orangeColor = QColor(255, 165, 0)

        colour_values = {
            self.blue_threshold: QtCore.Qt.blue,
            self.green_threshold: QtCore.Qt.green,
            self.yellow_threshold: QtCore.Qt.yellow,
            self.orange_threshold: orangeColor,
        }

        colour_values_list = sorted(colour_values)
        link_color_index = bisect_left(colour_values_list, util)

        if self.link._failed:
            link_color = QtCore.Qt.red
        elif util == 0:
            link_color = QtCore.Qt.black
        elif util > int(orange_threshold):
            link_color = QtCore.Qt.magenta
        else:
            try:
                link_color_key = colour_values_list[link_color_index]
                link_color = colour_values[link_color_key]
                # print(util, link_color, link_color_index, link_color_key)
            except:
                # guard agains <100% thresholds value
                link_color = QtCore.Qt.magenta
        painter.save()
        painter.setFont(QFont(self.font_family, self.font_size / 3))

        if self.link.link_num % 2 == 0:
            targetDistance = self.link.link_num * 5
        else:
            targetDistance = (-self.link.link_num + 1) * 5
        # hours of calculation and still can't figure out where it's wrong
        n1_p = Vector(*self.source_node.get_position())
        n2_p = Vector(*self.link.target.get_position())
        x1_x0 = n2_p[0] - n1_p[0]
        y1_y0 = n2_p[1] - n1_p[1]

        if y1_y0 == 0:
            x2_x0 = 0
            y2_y0 = targetDistance
        else:
            angle = math.atan((x1_x0) / (y1_y0))
            x2_x0 = -targetDistance * math.cos(angle)
            y2_y0 = targetDistance * math.sin(angle)

        d0x = n1_p[0] + (1 * x2_x0)
        d0y = n1_p[1] + (1 * y2_y0)
        d1x = n2_p[0] + (1 * x2_x0)
        d1y = n2_p[1] + (1 * y2_y0)

        dx = (d1x - d0x,)
        dy = (d1y - d0y,)

        dr = math.sqrt(dx[0] * dx[0] + dy[0] * dy[0])

        endX = (d1x + d0x) / 2
        endY = (d1y + d0y) / 2

        len1 = dr - ((dr / 2) * math.sqrt(3))
        endX = endX + (len1 / dr)
        endY = endY + (len1 / dr)
        n1_p = Vector(d0x, d0y)
        n2_p = Vector(endX, endY)
        uv = (n2_p - n1_p).unit()
        d = distance(n1_p, n2_p)
        r = self.link.target.get_radius()
        arrow_head_pos = n2_p
        d = distance(n1_p, arrow_head_pos)
        uv_arrow = (arrow_head_pos - n1_p).unit()
        arrow_base_pos = n1_p + uv_arrow * (d - 2 * 2)
        nv_arrow = uv_arrow.rotated(math.pi / 2)

        painter.setRenderHints(
            QtGui.QPainter.Antialiasing
            | QtGui.QPainter.TextAntialiasing
            | QtGui.QPainter.SmoothPixmapTransform
            | QtGui.QPainter.HighQualityAntialiasing,
            True,
        )
        if self.link.highlight:
            painter.setPen(QPen(link_color, 3, 3))
        elif option.state & QtWidgets.QStyle.State_Selected:
            painter.setPen(QPen(link_color, 2, 4))
        else:
            painter.setPen(QPen(link_color, Qt.SolidLine))

        painter.setBrush(QBrush(link_color, Qt.SolidPattern))

        painter.drawPolygon(
            QPointF(*arrow_head_pos),
            QPointF(*(arrow_base_pos + nv_arrow * 2)),
            QPointF(*(arrow_base_pos - nv_arrow * 2)),
        )

        painter.drawLine(QPointF(d0x, d0y), QPointF(endX, endY))
        painter.setPen(QtGui.QPen(link_color, 1))
        # text
        if endX - d0x > 0:
            link_paint = QLineF(QPointF(d0x, d0y), QPointF(endX, endY))
        else:
            link_paint = QLineF(QPointF(endX, endY), QPointF(d0x, d0y))
        mid = (arrow_base_pos + n1_p) / 2
        if self.show_latency:
            w_len = (
                len(str(self.link.metric) + str(self.link.latency) + "------") / 3 * r
                + r / 3
            )
        else:
            w_len = len(str(self.link.metric)) / 3 * r + r / 3
        weight_v = Vector(w_len, 2)
        weight_rectangle = QRectF(*(mid - weight_v), *(2 * weight_v))
        painter.save()
        center_of_rec_x = weight_rectangle.center().x()
        center_of_rec_y = weight_rectangle.center().y()
        painter.translate(center_of_rec_x, center_of_rec_y)
        rx = -(weight_v[0] * 0.5)
        ry = -(weight_v[1])
        painter.rotate(-link_paint.angle())
        new_rec = QRect(rx, ry, weight_v[0], 2 * weight_v[1])

        if self.link._failed:
            painter.setBrush(QBrush(Qt.red, Qt.SolidPattern))

        elif option.state & QtWidgets.QStyle.State_Selected:
            pass

        painter.setBrush(QBrush(Qt.black, Qt.SolidPattern))

        painter.setPen(QtGui.QPen(Qt.black, Qt.SolidLine))
        painter.drawRect(QRect(rx, ry, weight_v[0], 2 * weight_v[1]))
        painter.setFont(QFont(self.font_family, self.font_size / 3.3))
        painter.setPen(QPen(Qt.white, Qt.SolidLine))
        if self.show_latency:
            painter.drawText(
                new_rec,
                Qt.AlignCenter,
                str(self.link.metric) + " -- " + str(self.link.latency) + "/ms",
            )
        else:
            painter.drawText(new_rec, Qt.AlignCenter, str(self.link.metric))

        painter.restore()

        painter.restore()
コード例 #49
0
    cur.close()
    exit(0)

cur = connection.cursor()
cur.execute("SELECT * from data where success;")
if arguments.csv:
    seen = defaultdict(int)
    results = []
    print 't1, t2, distance, latency, test_point'
    for r in cur:
        id, timestamp, name1, name2, target1, target2, start, end, pings, address, test_point, success = r

        target1 = pickle.loads(target1)
        target2 = pickle.loads(target2)
        
        dist = distance(target1[2], target2[2])

        start = pickle.loads(start)
        end = pickle.loads(end)
        pings = pickle.loads(pings)
                
                # the minimum makes more sense than average actually
        latency = (end - start - min(pings)).total_seconds()
        address = pickle.loads(address)

                # speed-of-light limit violation. check them manually
        if latency < (dist/3.0/100000):
                    pass
                    # print "++++++++++++++++++++++++++"
                    # print 'Target1:', name1, target1
                    # print 'Target2:', name2, target2
コード例 #50
0
    def detect(self, image):
        best_transformation = self.transformer.get_playground_transformation(image)
        # cv2.imwrite("/home/anders/UNIK4690/project/report/playground_detection_pipeline/step_2_best_transformation.png", utilities.as_uint8(best_transformation))
        # return

        best_transformation = utilities.as_uint8(best_transformation)
        middle = utilities.get_middle(best_transformation)
        box = utilities.get_box(best_transformation, middle, 100)
        if np.average(box) > np.average(best_transformation):
            print("Inverting image")
            best_transformation = 255 - best_transformation
            box = utilities.get_box(best_transformation, middle, 100)

        # cv2.imwrite("/home/anders/UNIK4690/project/report/playground_detection_pipeline/step_3_invert.png", utilities.as_uint8(best_transformation))
        blur_size = 5
        best_transformation = cv2.blur(best_transformation, (blur_size, blur_size))
        # cv2.imwrite("/home/anders/UNIK4690/project/report/playground_detection_pipeline/step_4_blur.png", utilities.as_uint8(best_transformation))

        box_hist = utilities.get_histogram(box)
        box_hist /= sum(box_hist)
        argmax = np.argmax(box_hist)
        cur = argmax
        low = argmax
        high = argmax
        tot_sum = 0.0
        while tot_sum < 0.9:
            tot_sum += box_hist[cur]
            if high == 255:
                cur = low - 1
            elif low == 0:
                cur = high + 1
            else:
                if box_hist[high+1] > box_hist[low-1]:
                    cur = high + 1
                else:
                    cur = low - 1
            low = min(low, cur)
            high = max(high, cur)

        def threshold_range(img, lo, hi):
            th_lo = cv2.threshold(img, lo, 255, cv2.THRESH_BINARY)[1]
            th_hi = cv2.threshold(img, hi, 255, cv2.THRESH_BINARY_INV)[1]
            return cv2.bitwise_and(th_lo, th_hi)
        print("Thresholding between {} and {}".format(low, high))

        best_transformation = threshold_range(best_transformation, low, high)
        # cv2.imwrite("/home/anders/UNIK4690/project/report/playground_detection_pipeline/step_5_threshold.png", utilities.as_uint8(best_transformation))

        # ret, best_transformation = cv2.threshold(best_transformation, idx, 255, cv2.THRESH_TOZERO)
        box = utilities.get_box(best_transformation, middle, 100)
        box[:,:] = 255

        best_transformation[np.where(best_transformation == 255)] = 254

        num_filled, best_transformation, _, _ = cv2.floodFill(best_transformation, None, middle, 255, upDiff=0, loDiff=0, flags=cv2.FLOODFILL_FIXED_RANGE)

        best_transformation[np.where(best_transformation != 255)] = 0
        # cv2.imwrite("/home/anders/UNIK4690/project/report/playground_detection_pipeline/step_6_flood_fill.png", utilities.as_uint8(best_transformation))

        kernel_size = 3
        iterations = 1
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size,kernel_size))
        best_transformation = cv2.erode(best_transformation, kernel, iterations=iterations)
        best_transformation = cv2.dilate(best_transformation, kernel, iterations=iterations-1)
        # cv2.imwrite("/home/anders/UNIK4690/project/report/playground_detection_pipeline/step_7_opening.png", utilities.as_uint8(best_transformation))

        best_transformation[np.where(best_transformation == 255)] = 254
        num_filled, best_transformation, _, _ = cv2.floodFill(best_transformation, None, middle, 255, upDiff=0, loDiff=0, flags=cv2.FLOODFILL_FIXED_RANGE)
        best_transformation[np.where(best_transformation != 255)] = 0
        # cv2.imwrite("/home/anders/UNIK4690/project/report/playground_detection_pipeline/step_8_flood_fill_2.png", utilities.as_uint8(best_transformation))

        im2, contours, hierarchy = cv2.findContours(best_transformation.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

        if len(contours) > 0:
            # IDEA: For each vertex, see if the density inside the triangle made by connecting this vertex with the previous
            # and next vertices are much less than the density of the entire convex hull.
            # If it is, we should probably remove this vertex as it is the result
            #  of a "thin arm" that the flood fill followed.
            polygon = contours[0]
            for idx in range(1, len(contours)):
                polygon = np.concatenate((polygon, contours[idx]))

            convex_hull = cv2.convexHull(polygon)

            convex_hull = cv2.approxPolyDP(convex_hull, 5, True)
            original_convex_hull = convex_hull.copy()

            convex_hull_as_list = []
            for idx in range(len(convex_hull)):
                vertex = convex_hull[idx][0]
                convex_hull_as_list.append((vertex[0], vertex[1]))

            temp = best_transformation.copy()
            temp[np.where(temp == 255)] = 120
            for idx, v1 in enumerate(convex_hull_as_list):
                cv2.line(temp, v1, convex_hull_as_list[(idx+1)%len(convex_hull_as_list)], 255, 3)
            # cv2.imwrite("/home/anders/UNIK4690/project/report/playground_detection_pipeline/step_9_convex_hull.png", utilities.as_uint8(temp))

            convex_hull_mask = utilities.poly2mask(convex_hull, best_transformation)
            best_transformation[np.where(convex_hull_mask == 0)] = 0
            convex_hull_n = np.count_nonzero(convex_hull_mask)
            convex_hull_n_white = np.count_nonzero(best_transformation[np.where(convex_hull_mask != 0)])
            convex_hull_density = convex_hull_n_white / convex_hull_n
            # print("Convex hull density:", convex_hull_density)
            copy = best_transformation.copy()

            # utilities.show(convex_hull_mask, time_ms=10)
            outside_convex_hull_color = 0
            outside_triangle_not_filled_color = int(1/6 * 255)
            outside_triangle_filled_color = int(2/3 * 255)
            inside_triangle_not_filled_color = int(2/6 * 255)
            inside_triangle_filled_color = 255

            copy[np.where(convex_hull_mask == 0)] = outside_convex_hull_color
            copy[np.where((convex_hull_mask != 0) & (copy != 0))] = outside_triangle_filled_color
            copy[np.where((convex_hull_mask != 0) & (copy == 0))] = outside_triangle_not_filled_color

            # utilities.show(best_transformation, time_ms=0)

            new_convex_hull = []

            #import transformer
            #from image import Image
            #light_mask = transformer.Transformer.get_light_mask(Image(image_data=img))

            idx = 0
            isd = 0
            while idx < len(convex_hull_as_list):
                temp = best_transformation.copy()
                temp[np.where(temp == 255)] = 120

                v1 = convex_hull_as_list[(idx-1)%len(convex_hull_as_list)]
                v2 = convex_hull_as_list[idx]
                v3 = convex_hull_as_list[(idx+1)%len(convex_hull_as_list)]

                triangle_mask = utilities.poly2mask([v1, v2, v3], best_transformation)

                # temp[np.where((triangle_mask != 0) & (temp != 0))] = 255
                # temp[np.where((triangle_mask != 0) & (temp == 0))] = 60
                # utilities.show(temp)
                # cv2.imwrite("/home/anders/UNIK4690/project/report/playground_detection_pipeline/step_10_{}_convex_hull_refinement.png".format(isd), utilities.as_uint8(temp))
                isd += 1
                copy[np.where((triangle_mask == 0) & (copy == inside_triangle_filled_color))] = outside_triangle_filled_color
                copy[np.where((triangle_mask == 0) & (copy == inside_triangle_not_filled_color))] = outside_triangle_not_filled_color

                copy[np.where((triangle_mask != 0) & (copy == outside_triangle_filled_color))] = inside_triangle_filled_color
                copy[np.where((triangle_mask != 0) & (copy == outside_triangle_not_filled_color))] = inside_triangle_not_filled_color

                triangle_n_white = np.count_nonzero(best_transformation[np.where(triangle_mask != 0)])
                triangle_n = np.count_nonzero(triangle_mask)
                triangle_density = triangle_n_white / triangle_n

                #light_density = np.count_nonzero(light_mask[np.where(triangle_mask != 0)]) / triangle_n

                limit = 0.4*convex_hull_density# + light_density / 2
                # utilities.show(copy, text="Triangle density: {}, limit: {}".format(round(triangle_density, 2), round(limit, 2)))
                if triangle_density > limit:
                    new_convex_hull.append(v2)
                    idx += 1
                else:
                    best_transformation[np.where(triangle_mask != 0)] = 0
                    convex_hull_as_list.remove(v2)
                    copy[np.where(triangle_mask != 0)] = outside_convex_hull_color

            def show_lines(image, pts):
                # to_show = image.get_bgr().copy()
                to_show = utilities.as_float32(image.original_bgr)
                # to_show = image.copy()
                # to_show[:,:] = 0
                for idx, pt1 in enumerate(pts):
                    if idx % 2 == 0:
                        color = (0, 0, 1)
                    else:
                        color = (1, 0, 0)
                    pt2 = pts[(idx+1) % len(pts)]
                    cv2.line(to_show, pt1, pt2, color, 3)
                # cv2.imwrite("/home/anders/UNIK4690/project/report/playground_detection_pipeline/step_11_result_2.png", utilities.as_uint8(to_show))
                utilities.show(to_show, text=image.filename, time_ms=30)

            # show_lines(best_transformation, new_convex_hull)

            convex_hull = []
            for idx, pt in enumerate(new_convex_hull):
                angle = utilities.get_angle(new_convex_hull[(idx-1)%len(new_convex_hull)], pt, new_convex_hull[(idx+1)%len(new_convex_hull)])
                if 15 < angle < 180-15:
                    convex_hull.append(pt)

            new_convex_hull = convex_hull
            # show_lines(image, new_convex_hull)

            angles = []
            for idx, pt in enumerate(new_convex_hull):
                angles.append((pt, utilities.get_angle(new_convex_hull[(idx-1)%len(new_convex_hull)], pt, new_convex_hull[(idx+1)%len(new_convex_hull)])))

            angles.sort(key=lambda x: x[1], reverse=True)

            lines = []
            for idx, pt in enumerate(new_convex_hull):
                pt2 = new_convex_hull[(idx+1)%len(new_convex_hull)]
                lines.append((pt, pt2, idx))

            # sort by line length
            lines.sort(key=lambda x: utilities.distance(x[0], x[1]))

            top_four = list(lines[-4:])
            top_four.sort(key=lambda x: x[2])

            points = []
            for idx, line in enumerate(top_four):
                next = top_four[(idx+1) % len(top_four)]
                l1_p1, l1_p2, line_idx = line[0], line[1], line[2]
                l2_p1, l2_p2, next_idx = next[0], next[1], next[2]

                #print("From", l1_p1, "to", l1_p2)
                #print("From", l2_p1, "to", l2_p2)
                #print()

                # cv2.circle(img, l1_p1, 9, (0,0,255), 5)
                # cv2.circle(img, l1_p2, 9, (0,255,0), 5)

                l1_p1x, l1_p2x = l1_p1[0], l1_p2[0]
                l2_p1x, l2_p2x = l2_p1[0], l2_p2[0]

                l1_p1y, l1_p2y = l1_p1[1], l1_p2[1]
                l2_p1y, l2_p2y = l2_p1[1], l2_p2[1]

                def intersection(x1, y1, x2, y2, x3, y3, x4, y4):
                    Px_upper = np.array([x1, y1, x1, 1, x2, y2, x2, 1, x3, y3, x3, 1, x4, y4, x4, 1]).reshape((4,4))
                    lower = np.array([x1, 1, y1, 1, x2, 1, y2, 1, x3, 1, y3, 1, x4, 1, y4, 1]).reshape((4,4))

                    Py_upper = Px_upper.copy()
                    Py_upper[:,2] = Py_upper[:,1].copy()

                    _det = np.linalg.det
                    def det(mat):
                        return _det(mat[:2, :2]) * _det(mat[2:, 2:]) - _det(mat[2:, :2]) * _det(mat[:2, 2:])

                    return (int(round(det(Px_upper) / det(lower), 0)), int(round(det(Py_upper) / det(lower), 0)))


                point = intersection(l1_p1x, l1_p1y, l1_p2x, l1_p2y, l2_p1x, l2_p1y, l2_p2x, l2_p2y)
                points.append(point)

            # print(points)

            lines = []
            for idx, pt1 in enumerate(points):
                lines.append((pt1, points[(idx + 1) % len(points)]))

            # sort by line length
            lines.sort(key=lambda x: (x[0][0]-x[1][0])**2 + (x[0][1]-x[1][1])**2)

            # print("Lines:", lines)

            # shortest line is probably one of the short sides
            short_side = lines[0]
            # sides_in_order: First one of the short sides, then a long side, then the other short side, then the last long side
            sides_in_order = [short_side[0], short_side[1]]
            while len(sides_in_order) < 4:
                for line in lines:
                    if len(sides_in_order) >= 4:
                        break
                    if sides_in_order[-1] == line[0]:
                        sides_in_order.append(line[1])

            show_lines(image, sides_in_order)
            reversed = sides_in_order[::-1]
            return reversed[1:] + reversed[:1]

        return
コード例 #51
0
ファイル: blobs.py プロジェクト: djpetti/neato-software
def find_blobs(points):
  log.debug("Starting blob finder...")

  # How close points have to be to be in the same blob.
  blob_threshold = 300

  # Sort points by x coordinates.
  sort = sorted(points, key = itemgetter(0))
  # Add "used" flag to list.
  x_order = []
  for item in sort:
    x_order.append([item, False])

  # For each point, find all the ones that are close to it.
  blobs = []
  for index in range(0, len(x_order)):
    point = x_order[index][0]

    # Find a subset of the points that are possibly part of this blob.
    possible = []

    # First do it by x's.
    radius = 1
    none_lower = False
    none_higher = False
    while (not (none_lower and none_higher)):
      if index - radius < 0:
        none_lower = True
      if index + radius >= len(x_order):
        none_higher = True

      if not none_lower:
        lower = x_order[index - radius]
        value = lower[0]
        used = lower[1]

        if point[0] - value[0] < blob_threshold:
          if not used:
            possible.append(index - radius)
        else:
          none_lower = True

      if not none_higher:
        higher = x_order[index + radius]
        value = higher[0]
        used = higher[1]

        if value[0] - point[0] < blob_threshold:
          if not used:
            possible.append(index + radius)
        else:
          none_higher = True

      radius += 1

    # Now see if any of them work with the y value as well.
    to_delete = []
    for candidate_index in possible:
      candidate = x_order[candidate_index][0]
      if abs(point[1] - candidate[1]) > blob_threshold:
        # This point can't work.
        to_delete.append(candidate_index)
    for delete in to_delete:
      possible.remove(delete)

    # And now we have points that it is worth actually checking the distance on.
    blob = Blob.find_blob(point, blobs)

    for candidate_index in possible:
      candidate = x_order[candidate_index][0]

      if utilities.distance(point, candidate) < blob_threshold:
        # This is part of the blob.
        if blob:
          # Add candidate to our existing blob.
          blob.add_point(candidate)
        else:
          # Make a new blob.
          blobs.append(Blob([point, candidate]))

        # We'll get to each candidate later as the point we're checking, so we can
        # flag it as used.
        x_order[candidate_index][1] = True

    # We can also get rid of the original point, because we've already found
    # everything close to it.
    x_order[index][1] = True

  for blob in blobs:
    log.debug("Found blob: %s." % (blob))
  return blobs
コード例 #52
0
 def get_distance(self, lat, lon):
     return distance((self.lat, self.lon), (lat, lon))
コード例 #53
0
ファイル: test_utilities.py プロジェクト: joey10086/BORIS
 def test_1(self):
     utilities.distance((10, 10), (80, 120)) == 130.38404810405297
コード例 #54
0
ファイル: entity.py プロジェクト: z-van-baars/embark
 def within_range(self, my_coordinates, target_coordinates, weapon_range):
     if utilities.distance(my_coordinates[0], my_coordinates[1], target_coordinates[0], target_coordinates[1]) < weapon_range:
         return True
     else:
         return False
コード例 #55
0
ファイル: test_utilities.py プロジェクト: olivierfriard/BORIS
 def test_1(self):
     utilities.distance((10, 10), (80, 120)) == 130.38404810405297
コード例 #56
0
ファイル: pump.py プロジェクト: puttak/ChemSimPy
 def mouseover(self, x, y):
     return (utilities.distance(x - self.location.x, y - self.location.y) <= globe.PumpInitRadius)
コード例 #57
0
            gameGoalPos = goalPosition[:, trial, epoch].copy()

            trialArmAngles = armAngles[:, :, trial, epoch].copy()
            trialGoalAngles = goalAngles[:, :, trial, epoch].copy()
            trialGangliaAngles = gangliaAngles[:, :, trial, epoch].copy()

            if cerebellum == True:
                trialCerebAngles = cerebAngles[:, :, trial, epoch].copy()

            trialTraj = trajectories[:, :, trial, epoch].copy()

            if trialTraj[0, :].any() != 0:
                trimmedTraj = utils.trimTraj(trialTraj)

                minDistance = utils.distance(
                    trimmedTraj[:, 0], trimmedTraj[:,
                                                   len(trimmedTraj[0, :]) - 1])
                trajLen = utils.trajLen(trimmedTraj)

                trialTangVel = np.zeros(len(trimmedTraj[0, :]))

                for step in xrange(len(trimmedTraj[0, :])):

                    if step > 0:
                        trialTangVel[step] = utils.distance(
                            trimmedTraj[:, step],
                            trimmedTraj[:, step - 1]) / arm.dt

                trialTangJerk = np.trim_zeros(jerk[:, trial, epoch], 'b')

                trialdXdY = np.zeros([2, len(trimmedTraj[0, :])])
コード例 #58
0
    def mousemove(self, event):
        if (self.sim.simulating == False):
                #if (sim.nmpccontrollers == null) { sim.nmpccontrollers = new List<nmpc>(); } //THIS LINE SHOULD AT SOME POINT BE DELETED WHEN THE MODEL FILE HAS 
                #//BEEN RECREATED WITH THE LATEST VERSION OF THIS CLASS.
            pointerx = self.canvas.canvasx(event.x) #4 local vars here
            pointery = self.canvas.canvasy(event.y)
            xonplant = (pointerx - globe.OriginX) / globe.GScale 
            yonplant = (pointery - globe.OriginY) / globe.GScale
            if self.radiobuttonValue.get() == pfdunitops['Edit']:
                for i in range(len(self.sim.unitops)):
                    if (self.sim.unitops[i].mouseover(xonplant, yonplant)):
                        self.sim.unitops[i].highlighted = True
                        #if (e.Button == System.Windows.Forms.MouseButtons.Left)
                        #{
                         #   sim.unitops[i].location.x = (pointerx - global.OriginX) / global.GScale;
                        #    sim.unitops[i].location.y = (pointery - global.OriginY) / global.GScale;
                        #}
                    else: self.sim.unitops[i].highlighted = False
                for i in range(len(self.sim.streams)):
                    if (self.sim.streams[i].mouseover((pointerx - globe.OriginX) / globe.GScale, \
                            (pointery - globe.OriginY) / globe.GScale)):
                        self.sim.streams[i].highlighted = True
                        #if (e.Button == System.Windows.Forms.MouseButtons.Left)
                        #{
                        #    point onplant = new point(xonplant,yonplant);
                        #    int pointtomove;
                        #    if (utilities.distance(sim.streams[i].points[0], onplant) < utilities.distance(sim.streams[i].points[1], onplant))
                        #    {
                        #        pointtomove = 0;
                        #    }
                        #    else
                        #    {
                        #        pointtomove = 1;
                        #    }
                        #    sim.streams[i].updatepoint(pointtomove,xonplant,yonplant);
                        #}
                    else: self.sim.streams[i].highlighted = False
                for i in range(len(self.sim.nmpccontrollers)):
                    if (self.sim.nmpccontrollers[i].mouseover(xonplant, yonplant)):
                        self.sim.nmpccontrollers[i].highlighted = True
                        #if (e.Button == System.Windows.Forms.MouseButtons.Left)
                        #{
                        #    sim.nmpccontrollers[i].location.x = (pointerx - global.OriginX) / global.GScale;
                        #    sim.nmpccontrollers[i].location.y = (pointery - global.OriginY) / global.GScale;
                        #}
                    else:
                        self.sim.nmpccontrollers[i].highlighted = False
                for i in range(len(self.sim.pidcontrollers)):
                    if (self.sim.pidcontrollers[i].mouseover(xonplant, yonplant)):
                        self.sim.pidcontrollers[i].highlighted = True
                        #if (e.Button == System.Windows.Forms.MouseButtons.Left)
                        #{
                        #    sim.nmpccontrollers[i].location.x = (pointerx - global.OriginX) / global.GScale;
                        #    sim.nmpccontrollers[i].location.y = (pointery - global.OriginY) / global.GScale;
                        #}
                    else:
                        self.sim.pidcontrollers[i].highlighted = False

            elif self.radiobuttonValue.get() == pfdunitops['Stream']:  # //Stream button
                for i in range(len(self.sim.unitops)):
                    for j in range(self.sim.unitops[i].nin):
                        if (utilities.distance(((pointery - globe.OriginY) / globe.GScale - self.sim.unitops[i].inpoint[j].y), \
                                ((pointerx - globe.OriginX) / globe.GScale - self.sim.unitops[i].inpoint[j].x)) <= \
                                globe.MinDistanceFromPoint):
                            self.sim.unitops[i].inpoint[j].highlighted = True
                        else:
                            self.sim.unitops[i].inpoint[j].highlighted = False
                    for j in range(self.sim.unitops[i].nout):
                        if (utilities.distance(((pointery - globe.OriginY) / globe.GScale - self.sim.unitops[i].outpoint[j].y), \
                                ((pointerx - globe.OriginX) / globe.GScale - self.sim.unitops[i].outpoint[j].x)) <= \
                                globe.MinDistanceFromPoint):
                            self.sim.unitops[i].outpoint[j].highlighted = True
                        else:
                            self.sim.unitops[i].outpoint[j].highlighted = False
                if (self.dmode == globe.drawingmode.Streams):
                    self.sim.streams[-1].updatepoint(1, xonplant, yonplant)

        self.sim.drawnetwork(self.canvas)