Example #1
0
def get_radius(mesh, nodes, edge):
    """
    Compute the radius of the mesh at a given edge.

    Given the mesh and a set of nodes, edges obtained
    e.g. via get_graph(mesh, ...), for a given edge
    u, v we approximate the radius as follows:
    1. c = (u+v)/2
    2. n = v-u
    2. cut mesh throuch c with normal n
    3. compute length of intersection (only one CC)
    4. infer radius

    This is a rought approximation but seems the best we can
    do in this situation. Also, a rought approximation will
    be more than enough for our needs.

    """
    u, v = nodes[edge]
    section = mesh.section(v - u, (u + v) / 2)

    connected_comps = list(nx.connected_components(section.vertex_graph))
    cut_centers = [
        section.vertices[list(H)].mean(axis=0) for H in connected_comps
    ]
    mycut_idx = np.argmin(norm(cut_centers - v, axis=1))

    lengths = [
        norm(section.vertices[line.end_points[0]] -
             section.vertices[line.end_points[1]]) for line in section.entities
        if (line.end_points[0] in connected_comps[mycut_idx])
    ]

    radius = np.sum(lengths) / (2 * np.math.pi)
    return radius
Example #2
0
    def Executar(self):
        
        self.Inicializar()
        
        global media_anterior
        valores = []
        suporte = []
        solucao_geral = []
        
        
        for i in range(self.execucoes):
            
            print("\n----------------------------  Execução: ", i , "------------------------------------------------------")
            

            ambiente = self.Pendulum()
            
            self.Relembrar_Ambiente(self.ambiente_atual)
            
            self.Detectar_mudanca(ambiente, media_anterior)
                          
            if((self.congelar == False)):     
                self.Swarm_Finder(ambiente)
                print("-> Finder: ", self.finder.gbest.fitness)
                
                self.Exclusion(self.finder)
                
                suporte.append(self.finder.gbest.fitness)
                global current_particle 
                current_particle.append(self.finder.gbest)
            
                #finderConvergenceChecking
                if(i >= 4):
                    if(((suporte[i-3] - self.finder.gbest.fitness) < r_conv) or (sp.norm(current_particle[i-3].dimensao-self.finder.gbest.dimensao) < (r_conv/5))):
                        self.tracker.particulas = copy.deepcopy(self.finder.particulas)
                        self.tracker.gbest = copy.deepcopy(self.finder.gbest)
                        

            self.Swarm_Tracker(ambiente)
            print("-> Tracker: ", self.tracker.gbest.fitness)
                            
            print("-> Melhor solução: ", self.tracker.gbest.fitness)     
            solucao_geral.append(self.tracker.gbest.fitness)
            
            
            valores.append(self.finder.gbest.fitness)
                    
            #Swarm_freezing
            if(i >= 4):
                if(((valores[i-2] - self.finder.gbest.fitness) < r_conv) or (sp.norm(current_particle[i-2].dimensao-self.finder.gbest.dimensao) < (r_conv/5))):
                    self.congelar = True
          
        print("\nMedia:" , np.mean(solucao_geral))
        print("Desvio:" , np.std(solucao_geral))  
Example #3
0
def join_graphs(nodes1, edges1, nodes2, edges2, vertex):
    """
    Join two graphs using an auxiliary vertex.

    At the moment simply look for the closest node
    of each tree to the aux vertex, and link.
    """
    closest_n1 = np.argmin(norm(nodes1 - vertex, axis=1))
    closest_n2 = np.argmin(norm(nodes2 - vertex, axis=1))
    nodes = np.concatenate([nodes1, nodes2, [vertex]])
    edges = np.concatenate([
        edges1, edges2 + len(nodes1), [[len(nodes) - 1, closest_n1]],
        [[len(nodes) - 1, len(nodes1) + closest_n2]]
    ])
    return nodes, edges
Example #4
0
    def _color_point(self,
                     colors,
                     filled,
                     clustering_truth,
                     cluster_idx,
                     max_dist,
                     point,
                     offset=np.array([0, 0, 0])):
        """
        Internal function used to color voxels in the draw_pixel function and to color the noise voxels

        :param colors: The np.array containing the HTML color strings for every voxel
        :param filled: The np.array containing the presence information for every voxel (if a voxel is drawn or not)
        :param clustering_truth: The np.array containing the ground truth labels for the points
        :param cluster_idx: The index of the current cluster
        :param point: The coordinates of a voxel for the use in the colors/filled np.array
        :param color: The color the point will have in HTML format with alpha value --> #RRGGBBAA or #RRGGBB
        :param offset: The offset for the point. This is currently only used for adding noise
        :return: the altered colors, filled np.array
        """
        offset_point = point + offset
        if max(offset_point) < (len(colors) - 1) and min(offset_point) > 0 and \
                colors[offset_point[0]][offset_point[1]][offset_point[2]] != self._point_color:
            color = self._calculate_point_color(norm(point - offset_point),
                                                max_dist,
                                                variant="curve")
            colors[offset_point[0]][offset_point[1]][offset_point[2]] = \
                "#" + 3 * color + "50" if self._alpha_voxels else "#" + 3 * color
            filled[offset_point[0]][offset_point[1]][offset_point[2]] = 1
            clustering_truth[offset_point[0], offset_point[1],
                             offset_point[2]] = cluster_idx
        return colors, filled, clustering_truth
Example #5
0
    def apply_textures(self, vectors, fnames):
        ids = self.segment_ids()
        count = ids.shape[0]
        done = 0
        picked_textures = np.ones(vectors.shape[0])
        for segment_id in ids:
            print float(done) / count * 100
            done += 1
            mask = self.segment_mask(segment_id)
            vector = feature_vector(self.raw_img[np.nonzero(mask)])

            # compute cosine similarity
            dots = np.einsum('ij,ij->i', vectors, np.resize(vector, vectors.shape))
            v_norm = np.resize(distance.norm(vector), vectors.shape[0])
            m_norm = norms(vectors)
            scales = v_norm * m_norm
            cosine_similarities = dots / scales

            similarities = cosine_similarities / picked_textures

            idx = np.argmax(similarities)
            picked_textures[idx] += (picked_textures[idx] * 10)
            #picked_textures[idx] += 1

            fname = fnames[idx]
            texture = self.load_image(fname, self.raw_img.shape)
            self.raw_img[mask] = texture[mask]
Example #6
0
    def functionToFindRootOf(X):
        # define airplane
        definingParameters = setDefiningParameters(drivingParameters, X)
        initialAirplane = defineSpecificAirplane(definingParameters)
        initialAirplane.passengers = ceil(designMission.passengerFactor *
                                          initialAirplane.maxPassengers)
        # simulate airplane
        simulationResult = simulateAirplane(initialAirplane,
                                            designMission,
                                            silent=silent)
        initialAirplane = simulationResult["initial airplane"]
        simulation = simulationResult["simulation"]
        finalAirplane = simulationResult["final airplane"]
        succeeded = simulationResult["succeeded"]

        # calculate resultant point
        if succeeded:
            guessedGrossWeight = definingParameters["initial gross weight"]
            predictedGrossWeight = AirplaneWeight(initialAirplane)
            grossWeightDifference = abs(guessedGrossWeight -
                                        predictedGrossWeight)
            emptyFuelMass = finalAirplane.powerplant.emptyFuelMass
            finalFuelMass = finalAirplane.powerplant.fuelMass

            result = [
                convert(grossWeightDifference, "N", "lb"),
                convert(finalFuelMass * g - emptyFuelMass * g, "N", "lb")
            ]  # W0 guess = W0 predicted, Wf capacity is all used up by end of mission
        else:
            result = [1e10, 1e10]  # pseudo bound

        print(X, "->", result, "=>", norm(
            [0, 0], result)) if not silent else None  # show convergence

        return result
def rel_err(get, expect):
    a = euclidean(get, expect)
    b = norm(expect)
    if b == 0:
        return a
    else:
        return a / b
def rel_err(get, expect):
    a = euclidean(get, expect)
    b = norm(expect)
    if b == 0:
        return a
    else:
        return a/b
Example #9
0
    def functionToFindRootOf(X):
        # define airplane
        initialAirplane, referenceMissionChanged = setInitialConfiguration(
            baseConfiguration, referenceMission, X)
        # simulation
        simulationResult = simulateAirplane(initialAirplane,
                                            referenceMissionChanged,
                                            silent=silent)
        initialAirplane = simulationResult["initial airplane"]
        simulation = simulationResult["simulation"]
        finalAirplane = simulationResult["final airplane"]
        succeeded = simulationResult["succeeded"]

        # post-validation
        if succeeded:
            Wgs = [mg * g for mg in simulation["gas mass"]]
            range = simulation["position"][lastIndex(
                simulation["segment"], lambda s: s == "descent"
            )]  # the range not including the loiter segments
            # FIXME: range getting beginning of descent

            result = [
                Wgs[-1], convert(range - referenceRange, "m", "nmi")
            ]  # no gas left after whole mission & range flown = desired range

        else:
            result = [1e10, 1e10]  # pseudo bound

        print(X, "->", result, "=>", norm([0, 0], result))
        return result
Example #10
0
def Hellinger_distance(p, q, norm='l2'):
    """Hellinger distance of two discrete pdfs

    Parameters
    ---------
    p : array-like, the reference distribution
    q : array-like, the estimate of the reference

    Returns
    -------
    distance : array-like shape (n_samples,)
    """
    p, q = _check_metric_arrays((p, q))

    if norm == 'l1':
        hellinger = np.vectorize(
            (lambda p, q: norm(np.sqrt(p) - np.sqrt(q)) / _SQRT2),
            signature='(n),(n)->()')
    elif norm == 'l2':
        hellinger = np.vectorize(
            (lambda p, q: euclidean(np.sqrt(p), np.sqrt(q)) / _SQRT2),
            signature='(n),(n)->()')
    else:
        raise ValueError(
            'Norm must be specified to be l1 or l2, got {}'.format(norm))

    return hellinger(p, q)
Example #11
0
    def apply_textures(self, vectors, fnames):
        ids = self.segment_ids()
        count = ids.shape[0]
        done = 0
        picked_textures = np.ones(vectors.shape[0])
        for segment_id in ids:
            print float(done) / count * 100
            done += 1
            mask = self.segment_mask(segment_id)
            vector = feature_vector(self.raw_img[np.nonzero(mask)])

            # compute cosine similarity
            dots = np.einsum('ij,ij->i', vectors,
                             np.resize(vector, vectors.shape))
            v_norm = np.resize(distance.norm(vector), vectors.shape[0])
            m_norm = norms(vectors)
            scales = v_norm * m_norm
            cosine_similarities = dots / scales

            similarities = cosine_similarities / picked_textures

            idx = np.argmax(similarities)
            picked_textures[idx] += (picked_textures[idx] * 10)
            #picked_textures[idx] += 1

            fname = fnames[idx]
            texture = self.load_image(fname, self.raw_img.shape)
            self.raw_img[mask] = texture[mask]
Example #12
0
    def visit(self, node, x):
        if (node is None):
            return
        dis = x[node.sp] - self.data[node.data, node.sp]
        if (dis > 0):
            self.visit(node.right, x)
        else:
            self.visit(node.left, x)

        if (dis > -self.neighbors[0].key):  #dis是查询点到node分
            # 割数据的距离以及另一
            # 边所有数据的距离的一个下界,如果dis都没有资格进入knn
            # 那么node上的数据以及node分割的另一边区域的所有数据都无需查询
            return

        #如果node上的数据点能进knn,就进knn
        dis0 = -norm(self.data[node.data] - x)

        if (dis0 > self.neighbors[0].key):  #大家都是负数 大说明绝对值小,即更近,有资格进knn
            heapq.heappushpop(self.neighbors, Temp(dis0, node.data))

        #visit node的另一边区域
        if (dis > 0):
            self.visit(node.left, x)
        else:
            self.visit(node.right, x)
Example #13
0
def _get_edge_cylinder(node0, node1, radius=0.1):
    center = (node0 + node1) / 2
    normal = node1 - node0
    cyl = _get_cylinder(radius=radius,
                        normal=normal,
                        center=center,
                        height=norm(normal),
                        sections=6)
    return cyl
Example #14
0
 def Exclusion(self, swarm):
     r_excel = 0.5
     
     for i in swarm.particulas:
         if((sp.norm(i.dimensao-swarm.gbest.dimensao)) < r_excel):
            swarm = PSO(1000, 10, 1, 2, 2, 1000)
            swarm.Criar_Particula()
 
     return swarm
Example #15
0
 def Distancia_vetores(self, a, b):
     '''
     método para calcular a distancia entre dois arrays 
     :param a: primeiro array
     :param b: segundo array
     :return: retorna a distancia entre os dois 
     '''
     
     distancia = sp.norm(a-b)
     return distancia
Example #16
0
 def step(self):
     self._iteration_k += 1
     subgradient = self.state().middle_subgradient()
     subgradient_norm = distance.norm(subgradient, ord=2)
     t_k = self._step_size_selector.step_size(subgradient_norm,
                                              self._state.score(),
                                              self._iteration_k)
     shifted = self.state().x() - t_k * subgradient
     projected = l1_projection.project_into_simplex(shifted)
     self._state = self.state().move_to_x(projected)
Example #17
0
    def generate_displacement_word(self, word, timepoints):
        L = []

        for ot, nt in timepoints:
            modelo = self.get_predictor(ot)
            modeln = self.get_predictor(nt)
            tuples = self.get_tuples(word, ot, nt)

            for tup in tuples:
                word1 = tup[0]
                timepoint1 = tup[1]
                word2 = tup[2]
                timepoint2 = tup[3]

                if self.is_present(timepoint1, word1) and self.is_present(
                        timepoint2, word2):
                    vec1 = self.get_vector(timepoint1, word1)
                    vec2 = self.get_vector(timepoint2, word2)

                    if self.norm_embedding:
                        assert (np.isclose(norm(vec1), 1.0))
                        assert (np.isclose(norm(vec2), 1.0))

                    vec1_pred = modelo.predict(vec1)
                    vec2_pred = modeln.predict(vec2)

                    if self.norm_embedding:
                        vec1_pred = normalize_vector(vec1_pred)
                        vec2_pred = normalize_vector(vec2_pred)
                        assert (np.isclose(norm(vec1), 1.0))
                        assert (np.isclose(norm(vec2), 1.0))

                    d = self.calculate_distance(vec1_pred, vec2_pred)
                    assert (len(d) == self.number_distance_metrics())
                    L.append([word1, timepoint1, word2, timepoint2] + d)
                else:
                    # Word is not present in both time periods
                    L.append([word1, timepoint1, word2, timepoint2] + list(
                        itertools.repeat(np.nan,
                                         self.number_distance_metrics())))
        return L
Example #18
0
    def prepare_distances(self, data):
        """
        Preprocess the given data.

        Must be called before calling log_likelihood, or distances.
        :param data:
        :return:
        """
        self._distances = np.sum((data - self._u)**2, axis=1)
        assert abs(self._distances[1] -
                   distance.norm(data[1] - self._u, ord=2)**2) < 0.00001
        assert len(self._distances) == len(data)
Example #19
0
    def set_center_no_inter(self):
        """
        Set the center of the bridge.

        To be used only when there is not intersection between the bodyparts.

        """
        m0 = self.bp0.mesh.vertices
        m1 = self.bp1.mesh.vertices
        a = np.array([norm(m1 - v, axis=1) for v in m0])
        i0, i1 = np.unravel_index(np.argmin(a, axis=None), a.shape)
        self.center = 0.5 * (m0[i0] + m1[i1])
Example #20
0
def _transform_to_similarity(v, s):
    v = v / norm(v)

    if s >= 0:
        u = numpy.copy(v)
    else:
        u = -v

    n = v.shape[0]
    m = numpy.abs(v).argmax()
    u[m] = 0

    if count_nonzero(v) == 1:
        u[(m+1)%n] = sin(arccos(s))

    A = dot(u, v)
    B = dot(u, u)

    a = v[m]**2 - s**2
    b = 2 * A * v[m]
    c = A**2 - B * s**2

    umx = -b / (2 * a)
    umy_inner = max(b**2 - 4*a*c, 0)  # To handle precision errors
    umy = numpy.sqrt(umy_inner) / (2 * a)

    um1 = umx + umy
    um2 = umx - umy

    if (
        abs((um1*v[m] + A) / numpy.sqrt(um1**2 + B) - s)
        < abs((um2*v[m] + A) / numpy.sqrt(um2**2 + B) - s)):
        u[m] = um1
    else:
        u[m] = um2

    u /= norm(u)

    return u
Example #21
0
def check_emptyness(mesh, nodes, edges):
    """
    Try to guess if there are empty spaces.

    Computes the distance of each vertex to its closest
    graph node, rescaled by average mesh radius. Assumes
    something is wrong if there are vertex with dist > th

    Parameters
    ----------
    ...

    """
    radiuses = [get_radius(mesh, nodes, edge) for edge in edges]
    mean_rad = np.mean(radiuses)
    vertices_dist_to_closest_node = [min(norm(nodes - v, axis=1))
                                     for v in mesh.vertices]
    vertices_dist_to_closest_node /= mean_rad
    return max(vertices_dist_to_closest_node)
Example #22
0
    def _incremental_update(self, data_set, c_eta, c_nhr):
        total_qE = 0
        for fv in data_set:
            bm_units, c_qE = self.get_winners(fv)
            total_qE += c_qE

            # update activation map
            self.whist[bm_units] += 1

            # get bmu's multi index
            bmu_midx = _np.unravel_index(bm_units, self.shape)

            # calculate neighbourhood over bmu given current radius
            c_nh = self._neighbourhood(bmu_midx, c_nhr)

            # update lattice
            u = self.weights + c_eta * fv
            self.weights = u / _distance.norm(u)

        self.quantization_error.append(total_qE)
Example #23
0
    def value(self, functional='tv', **kwargs):
        r"""
        Compute value capturing some meaure of similarity using the
        evaluated densities on a shared comparison set.
        If either density evaluation is missing, re-compute it.

        :param funtional: a function representing a measure of similarity
        :type functional: method that takes in two lists/arrays and returns
            a scalar value (measure of similarity)

        :rtype: float
        :returns: value representing a measurement between the left and right
            sample sets, ideally a measure of similarity, a distance, a metric.

        """
        left_den, right_den = self.get_left_densities(), self.get_right_densities()
        if left_den is None:
            # logging.log(20,"Left density missing. Estimating now.")
            left_den = self.estimate_densities_left()
        if right_den is None:
            # logging.log(20,"Right density missing. Estimating now.")
            right_den = self.estimate_densities_right()

        if functional in ['tv', 'totvar',
                          'total variation', 'total-variation', '1']:
            dist = ds.minkowski(left_den, right_den, 1, w=0.5, **kwargs)
        elif functional in ['mink', 'minkowski']:
            dist = ds.minkowski(left_den, right_den, **kwargs)
        elif functional in ['norm']:
            dist = ds.norm(left_den - right_den, **kwargs)
        elif functional in ['euclidean', '2-norm', '2']:
            dist = ds.minkowski(left_den, right_den, 2, **kwargs)
        elif functional in ['sqhell', 'sqhellinger']:
            dist = ds.sqeuclidean(np.sqrt(left_den), np.sqrt(right_den)) / 2.0
        elif functional in ['hell', 'hellinger']:
            return np.sqrt(self.value('sqhell'))
        else:
            dist = functional(left_den, right_den, **kwargs)

        return dist / self._comparison_sample_set.check_num()
Example #24
0
File: cf.py Project: migushu/PHM
def cal_similarity(seq1, seq2, method):
    if method == 'pear':
        sim = pearsonr(seq1, seq2)[0]
        return sim
    elif method == 'cos':
        sim = 1 - 0.5 * distance.cosine(seq1, seq2)
        return sim
    elif method == 'norm':
        d_norm = distance.norm(np.array(seq1) - np.array(seq2), ord=2)
        sim = 1 / (1 + d_norm)
        return sim
    elif method == 'diff':
        _error = []
        _diff = []
        for i in range(len(seq1)):
            _error.append(seq2[i] - seq1[i])
        for i in range(len(_error) - 1):
            _diff.append(abs(_error[i + 1] - _error[i]))
        d_diff = np.mean(_diff)
        sim = np.exp(-10 * d_diff)
        return sim
    else:
        return -1
Example #25
0
    def visit(self, node, x):
        if (node is None):
            return
        dis = x[node.sp] - self.data[node.data, node.sp]
        if (dis > 0):
            self.visit(node.right, x)
        else:
            self.visit(node.left, x)

        if (dis > -self.neighbors[0].key):  # 剪枝
            return

        # 如果node上的数据点能进knn,就进knn
        dis0 = -norm(self.data[node.data] - x)

        if (dis0 > self.neighbors[0].key):  # 大家都是负数 大说明绝对值小,即更近,有资格进knn
            heapq.heappushpop(self.neighbors, Temp(dis0, node.data))

        # visit node的另一边区域
        if (dis > 0):
            self.visit(node.left, x)
        else:
            self.visit(node.right, x)
Example #26
0
    def cmc(self, model):
        """
        1. How to compute CMC?

        We use one camera view as the probe set, and the other as the gallery set.
        For the gallery, we randomly sample one image for each identity.
        For the probe, we use all the images, getting the CMC curve for each of them, and then average over them.
        This evaluation process is repeated for 100 times and the mean value is reported as the final result.
        See the Matlab function for more details.
        :param model:
        :return:
        """
        model.eval()
        final_feature = None
        final_id_list = []
        final_cam_id_list = []

        for ii, (image_data_list, id_data_list,
                 cam_id_list) in enumerate(self._valid_dataloader):
            final_id_list.extend(id_data_list.numpy().flatten().tolist())
            final_cam_id_list.extend(cam_id_list.numpy().flatten().tolist())
            dat_list = [image_data_list]
            dat_list = [Variable(x) for x in dat_list]
            dat_list = [x.cuda() for x in dat_list]
            image_data_list = dat_list[0]
            feature_list = model.forward(image_data_list)
            feature_list_arr = feature_list.cpu().data.numpy()
            if final_feature is None:
                final_feature = feature_list_arr
            else:
                final_feature = np.vstack([final_feature, feature_list_arr])
            norm_arr = norm(final_feature, ord=2, axis=-1)[:, np.newaxis]
            final_feature /= norm_arr

        final_id_list = np.array(final_id_list)
        final_cam_id_list = np.array(final_cam_id_list)
        unique_id, unique_idx = np.unique(final_id_list, return_inverse=True)
        nb_id = unique_id.shape[0]
        nb_data = final_id_list.shape[0]
        count = 0
        probe_view = random.randint(0, 1)
        gallery_view = 1 - probe_view
        probe_view_list = final_cam_id_list == probe_view
        gallery_view_list = final_cam_id_list == gallery_view

        range_arr = np.arange(nb_data)
        gallery_view_idx_list = []
        probe_view_idx_list = range_arr[probe_view_list]
        for identity in unique_id:
            same_id_list = identity == final_id_list
            same_id_list *= gallery_view_list
            sample_idx = random.choice(range_arr[same_id_list])
            gallery_view_idx_list.append(sample_idx)

        gallery_view_idx_list = np.array(gallery_view_idx_list)

        probe_identity_list = final_id_list[probe_view_idx_list]
        gallery_identity_list = final_id_list[gallery_view_idx_list]
        probe_feature_list = final_feature[probe_view_idx_list]
        gallery_feature_list = final_feature[gallery_view_idx_list]
        mat_dist = cdist(probe_feature_list, gallery_feature_list)
        sort_mat = np.argsort(mat_dist, axis=-1)
        # compute cmc
        # top1 top5 top10
        top1 = 0
        top5 = 0
        top10 = 0
        for i, sort_res in enumerate(sort_mat):
            match_res = probe_identity_list[i] == gallery_identity_list[
                sort_res]
            top1 += match_res[0]
            top5 += 1 if np.sum(match_res[0:5]) > 0 else 0
            top10 += 1 if np.sum(match_res[:10]) > 0 else 0
        # compute top10
        return top1 / (0. + mat_dist.shape[0]), top5 / (
            0. + mat_dist.shape[0]), top10 / (0. + mat_dist.shape[0])
Example #27
0
def update_m(obj, ia, rcut=9.0, pbc=None):
    """
    retrieve local structure around atom `ia
    for periodic systems (or very large system)
    """
    zs, coords, c = obj
    v1, v2, v3 = c
    vs = ssd.norm(c, axis=0)

    ds = ssd.squareform(ssd.pdist(coords))

    nns = []
    for i, vi in enumerate(vs):
        n1_doulbe = rcut / vi
        n1 = int(n1_doulbe)
        if n1 - n1_doulbe == 0:
            n1s = range(-n1, n1 + 1) if pbc[i] else [
                0,
            ]
        elif n1 == 0:
            n1s = [-1, 0, 1] if pbc[i] else [
                0,
            ]
        else:
            n1s = range(-n1 - 1, n1 + 2) if pbc[i] else [
                0,
            ]

        nns.append(n1s)

    n1s, n2s, n3s = nns

    n123s_ = np.array(list(itl.product(n1s, n2s, n3s)))
    n123s = []
    for n123 in n123s_:
        n123u = list(n123)
        if n123u != [0, 0, 0]: n123s.append(n123u)

    nau = len(n123s)
    n123s = np.array(n123s, np.float)

    na = len(zs)
    cia = coords[ia]

    zs_u = []
    coords_u = []
    zs_u.append(zs[ia])
    coords_u.append(coords[ia])
    for i in range(na):
        di = ds[i, ia]
        if (di > 0) and (di <= rcut):
            zs_u.append(zs[i])
            coords_u.append(coords[i])

            # add new coords by translation
            ts = np.zeros((nau, 3))
            for iau in range(nau):
                ts[iau] = np.dot(n123s[iau], c)

            coords_iu = coords[i] + ts  #np.dot(n123s, c)
            dsi = ssd.norm(coords_iu - cia, axis=1)
            filt = np.logical_and(dsi > 0, dsi <= rcut)
            nx = filt.sum()
            zs_u += [
                zs[i],
            ] * nx
            coords_u += [list(ci) for ci in coords_iu[filt, :]]

    #for ci in coords_u: print(ci)

    obj_u = [np.array(zs_u, dtype=int), np.array(coords_u)]
    assert np.all(ssd.pdist(coords_u) > 0)

    return obj_u
 def Distancia_vetores(self, a, b):
     resultado = sp.norm(a - b)
     return resultado
Example #29
0
        def f(x, y): return distance.norm(x - y)

        if metric == "euclidean":
Example #30
0
 def deterministic_gradient_size(self):
     return distance.norm(self.middle_subgradient(), ord=2)
Example #31
0
 def score(self):
     return distance.norm(np.dot(self.A(), self.x()) - self.b(), ord=1)
Example #32
0
def closeAircraftDesign(defineSpecificAirplane,
                        drivingParameters,
                        designMission,
                        silent=False):
    # DEPENDENCIES

    def setDefiningParameters(drivingParameters, X):
        definingParameters = copy.deepcopy(drivingParameters)
        definingParameters["initial gross weight"] = X[0]
        definingParameters["initial fuel weight"] = X[1]

        return definingParameters

    def functionToFindRootOf(X):
        # define airplane
        definingParameters = setDefiningParameters(drivingParameters, X)
        initialAirplane = defineSpecificAirplane(definingParameters)
        initialAirplane.passengers = ceil(designMission.passengerFactor *
                                          initialAirplane.maxPassengers)
        # simulate airplane
        simulationResult = simulateAirplane(initialAirplane,
                                            designMission,
                                            silent=silent)
        initialAirplane = simulationResult["initial airplane"]
        simulation = simulationResult["simulation"]
        finalAirplane = simulationResult["final airplane"]
        succeeded = simulationResult["succeeded"]

        # calculate resultant point
        if succeeded:
            guessedGrossWeight = definingParameters["initial gross weight"]
            predictedGrossWeight = AirplaneWeight(initialAirplane)
            grossWeightDifference = abs(guessedGrossWeight -
                                        predictedGrossWeight)
            emptyFuelMass = finalAirplane.powerplant.emptyFuelMass
            finalFuelMass = finalAirplane.powerplant.fuelMass

            result = [
                convert(grossWeightDifference, "N", "lb"),
                convert(finalFuelMass * g - emptyFuelMass * g, "N", "lb")
            ]  # W0 guess = W0 predicted, Wf capacity is all used up by end of mission
        else:
            result = [1e10, 1e10]  # pseudo bound

        print(X, "->", result, "=>", norm(
            [0, 0], result)) if not silent else None  # show convergence

        return result

    # INITIALIZATION

    guess = [convert(3000, "lb", "N"), convert(300, "lb", "N")]

    # ROOT FINDING

    result = root(functionToFindRootOf, guess, tol=1e-4)
    closestGuess = result["x"]
    airplane = defineSpecificAirplane(
        setDefiningParameters(drivingParameters, closestGuess))
    closed = norm([0, 0], result["fun"]) <= sqrt(2)  # within 1 lb & 1 lb

    return {"airplane": airplane, "closed": closed}
Example #33
0
def closeReferenceMissionByFuelWeightAndRange(baseConfiguration,
                                              referenceMission,
                                              silent=False):
    # DEPENDENCIES

    def setInitialConfiguration(airplane, referenceMission, X):
        WFguess = X[0]
        rangeGuess = X[1]
        A = copy.deepcopy(airplane)
        referenceMission.segments[
            "cruise"].completed = lambda birplane, t, t0: rangeGuess <= birplane.position
        A.powerplant.gas.mass = WFguess / g

        return (A, referenceMission)

    def functionToFindRootOf(X):
        # define airplane
        initialAirplane, referenceMissionChanged = setInitialConfiguration(
            baseConfiguration, referenceMission, X)
        # simulation
        simulationResult = simulateAirplane(initialAirplane,
                                            referenceMissionChanged,
                                            silent=silent)
        initialAirplane = simulationResult["initial airplane"]
        simulation = simulationResult["simulation"]
        finalAirplane = simulationResult["final airplane"]
        succeeded = simulationResult["succeeded"]

        # post-validation
        if succeeded:
            Wgs = [mg * g for mg in simulation["gas mass"]]
            range = simulation["position"][lastIndex(
                simulation["segment"], lambda s: s == "descent"
            )]  # the range not including the loiter segments
            # FIXME: range getting beginning of descent

            result = [
                Wgs[-1], convert(range - referenceRange, "m", "nmi")
            ]  # no gas left after whole mission & range flown = desired range

        else:
            result = [1e10, 1e10]  # pseudo bound

        print(X, "->", result, "=>", norm([0, 0], result))
        return result

    # INITIALIZATION

    Wg = baseConfiguration.powerplant.gas.mass * g if baseConfiguration.powerplant.gas else 0
    guess = [Wg, convert(100, "nmi", "m")]

    # ROOT FINDING
    result = root(functionToFindRootOf, guess, tol=1e-4, options={"eps": 25})
    closestGuess = result["x"]
    initialAirplane, referenceMissionChanged = setInitialConfiguration(
        baseConfiguration, referenceMission, closestGuess)
    closed = norm([0, 0], result["fun"]) <= sqrt(2)  # within 1 N & 1 nmi

    return {
        "airplane": initialAirplane,
        "mission": referenceMissionChanged,
        "closed": closed
    }
Example #34
0
        if (dis > -self.neighbors[0].key):  #dis是查询点到node分
            # 割数据的距离以及另一
            # 边所有数据的距离的一个下界,如果dis都没有资格进入knn
            # 那么node上的数据以及node分割的另一边区域的所有数据都无需查询
            return

        #如果node上的数据点能进knn,就进knn
        dis0 = -norm(self.data[node.data] - x)

        if (dis0 > self.neighbors[0].key):  #大家都是负数 大说明绝对值小,即更近,有资格进knn
            heapq.heappushpop(self.neighbors, Temp(dis0, node.data))

        #visit node的另一边区域
        if (dis > 0):
            self.visit(node.left, x)
        else:
            self.visit(node.right, x)


if __name__ == '__main__':

    n_samples = 1000
    n_features = 50
    k = 20
    a = np.random.randn(n_samples, n_features)
    x = np.random.rand(n_features)
    kdtree = KDTree(data=a)
    ans1 = kdtree.k_neighbers(x, k=k)
    ans2 = np.array(sorted(a, key=lambda y: norm(x - y))[:k])
    print((ans1 == ans2).all())
 def Distancia_vetores(self, a, b):
     resultado = sp.norm(a-b)
     return resultado