Esempio n. 1
0
    def test_a_distance(self):
        a = Distance(self.earth, self.office)

        for i in range(len(self.result)):
            distance = a.get_km(self.testLat[i], self.testLon[i])
            self.assertEqual(distance, self.result[i])
        print('DISTANCE TESTS PASSED')
Esempio n. 2
0
File: node.py Progetto: val461/lbry
 def __init__(self, node, outer_d, shortlist, key, find_value, rpc):
     self.node = node
     self.outer_d = outer_d
     self.shortlist = shortlist
     self.key = key
     self.find_value = find_value
     self.rpc = rpc
     # all distance operations in this class only care about the distance
     # to self.key, so this makes it easier to calculate those
     self.distance = Distance(key)
     # List of active queries; len() indicates number of active probes
     #
     # n.b: using lists for these variables, because Python doesn't
     #   allow binding a new value to a name in an enclosing
     #   (non-global) scope
     self.active_probes = []
     # List of contact IDs that have already been queried
     self.already_contacted = []
     # Probes that were active during the previous iteration
     # A list of found and known-to-be-active remote nodes
     self.active_contacts = []
     # This should only contain one entry; the next scheduled iteration call
     self.pending_iteration_calls = []
     self.prev_closest_node = [None]
     self.find_value_result = {}
     self.slow_node_count = [0]
Esempio n. 3
0
 def __init__(self, node, shortlist, key, rpc, exclude=None):
     self.exclude = set(exclude or [])
     self.node = node
     self.finished_deferred = defer.Deferred()
     # all distance operations in this class only care about the distance
     # to self.key, so this makes it easier to calculate those
     self.distance = Distance(key)
     # The closest known and active node yet found
     self.closest_node = None if not shortlist else shortlist[0]
     self.prev_closest_node = None
     # Shortlist of contact objects (the k closest known contacts to the key from the routing table)
     self.shortlist = shortlist
     # The search key
     self.key = str(key)
     # The rpc method name (findValue or findNode)
     self.rpc = rpc
     # List of active queries; len() indicates number of active probes
     self.active_probes = []
     # List of contact (address, port) tuples that have already been queried, includes contacts that didn't reply
     self.already_contacted = []
     # A list of found and known-to-be-active remote nodes (Contact objects)
     self.active_contacts = []
     # Ensure only one searchIteration call is running at a time
     self._search_iteration_semaphore = defer.DeferredSemaphore(1)
     self._iteration_count = 0
     self.find_value_result = {}
     self.pending_iteration_calls = []
Esempio n. 4
0
    def get_crime_count(self, area_index):
        dist = Dist()
        output = []

        for i in range(self.occurences - 1):
            lat1, lon1 = self.areas[area_index][0], self.areas[area_index][1]
            lat2, lon2 = self.crimeData["lat"][i +
                                               1], self.crimeData["long"][i +
                                                                          1]
            d = dist.calculate_dist_in_miles(lat1, lon1, lat2, lon2)
            if d <= self.MAX_DIST:
                output.append(self.crimeData["type"][i])

        # unique_elements, counts_elements = np.unique(np.array(output), return_counts=True)
        output_dict = {}
        # for i in range(unique_elements):
        # 	output_dict[unique_elements[i]] = counts_elements[i]

        df = pd.DataFrame(output, columns=['type'])
        unique_elements = df['type'].value_counts().keys().tolist()
        counts_elements = df['type'].value_counts().tolist()
        for i in range(len(unique_elements)):
            output_dict[unique_elements[i]] = counts_elements[i]

        return output_dict
Esempio n. 5
0
 def reset(self, episode):
     # prefix_state --> [split_point, index]
     # suffix_state --> [index + 1, len - 1]
     # return observation
     self.split_point = 0
     self.DIS = Distance(len(self.cand_train_data[episode]), len(self.query_train_data[episode]))
     self.DIS_R = Distance(len(self.cand_train_data[episode]), len(self.query_train_data[episode]))
     self.length = len(self.cand_train_data[episode])
     
     self.presim = self.DIS.FRECHET(self.cand_train_data[episode][self.split_point:1], self.query_train_data[episode])
     self.sufsim = self.DIS_R.FRECHET(self.cand_train_data[episode][1:][::-1],self.query_train_data[episode][::-1])
     whole = self.DIS_R.FRECHET(self.cand_train_data[episode][::-1],self.query_train_data[episode][::-1]) #self.DIS.FRECHET(self.cand_train_data[episode], self.query_train_data[episode])
     observation = np.array([whole, self.presim, self.sufsim]).reshape(1,-1)
     
     self.subsim = min(whole, self.presim, self.sufsim)
     #print('episode', episode, whole, self.presim, self.sufsim)
     
     if self.subsim == whole:
         self.subtraj = [0, self.length - 1]
         
     if self.subsim == self.presim:
         self.subtraj = [0, 0]
     
     if self.subsim == self.sufsim:
         self.subtraj = [1, self.length - 1]
     
     return observation, self.length
Esempio n. 6
0
 def autopilot_process(self, q_state):
     while True:
         distance = Distance()
         cm = distance.detect()
         self.display_text('Distance:')
         self.display_text(cm)
         print int(cm)
         if int(cm) <= 30:
             self.display_text('Obstacle!')
             self.stop_motors()
             time.sleep(1)
             self.run_down_start()
             time.sleep(0.3)
             self.run_down_stop()
             time.sleep(0.3)
             self.run_right_start()
             time.sleep(0.3)
             self.run_right_stop()
             print 'end obstacle'
         else:
             self.display_text('run!')
             self.run_up_start()
             
         if not q_state.empty():
             exit = q_state.get()
             if exit == 'autopilot_stop':
                 print 'autopilot stop...'
                 break
             if exit == 'exit':
                 print 'stoping autopilot...'
                 break
Esempio n. 7
0
    def is_in_way(self, plane, start_loc=None, heading=None):

        # FIXME currently only testing linear part

        if not start_loc:
            
            start_loc = plane.loc

        if not heading:
            
            heading = plane.heading

        turn_dist = Distance.get_turn_dist(plane)
        turn_angle = Distance.get_turn_angle(plane)

        wp_dist = start_loc.get_distance(plane.next_wp, angle=heading) \
            .subtract(turn_dist).get_transform(turn_angle)

        obs_dist = start_loc.get_distance(self.loc, angle=heading) \
            .subtract(turn_dist).get_transform(turn_angle)

        if obs_dist < 0 or obs_dist > wp_dist.y:

            return False

        pass_alt = plane.loc + turn_dist.z + obs_dist.y / float(wp_dist.y) \
            * wp_dist.z
        radius = self.get_avoid_radius(pass_alt)

        return radius > obs_dist.x
Esempio n. 8
0
 def __init__(self, center=[], tag=""):
     self.samples = []  # 本群分类进来的样本点
     self.center = center  # 群心
     self.old_center = []  # 旧的群心
     self.distance = Distance()
     self.distance_method = Method.Eculidean
     self.tag = tag
Esempio n. 9
0
    def step(self, episode, action, index):
        if action == 0:  #non-split
            #state transfer
            self.presim = self.DIS.DTW(
                self.cand_train_data[episode][self.split_point:(index + 1)],
                self.query_train_data[episode])
            self.sufsim = self.DIS_R.DTW(
                self.cand_train_data[episode][(index + 1):][::-1],
                self.query_train_data[episode][::-1])
            if (index + 1) == self.length:
                self.sufsim = self.presim
            observation = np.array([self.subsim, self.presim,
                                    self.sufsim]).reshape(1, -1)

            last_subsim = self.subsim

            if self.presim < self.subsim:
                self.subsim = self.presim
                self.subtraj = [self.split_point, index]

            if self.sufsim < self.subsim:
                self.subsim = self.sufsim
                self.subtraj = [index + 1, self.length - 1]

            self.RW = last_subsim - self.subsim
            #print('action0', self.RW)
            return observation, self.RW

        if action == 1:  #split
            self.split_point = index
            self.DIS = Distance(
                len(self.cand_train_data[episode][self.split_point:]),
                len(self.query_train_data[episode]))
            #state transfer
            self.presim = self.DIS.DTW(
                self.cand_train_data[episode][self.split_point:(index + 1)],
                self.query_train_data[episode])
            self.sufsim = self.DIS_R.DTW(
                self.cand_train_data[episode][(index + 1):][::-1],
                self.query_train_data[episode][::-1])
            if (index + 1) == self.length:
                self.sufsim = self.presim
            observation = np.array([self.subsim, self.presim,
                                    self.sufsim]).reshape(1, -1)

            last_subsim = self.subsim

            if self.presim < self.subsim:
                self.subsim = self.presim
                self.subtraj = [self.split_point, index]

            if self.sufsim < self.subsim:
                self.subsim = self.sufsim
                self.subtraj = [index + 1, self.length - 1]

            self.RW = last_subsim - self.subsim
            #print('action1', self.RW)
            return observation, self.RW
Esempio n. 10
0
class Group:
    def __init__(self, center=[], tag=""):
        self.samples = []  # 本群分类进来的样本点
        self.center = center  # 群心
        self.old_center = []  # 旧的群心
        self.distance = Distance()
        self.distance_method = Method.Eculidean
        self.tag = tag

    def add_sample(self, sample):
        if not sample:
            return
        self.samples.append(sample)

    # 更新群心
    def update_center(self):
        # e.g.
        # samples = [x1, x2, x3]
        # x1 = [2, 2, 3, 3]
        # x2 = [4, 5, 6, 7]
        # x3 = [7, 8, 9, 1]
        #
        # summed_vectors = [(2+4+7), (2+5+8), (3+6+9), (3+7+1)]
        #                = [13, 15, 18, 11]
        #
        # new_center     = [13, 15, 18, 11] / len(samples)
        #                = [13, 15, 18, 11] / 3
        #                = [4.33333333, 5.0, 6.0, 3.66666667]

        # 把所有所属的样本点做矩阵相加 (相同维度位置彼此相加), summed_vectors 会是 numpy.ndarray 型态
        summedd_vectors = np.sum(self.samples, axis=0)
        # 再把加总起来的矩阵值除以所有样本数,取得平均后的新群心的特征属性, new_center 也是 numpy.ndarray型态
        new_center = summedd_vectors / float(len(self.samples))
        # 更新新旧 Center 的记录 (要把 new_center 转回去 python 的List)
        self.old_center = self.center
        self.center = new_center.tolist()

    # 清空记录的样本点
    def clear(self):
        # Romoving reference in this example is enough.
        del self.samples[:]

    # 计算本群里所有样本点对群心的距离总和,即为本群的 SSE 值
    def sse(self):
        if not self.samples:
            return 0.0
        sum = 0.0
        for point in self.samples:
            sum += self.distance.calculate(point, self.center,
                                           self.distance_method)
        return sum

    # 新旧群心的变化距离
    def diff_distance(self):
        if not self.old_center:
            return 0.0
        return self.distance.calculate(self.center, self.old_center,
                                       self.distance_method)
Esempio n. 11
0
    def test_args_valueerror(self):
        with self.assertRaises(ValueError):
            Distance("cosine")

        inputs = [[1, "2", 3], [True, [], 3.], [9.3, 1., set()], {"e": "1"}]

        for inp in inputs:
            with self.subTest(text=inp), self.assertRaises(ValueError):
                Distance("manhattan", (inp))
Esempio n. 12
0
 def __init__(self):
     self.samples = []  # 训练样本集: [features array of each sample]
     self.distance_method = Method.Eculidean  # 要用什么距离算法
     self.distance = Distance()  # 距离算法
     self.groups = []  # 每一个分类好的群聚 [Group]
     self.convergence = 0.001  # 收敛误差
     self.max_iteration = 100  # 最大迭代次数
     self.m = 2  # 计算归属度的参数 (m 是模糊器, 用来决定每一个群聚的模糊程度,m 太小则算法效果会接近硬聚类,太大则效果差)
     self.iteration_callback = None
     self.completion_callback = None
Esempio n. 13
0
 def __init__(self, center=[], tag=""):
     self.samples = []  # 本群分类进来的样本点 (跟 all_memberships 没有索引位置上的对应关系)
     self.all_memberships = []  # 所有样本点对本群心的归属度
     # FCM 是整体样本在做估计和运算(含更新群心、SSE),不像 K-Means 是个体群在做运算和更新群心
     self.center = center  # 群心
     self.old_center = []  # 旧的群心
     self.distance = Distance()
     self.distance_method = Method.Eculidean
     self.tag = tag
     self.sse = 0.0  # 本群 SSE (由外部提供, 這里做記錄)
Esempio n. 14
0
def __calculateDistance__(src: str, dst: str, distanceStr: str,
                          distanceUpto: int) -> int:
    if distanceUpto == -1:
        return distanceUpto, Distance(src, dst, distanceUpto)
    else:
        distance = -1
        if distanceStr.isnumeric():
            distance = int(distanceStr, base=10)
            return distance, Distance(src, dst, distance - distanceUpto)
        else:
            return distance, Distance(src, dst, distance)
Esempio n. 15
0
 def __init__(self):
     self.samples             = []
     self.distance_method     = Method.Eculidean
     self.distance            = Distance()
     self.center_choice       = Choice.Shuffing
     self.center_maker        = Maker()
     self.groups              = []
     self.convergence         = 0.001
     self.max_iteration       = 100
     self.iteration_callback  = None
     self.completion_callback = None
Esempio n. 16
0
    def test_concatenation_error(self):

        euc_dist = Distance("euclidean", 1, 2)
        cos_dist = Distance("cosine", 3, 4)
        with self.assertRaises(TypeError):
            euc_dist.concatenate(cos_dist)
        with self.assertRaises(TypeError):
            cos_dist.concatenate(euc_dist)
Esempio n. 17
0
 def search_free_road(self, last_distance=None):
     text = 'Looking for free road...'
     print text
     distance = Distance()
     cm = distance.detect()
     print int(cm)
     if last_distance is not None:
         if self.detect_no_movement(int(cm), last_distance):
             self.skip_obstacle()
     if int(cm) <= self.OBSTACLE_DISTANCE:
         self.skip_obstacle()
         self.search_free_road(last_distance)
     else:
         print "Run!"
         PyMove().run_up_start()
Esempio n. 18
0
 def output(self, index, episode, label='E'):
     #print('check', self.subsim, self.subtraj)
     if label == 'T':
         #print('check', self.subsim, self.subtraj, self.subsim_real)
         return [self.subsim_real, self.subtraj]
     if label == 'E':
         self.DIS = Distance(
             len(self.cand_train_data[episode]
                 [self.subtraj[0]:self.subtraj[1] + 1]),
             len(self.query_train_data[episode]))
         self.subsim_real = self.DIS.FRECHET(
             self.cand_train_data[episode][self.subtraj[0]:self.subtraj[1] +
                                           1],
             self.query_train_data[episode])
         return [self.subsim_real, self.subtraj]
class Route:
  trajeto = []
  total = 0
  def __init__(self,trajeto):
    self.distance = Distance()
    self.trajeto = trajeto

  def __eq__(self,obj):
    return self.total == obj.total
  
  def __lt__(self,obj):
    return self.total < obj.total
  
  def __gt__(self,obj):
    return self.total > obj.total
  
  def __ge__(self,obj):
    return self.total >= obj.total
  
  def __le__(self,obj):
    return self.total <= obj.total

  def totalDistance(self):
    self.total = self.distance.totalDistance()
  
  def numTrajetos(self):
    return len(self.trajeto)

  def bestRoute(self,obj):
    return self.total <= obj.total32
Esempio n. 20
0
def ExactS(traj_c, traj_q):
    subsim = 999999
    subtraj = [0, len(traj_c) - 1]
    subset = {}
    N = len(traj_c)
    for i in range(N):
        DIS = Distance(len(traj_c[i:]), len(traj_q))
        for j in range(i, N):
            temp = DIS.DTW(traj_c[i:j + 1], traj_q)
            #temp = similaritymeasures.dtw(traj_c[i:j+1], traj_q)[0]
            #print('sub-range:', [i, j], temp)
            subset[(i, j)] = temp
            if temp < subsim:
                subsim = temp
                subtraj = [i, j]
    return subsim, subtraj, subset
Esempio n. 21
0
    def findCloseNodes(self, key, count=None, sender_node_id=None):
        """ Finds a number of known nodes closest to the node/value with the
        specified key.

        @param key: the n-bit key (i.e. the node or value ID) to search for
        @type key: str
        @param count: the amount of contacts to return, default of k (8)
        @type count: int
        @param sender_node_id: Used during RPC, this is be the sender's Node ID
                               Whatever ID is passed in the paramater will get
                               excluded from the list of returned contacts.
        @type sender_node_id: str

        @return: A list of node contacts (C{kademlia.contact.Contact instances})
                 closest to the specified key.
                 This method will return C{k} (or C{count}, if specified)
                 contacts if at all possible; it will only return fewer if the
                 node is returning all of the contacts that it knows of.
        @rtype: list
        """
        exclude = [self._parentNodeID]
        if sender_node_id:
            exclude.append(sender_node_id)
        if key in exclude:
            exclude.remove(key)
        count = count or constants.k
        distance = Distance(key)
        contacts = self.get_contacts()
        contacts = [c for c in contacts if c.id not in exclude]
        contacts.sort(key=lambda c: distance(c.id))
        return contacts[:min(count, len(contacts))]
Esempio n. 22
0
    def knn_visual(k, locationid, model, database, this_vector=None):
        nearest = {}
        if not this_vector:
            this_vector = Vectorizer.visual_vector(locationid, database, model)

        others = database.get_location_ids()
        others.remove(locationid)
        # Get distance to each other vecctor and add to nearest if it is less than the
        #   distance to an existing vector.
        for other in others:
            other_vector = Vectorizer.visual_vector(other, database, model)
            distance = Distance.l_p_distance(3,
                                             this_vector,
                                             other_vector,
                                             positional=True)

            if len(nearest) < k:
                largest_key, largest_best = None, inf
            else:
                largest_key, largest_best = max(nearest.items(),
                                                key=itemgetter(1))

            if distance < largest_best:
                if largest_key:
                    nearest.pop(largest_key)
                nearest[other] = distance

        return nearest
Esempio n. 23
0
    def knn_visual_all(k, locationid, models, database, this_vector=None):
        nearest = {}
        others = database.get_location_ids()
        others.remove(locationid)

        # Calculate this_vector
        if not this_vector:
            this_vector = Vectorizer.visual_vector_multimodel(
                locationid, database, models)

        # Make a vector where each item is an average for that model
        for other in others:
            other_vector = Vectorizer.visual_vector_multimodel(
                locationid, database, models)
            # get distance between vectors
            distance = Distance.l_p_distance(3, this_vector, other_vector)

            if len(nearest) < k:
                largest_key, largest_best = None, inf
            else:
                largest_key, largest_best = max(nearest.items(),
                                                key=itemgetter(1))

            if distance < largest_best:
                if largest_key:
                    nearest.pop(largest_key)
                nearest[other] = distance

        return nearest
Esempio n. 24
0
File: kmeans.py Progetto: gszxwd/ML
 def clustering(self, K, N=100):
     classes = {}
     # generate K initial points
     pts = []
     for i in range(K):
         classes[i] = []
         pt = []
         for j in range(len(self.data[0][0])):
             pt.append(random.random())    # normallized data
         pts.append(pt)
     #
     for n in range(N):
         for i in range(K):
             classes[i] = []
         for i in range(len(self.data)):
             temp = 9999
             flag = 0
             for j in range(K):
                 dist = Distance.euclideanDist(self.data[i][0], pts[j])
                 if dist < temp:
                     temp = dist
                     flag = j
             classes[flag].append(i)
         #
         for i in range(K):
             means = [0]*len(self.data[0][0])
             for j in range(len(classes[i])):
                 for k in range(len(self.data[0][0])):
                     means[k] = means[k]+self.data[j][0][k]
                 for k in range(len(self.data[0][0])):
                     means[k] = means[k]/len(self.data[0][0])
             pts[i] = means
     return classes
Esempio n. 25
0
def distance(location1, location2):
    """
    Using the Great Circle distance by using the Harversine formula.

        >>> import geocoder
        >>> d = geocoder.distance('Ottawa', 'Toronto')
        >>> d.km
        351.902264779
        >>> d.miles
        218.672067333
        ...

    Different ways to use the Distance calculator, you can input the locations 
    by using a tuple (lat, lng) or a dictionary with lat/lng keys.

        >>> import geocoder
        >>> ottawa = (45.4215296, -75.69719309999999)
        >>> toronto = {'lat':43.653226, 'lng':-79.3831843}
        >>> d = geocoder.distance(ottawa, toronto)
        >>> d.meters
        351902
        ...

    Wiki Docs
    ---------
    http://en.wikipedia.org/wiki/Haversine_formula
    """
    return Distance(location1, location2)
Esempio n. 26
0
    def test_distance_with_valid(self):
        obj = Distance('euc')

        expected = 'euclidean'
        actual = obj.func.__name__

        self.assertEqual(expected, actual)
Esempio n. 27
0
def biomass_worker(driver, biomass, out_name, distance='hav'):
    """Worker function for parallel execution.

    Computes the biomass emissions (AGB and BGB) by using ``biomass_emissions`` function.
    Further, the pixel resolution in square meter is computed and delegated to ``biomass_emissions``.
    Result is stored on disk as raster image by using the metadata profile of the first argument.

    Args:
        driver (str or Path): Path to Proximate Deforestation Driver tile.
        biomass (str or Path): Path to Above-ground Woody Biomass Density stratum.
        out_name (str or Path): Path plus name of out file.
        distance (str, optional): Default is Haversine equation.
    """
    with open(driver, 'r') as h1, open(biomass, 'r') as h2:
        driver_data = h1.read(1)
        biomass_data = h2.read(1)

        profile = h1.profile
        transform = h1.transform

    haversine = Distance(distance)
    x = haversine((transform.xoff, transform.yoff),
                  (transform.xoff + transform.a, transform.yoff))
    y = haversine((transform.xoff, transform.yoff),
                  (transform.xoff, transform.yoff + transform.e))
    area = round(x * y)

    emissions = biomass_emissions(driver_data, biomass_data, area=area)

    # write updates the dtype corresponding to the array dtype
    write(emissions, out_name, **profile)
Esempio n. 28
0
 def get_distances(self, vectors, image_dict):
     results = {}
     result = []
     for i in vectors:
         print("Working on hash" + str(i))
         dist = {}
         projection = []
         for image in image_dict:
             a = np.array(vectors[i], dtype=np.float)
             b = a[1]
             a = a[0]
             p = np.array(image_dict[image], dtype=np.float)
             ap = p - a
             ab = b - a
             # distance = np.array(np.around((ab * ap) / Distance.E2_distance(a, b), decimals=4))
             projection.append(
                 np.array(
                     np.around((a + np.dot(ab, ap) / np.dot(ab, ab) * ab),
                               decimals=3)))
             # projection.append(np.array(np.around()))
         min_proj = np.amin(projection, axis=0)
         image_keys = list(image_dict.keys())
         j = 0
         # print(min_proj)
         for x in projection:
             distance = Distance.E2_distance(min_proj, x)
             ind = image_keys[j]
             dist[ind] = distance
             j = j + 1
         result.append(dist)
         results['h' + str(i)] = result
         result = []
     # print(results)
     return results
Esempio n. 29
0
    def test_distance_with_args(self):
        obj = Distance('euc')

        expected = (float, int)
        actual = obj((4, 5), (1, 1))

        self.assertTrue(isinstance(actual, expected))
Esempio n. 30
0
    def parse_population_generator(self) -> Population_Generator:
        """Parse the population generator object from the Population_Generator.json file.

        Returns:
            Population_Generator: The population generator object containing the population information.
        """
        self.json_name = 'Population_Generator'
        self.build_path()

        # load json file
        with open(self.path, 'r') as f:
            self.json_dict = json.load(f)

        # retrieve main attributes dictionaries
        population_size = self.json_dict['population_size']
        family_patterns = self.parse_family_patterns(
            self.json_dict['family_patterns'])
        community_types = self.parse_community_types(
            self.json_dict['community_types'])
        distance_function = Distance.map_str_to_function(
            self.json_dict['distance_function'])

        # build the object
        population_generator = Population_Generator(population_size,
                                                    family_patterns,
                                                    community_types,
                                                    distance_function)
        return population_generator
Esempio n. 31
0
def enter():
    game_framework.reset_time()
    global map, player, house, background, avalanche, coin, snows, map_on_coins, game_over, santa, game_clear, distance, stones
    map = Map()
    player = Player()
    house = House()
    background = Background()
    avalanche = Avalanche()
    coin = Coin()
    game_over = Game_over()
    santa = Santa()
    game_clear = Game_clear()
    distance = Distance()
    map_on_coins = [Map_on_Coin() for i in range(200)]
    snows = [Snow() for i in range(20)]
    stones = [Stone() for i in range(10)]

    Player.x = 300.0
    Player.y = 300.0
    Player.unreal_x = 300.0
    Player.unreal_y = 0
    Player.jump_before_y = 0
    Map.map_move_y_minor = 0
    Avalanche.game_over = 0
    Game_clear.game_clear = 0
    Santa.game_clear = 0
Esempio n. 32
0
class Group:
    def __init__(self, center=[], tag=""):
        self.samples = []  # 本群分类进来的样本点 (跟 all_memberships 没有索引位置上的对应关系)
        self.all_memberships = []  # 所有样本点对本群心的归属度
        # FCM 是整体样本在做估计和运算(含更新群心、SSE),不像 K-Means 是个体群在做运算和更新群心
        self.center = center  # 群心
        self.old_center = []  # 旧的群心
        self.distance = Distance()
        self.distance_method = Method.Eculidean
        self.tag = tag
        self.sse = 0.0  # 本群 SSE (由外部提供, 這里做記錄)

    def add_sample(self, sample):
        if not sample:
            return
        self.samples.append(sample)

    def add_membership(self, membership=1.0):
        self.all_memberships.append(membership)

    # 要用全部的样本点(all_samples)来更新群心
    # all_samples 会对应 self.all_memberships的索引位置
    def update_center(self, all_samples=[], m=2):
        # 把所有的样本点先各自乘上自己对本群心的归属度 m 次方后,再做矩阵相加(相同维度位置彼此相加)。
        # membership_samples 和 summed_vectors 都会是 numpy.ndarray 型态
        length = len(all_samples[0])
        summed_vectors = np.zeros(length)  # 先建一个跟样本点特征长度等长的零值阵列
        for index, point in enumerate(all_samples):
            # 取出该样本点对本群的归属度
            membership = self.all_memberships[index]
            # 归属度 m 次方
            m_membership = membership**m
            membership_point = np.multiply(point, m_membership)
            # 加总
            summed_vectors = np.add(membership_point, summed_vectors)

        # 再把加总起来的 summed_vectors 矩阵值除以 "所有样本点对本群心的归属度 m 次方总和",
        # new_center 也是 numpy.ndarray 形态
        summed_membership = 0.0
        for membership in self.all_memberships:
            summed_membership += (membership**m)
        new_center = summed_vectors / summed_membership

        # 更新新旧 Center 的记录(要把 new_center 从 numpy 物件转回去 python 的 List)
        self.old_center = self.center
        self.center = new_center.tolist()

    # 清空记录的样本点
    def clear(self):
        del self.samples[:]
        del self.all_memberships[:]
        self.sse = 0.0

    # 新旧群心的变化距离
    def diff_distance(self):
        if not self.old_center:
            return 0.0
        return self.distance.calculate(self.center, self.old_center,
                                       self.distance_method)
Esempio n. 33
0
File: knn.py Progetto: gszxwd/ML
 def predict(self, sample, k):
     candidats = [{9999: 0}] * k
     ids = [0] * k
     for i in range(len(self.tdata)):
         dist = Distance.euclideanDist(sample, self.tdata[i][0])
         if dist < candidats[-1].keys()[0]:
             candidats.sort()
             candidats.pop()
             candidats.insert(0, {dist: i})
     # most is the winner
     counter = {}
     for c in candidats:
         counter[self.tdata[c.values()[0]][1]] = 0
     for c in candidats:
         counter[self.tdata[c.values()[0]][1]] = counter[self.tdata[c.values()[0]][1]] + 1
     print counter
Esempio n. 34
0
        openevent.wait(10)
        if openevent.is_set():
            closedevent.wait()
            # let em clear out

        light.turnon()
        eyes.turnoff()

        threading.Timer(5, lambda: scaring.clear()).start()

door = Door(args=(open_callback, close_callback, closedevent), kwargs={'gpio_door': 11})

        
dist = Distance(args=(distance_callback, 190),
               kwargs={'gpio_trigger': 16,
                      'gpio_echo': 18})

def stopthreads():
    light.fullon()
    spk.stop()
    dist.stop()
    light.stop()
    eyes.stop()
    door.stop()

    eyes.join(1)
    door.join(1)
    spk.join(1)
    dist.join(1)
    light.join(1)