How to use the numpy.linalg.norm function in numpy

To help you get started, we’ve selected a few numpy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github byungsook / vectornet / graphcut_test_svg.py View on Github external
f.write('%d\n' % num_line_pixels)

    
    # support only symmetric edge weight
    for i in xrange(num_line_pixels-1):
        p1 = np.array([line_pixels[0][i], line_pixels[1][i]])
        pred_p1 = np.reshape(y_batch[i,:,:,:], [img.shape[0], img.shape[1]])
        prediction_list = []
        for j in xrange(i+1, num_line_pixels):
            p2 = np.array([line_pixels[0][j], line_pixels[1][j]])
            pred_p2 = np.reshape(y_batch[j,:,:,:], [img.shape[0], img.shape[1]])
            pred = (pred_p1[p2[0],p2[1]] + pred_p2[p1[0],p1[1]]) * 0.5
            pred = np.exp(-0.5 * (1.0-pred)**2 / FLAGS.prediction_sigma**2)
            
            if FLAGS.neighbor_sigma > 0:
                d12 = LA.norm(p1-p2, 2)
                spatial = np.exp(-0.5 * d12**2 / FLAGS.neighbor_sigma**2)
            else:
                spatial = 1.0
            f.write('%d %d %f %f\n' % (i, j, pred, spatial))
    
    f.close()
    print('%s: %s, prediction computed' % (datetime.now(), file_name))
    
    # run gco_linenet
    start_time = time.time()
    working_path = os.getcwd()
    gco_path = os.path.join(working_path, 'gco/gco_src')
    os.chdir(gco_path)
    os.environ['LD_LIBRARY_PATH'] = os.getcwd()
    call(['./gco_linenet', '../../' + pred_file_path])
    os.chdir(working_path)
github leeping / geomeTRIC / geometric / internal.py View on Github external
Compute the reference axis for adding dummy atoms. 
        Only used in the case of linear molecules.

        We first find the Cartesian axis that is "most perpendicular" to the molecular axis.
        Next we take the cross product with the molecular axis to create a perpendicular vector.
        Finally, this perpendicular vector is normalized to make a unit vector.
        """
        ysel = self.x0[self.a, :]
        vy = ysel[-1]-ysel[0]
        ev = vy / np.linalg.norm(vy)
        # Cartesian axes.
        ex = np.array([1.0,0.0,0.0])
        ey = np.array([0.0,1.0,0.0])
        ez = np.array([0.0,0.0,1.0])
        self.e0 = np.cross(vy, [ex, ey, ez][np.argmin([np.dot(i, ev)**2 for i in [ex, ey, ez]])])
        self.e0 /= np.linalg.norm(self.e0)
github jkitchin / dft-book / dft-scripts / script-253.py View on Github external
ui4 = u7 + s[0] * (u8 - u7)
    ui5 = ui1 + s[1] * (ui2 - ui1)
    ui6 = ui3 + s[1] * (ui4 - ui3)
    ui7 = ui5 + s[2] * (ui6 - ui5)
    return ui7
# compute a line with 60 points in it through these two points
P1 = np.array([0.0, 5.0, 5.0])
P2 = np.array([10.0, 5.0, 5.0])
npoints = 60
points = [P1 + n * (P2 - P1) / npoints for n in range(npoints)]
# compute the distance along the line
R = [np.linalg.norm(p - P1) for p in points]
icd = [vinterp3d(x, y, z, cd, p[0], p[1], p[2]) for p in points]
plot(R, icd)
pos = atoms.get_positions()
cR = np.linalg.norm(pos[0] - P1)
oR = np.linalg.norm(pos[1] - P1)
plot([cR, cR], [0, 2], 'r-') #markers for where the nuclei are
plot([oR, oR], [0, 8], 'r-')
xlabel('|R| ($\AA$)')
ylabel('Charge density (e/$\AA^3$)')
savefig('images/interpolated-charge-density.png')
show()
github SUNCAT-Center / CatKit / catkit / gen / utils / vectors.py View on Github external
basis_vectors : ndarray (3, 3)
        Automatically generated basis vectors from the given
        positions.
    """
    if len(coordinates) == 3:
        c0, c1, c2 = coordinates
    else:
        c0, c1 = coordinates
        c2 = np.array([0, 1, 0])

    basis1 = c0 - c1
    basis2 = np.cross(basis1, c0 - c2)
    basis3 = np.cross(basis1, basis2)

    basis_vectors = np.vstack([basis1, basis2, basis3])
    basis_vectors /= np.linalg.norm(
        basis_vectors, axis=1, keepdims=True)

    return basis_vectors
github mapillary / OpenSfM / opensfm / reconstruction.py View on Github external
def remove_outliers(graph, reconstruction, config):
    """Remove points with large reprojection error."""
    threshold = get_actual_threshold(config, reconstruction.points)
    outliers = []
    for track in reconstruction.points:
        for shot_id, error in reconstruction.points[track].reprojection_errors.items():
            if np.linalg.norm(error) > threshold:
                outliers.append((track, shot_id))

    for track, shot_id in outliers:
        del reconstruction.points[track].reprojection_errors[shot_id]
        graph.remove_edge(track, shot_id)
    for track, _ in outliers:
        if track not in reconstruction.points:
            continue
        if len(graph[track]) < 2:
            del reconstruction.points[track]
            graph.remove_node(track)
    logger.info("Removed outliers: {}".format(len(outliers)))
    return len(outliers)
github anthonyhu / tumblr-emotions / image_text_model / im_text_rnn_model.py View on Github external
session_creator=session_creator, hooks=None) as session:
            batch_size = config['batch_size']
            nb_batches = model.dataset.num_samples / batch_size
            for i in range(nb_batches):
                current_dense = session.run(model.concat_features)
                weight = float(i) * batch_size / ((i+1) * batch_size)
                dense_mean = weight * dense_mean + (1-weight) * current_dense.mean(axis=0)

            # Now look at outliers
            max_norms = np.zeros((batch_size))
            max_post_ids = np.zeros((batch_size))
            max_logits = np.zeros((batch_size, model.dataset.num_classes))
            for i in range(nb_batches):
                current_dense, np_post_ids, current_logits = session.run([model.concat_features, model.post_ids,
                    model.logits])
                current_diff = np.linalg.norm(current_dense - dense_mean, axis=1)
                for k in range(batch_size):
                    if current_diff[k] > max_norms[k]:
                        max_norms[k] = current_diff[k]
                        max_post_ids[k] = np_post_ids[k]
                        max_logits[k] = current_logits[k]
            
    np.save('data/max_norms.npy', max_norms)
    np.save('data/max_post_ids.npy', max_post_ids)
    np.save('data/max_logits.npy', max_logits)
    return max_norms, max_post_ids, max_logits
github cosmo-epfl / librascal / examples / utilities / vectors_utils.py View on Github external
soap=SOAP(**mask_body_order(self.hyperparameters))
        features1=soap.transform(self.frames[key1])
        features2=soap.transform(self.frames[key2])

        kernel = Kernel(soap,
                        target_type="Structure" if average else "Atom",
                        zeta = 2,
                        **self.hyperparameters)
        data = kernel(features2, features1)

        if (average):

            vec1 = np.mean(features1.get_dense_feature_matrix(soap),axis=0)
            vec2 = np.mean(features2.get_dense_feature_matrix(soap), axis=0)
            if(vec1.shape==vec2.shape):
                data = np.dot(vec1, vec2)/(np.linalg.norm(vec1)*np.linalg.norm(vec2))
            df=pd.DataFrame(data=[['%1.3f' %(data)]],
                            columns =[key2],
                            index =[key1]
                        )
        else:
            df=pd.DataFrame(data=[['%1.3f' %(data[i][j])
                                    for i,v in enumerate(features2._frames.numbers) if v!=1]
                                    for j,w in enumerate(features1._frames.numbers) if w!=1],
                            columns =[chemical_symbols[v] for i,v in enumerate(features2._frames.numbers) if v!=1],
                            index =[chemical_symbols[v] for i,v in enumerate(features1._frames.numbers) if v!=1]
                            )
        #
        df.name = ("Self-" if key1 == key2 else '') + \
            "Similarity " + ("Kernel" if not average else "")
        return df
github dimonaks / siman / siman / analysis.py View on Github external
# print np.array(atom_pos)

    #test if the distances between points are not spoiled by PBC 
    nbc = range(-1, 2)
    jj=0
    for x in atom_pos:

        x2 = atom_pos[jj+1]
        # x = np.array(x)
        # x2 = np.array(x2)
        r = cl.end.rprimd
        d1, _ = image_distance(x, x2, r, order = 1) #minimal distance
        x2_gen = (x2 + (r[0] * i  +  r[1] * j  +  r[2] * k) for i in nbc for j in nbc for k in nbc) #generator over PBC images
        x2c = copy.deepcopy(x2)
        ii = 0
        while  np.linalg.norm(x - x2c) > d1: #find the closest PBC image position
            if ii > 100:
                break
            ii+=1
            x2c = next(x2_gen)
        atom_pos[jj+1] = x2c
        jj+=1
        if jj == len(atom_pos)-1: # the last point is not needed, we could not use slice since we need to use changed atom_pos in place
            break
        # print np.linalg.norm(x - x2c), d1



    _, diff_barrier = plot_mep(atom_pos, mep_energies, plot = 0, show = 0, fitplot_args = fitplot_args, style_dic = style_dic)

    results_dic['barrier'] = diff_barrier
github scascketta / CapMetrics / process.py View on Github external
nearest_stop = lambda pos: get_nearest_stop(pos[1], trip_stops[pos[1].trip_id], stops)
    nearest_stop_dicts = map(nearest_stop, positions.iterrows())
    nearest_stops = pd.DataFrame(nearest_stop_dicts)

    positions['stop_lat'] = nearest_stops['stop_lat']
    positions['stop_lon'] = nearest_stops['stop_lon']
    positions['stop_id'] = nearest_stops['stop_id']

    arrival_times = get_arrival_times(positions.trip_id.unique(), positions, schedule)

    sched_times = positions.apply(lambda pos: get_sched_time(pos, arrival_times), axis=1)
    positions['sched_time'] = sched_times

    lat_diff = positions.latitude - positions.stop_lat
    lon_diff = positions.longitude - positions.stop_lon
    distances_to_stop = np.linalg.norm(zip(lat_diff, lon_diff), axis=1)
    positions['distance_to_stop'] = distances_to_stop * 100

    positions['sched_dev'] = positions.apply(lambda pos: get_sched_dev(pos), axis=1)

    positions['dayofweek'] = positions.apply(lambda pos: pos.timestamp.isoweekday(), axis=1)
    positions['hourofday'] = positions.apply(lambda pos: pos.timestamp.datetime.hour, axis=1)

    grouped = positions.groupby(['trip_id', 'stop_id'])
    selected_positions = grouped.apply(select_pos_from_group)

    return selected_positions
github deepmind / dm_control / dm_control / composer / entity.py View on Github external
RuntimeError: If the entity is not attached.
    """
    root_joint = mjcf.get_frame_freejoint(self.mjcf_model)
    if root_joint:
      if position is not None:
        physics.bind(root_joint).qpos[:3] = position
      if quaternion is not None:
        physics.bind(root_joint).qpos[3:] = quaternion
    else:
      attachment_frame = mjcf.get_attachment_frame(self.mjcf_model)
      if attachment_frame is None:
        raise RuntimeError(_NO_ATTACHMENT_FRAME)
      if position is not None:
        physics.bind(attachment_frame).pos = position
      if quaternion is not None:
        normalised_quaternion = quaternion / np.linalg.norm(quaternion)
        physics.bind(attachment_frame).quat = normalised_quaternion