How to use the numpy.linspace 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 hyperspy / hyperspy / hyperspy / roi.py View on Github external
# we add one above because we include the last point in the profile
        # (in contrast to standard numpy indexing)
        line_col = np.linspace(src_col, dst_col, length)
        line_row = np.linspace(src_row, dst_row, length)

        data = np.zeros((2, length, int(linewidth)))
        data[0, :, :] = np.tile(line_col, [linewidth, 1]).T
        data[1, :, :] = np.tile(line_row, [linewidth, 1]).T

        if linewidth != 1:
            # we subtract 1 from linewidth to change from pixel-counting
            # (make this line 3 pixels wide) to point distances (the
            # distance between pixel centers)
            col_width = (linewidth - 1) * np.sin(-theta) / 2
            row_width = (linewidth - 1) * np.cos(theta) / 2
            row_off = np.linspace(-row_width, row_width, linewidth)
            col_off = np.linspace(-col_width, col_width, linewidth)
            data[0, :, :] += np.tile(col_off, [length, 1])
            data[1, :, :] += np.tile(row_off, [length, 1])
        return data
github geocryology / globsim / redcapp_XQ.py View on Github external
dataImport =  dataImport = rawData(dir_data)
            dataImport.ascii2ncdf(dem_file, dem_out)
            
        """
        
        #meta information
        header = self.asciiDemHeader(demAsciif)
        ncol   = int(re.findall(r'\d+', header[0])[0])
        nrow   = int(re.findall(r'\d+', header[1])[0])
        xllcorner = float(re.findall(r'\d+\.\d+', header[2])[0])
        yllcorner = float(re.findall(r'\d+\.\d+', header[3])[0])
        cellsize  = float(re.findall(r'\d+\.\d+', header[4])[0])
        
        #get variables
        ele = self.asciiDemEle(demAsciif)# elevation
        lats = np.linspace(yllcorner, yllcorner+cellsize*nrow, 
                           nrow, endpoint= True)# latitude
        lons = np.linspace(xllcorner, xllcorner+cellsize*ncol, 
                           ncol, endpoint= True)# lontitude
        
        #create nc file
        nc_root = nc.Dataset(dem_out ,'w', format = 'NETCDF4_CLASSIC')
        
        #create dimensions
        nc_root.createDimension('lat', nrow)
        nc_root.createDimension('lon', ncol)
        
        #create variables
        longitudes = nc_root.createVariable('lon', 'f4', ('lon'))
        latitudes  = nc_root.createVariable('lat', 'f4', ('lat'))
        elevation  = nc_root.createVariable('elevation', 
                                           'f4', ('lat', 'lon'), zlib = True)
github nanophotonics / nplab / examples / simple_experiment.py View on Github external
def threaded_experiment():
    """
    The threaded experiment function separates the experiment into the worker function which runs in
    its own thread. While the thread is running the main (GUI) thread continues updating at a different
    rate.
    :return:
    """
    x = np.linspace(0,2*2*np.pi,100)
    f = lambda i: np.sin(i)
    y = np.zeros_like(x)
    y.fill(np.nan)

    plt.ion()
    fig, ax = plt.subplots(1,1, figsize=(6,4))
    line, = plt.plot(x, y, 'ro')
    plt.xlim(x.min(), x.max())
    plt.xlabel('$x$')
    plt.ylabel('$y$')
    plt.show()

    thread = threading.Thread(target=worker, args=(x,y,f))
    t0 = time()
    thread.start()
github sao-eht / eat / eat / polcal / polcal.py View on Github external
plt.figure(figsize=(10,10))
    plt.plot(np.real(RLbyRRg),np.imag(RLbyRRg),'*b')
    plt.plot(np.real(estimatedY),np.imag(estimatedY),'r*')
    foo = Dterms[1]*np.conjugate(phasor_tot_fra) + Dterms[0]
    plt.plot(np.real(foo),np.imag(foo),'g*')
    #print('foo=', foo)
    plt.axis('equal')
    #plt.axis([-0.4,0.4,-0.4,0.4])
    plt.axhline(0,color='k',linestyle='--')
    plt.axvline(0,color='k',linestyle='--')
    plt.grid(which='both')
    plt.show()

    rhs = np.conjugate(1./gr2)*(frac_pol*np.conjugate(phasor_fra2) + Dterms[0]*np.conjugate(phasor_tot_fra) +Dterms[1])
    plt.figure(figsize=(10,10))
    t = np.linspace(0,2*np.pi,128)
    
    plt.plot(np.real(RLbyRR),np.imag(RLbyRR),'*b')
    plt.plot(np.real(rhs),np.imag(rhs),'r*')

    plt.axis('equal')
    #plt.axis([-0.4,0.4,-0.4,0.4])
    plt.axhline(0,color='k',linestyle='--')
    plt.axvline(0,color='k',linestyle='--')
    plt.grid(which='both')
    plt.show()
    #print('r =', r2)
    #print('r_m =', np.sqrt(x2**2+y2**2))
    #print('x_m =', x2)
    #print('y_m =', y2)

    return Dterms
github leeping / geomeTRIC / geometric / nifty.py View on Github external
def monotonic(arr, start, end):
    # Make sure an array is monotonically decreasing from the start to the end.
    a0 = arr[start]
    i0 = start
    if end > start:
        i = start+1
        while i < end:
            if arr[i] < a0:
                arr[i0:i+1] = np.linspace(a0, arr[i], i-i0+1)
                a0 = arr[i]
                i0 = i
            i += 1
    if end < start:
        i = start-1
        while i >= end:
            if arr[i] < a0:
                arr[i:i0+1] = np.linspace(arr[i], a0, i0-i+1)
                a0 = arr[i]
                i0 = i
            i -= 1
github jnez71 / kalmaNN / demos / 2d_classify.py View on Github external
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import kalmann

# Get some noisy training data classifications, spirals!
n = 100
stdev = 0.2
U = np.zeros((n*3, 2))
Y = np.zeros((n*3, 1), dtype='uint8')
for j in xrange(3):
    ix = range(n*j, n*(j+1))
    r = np.linspace(0, 1, n)
    t = np.linspace(j*4, (j+1)*4, n) + np.random.normal(0, stdev, n)
    U[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
    Y[ix] = j
Y[-20:-18] = 0

# Create two identical KNN's that will be trained differently
knn_ekf = kalmann.KNN(nu=2, ny=1, nl=10, neuron='logistic')
knn_sgd = kalmann.KNN(nu=2, ny=1, nl=10, neuron='logistic')

# Train
nepochs_ekf = 100
nepochs_sgd = 200
knn_ekf.train(nepochs=nepochs_ekf, U=U, Y=Y, method='ekf', P=0.2, Q=0, R=stdev**2, pulse_T=2)
knn_sgd.train(nepochs=nepochs_sgd, U=U, Y=Y, method='sgd', step=0.1, pulse_T=2)

# Use the KNNs as classifiers
F_ekf = knn_ekf.classify(U, high=2, low=0)
github obspy / obspy / obspy / imaging / source.py View on Github external
# angle between z and null
        angle = np.arccos(np.dot(zaxis, orientation))

        eye = np.eye(3, dtype=np.float64)
        raxis2 = np.outer(raxis, raxis)
        skew = np.array([[0, raxis[2], -raxis[1]],
                         [-raxis[2], 0, raxis[0]],
                         [raxis[1], -raxis[0], 0]])

        rotmtx = (raxis2 + np.cos(angle) * (eye - raxis2) +
                  np.sin(angle) * skew)

    # make uv sphere that is aligned with z-axis
    ntheta, nphi = 100, 100
    u = np.linspace(0, 2 * np.pi, nphi)
    v = np.linspace(0, np.pi, ntheta)

    x = np.outer(np.cos(u), np.sin(v))
    y = np.outer(np.sin(u), np.sin(v))
    z = np.outer(np.ones(np.size(u)), np.cos(v))

    # ravel point array and rotate them to the null axis
    points = np.vstack((x.flatten(), y.flatten(), z.flatten()))
    points = np.dot(rotmtx, points)
    return points
github scikit-hep / uproot-methods / uproot_methods / classes / TH1.py View on Github external
def __init__(self, edges):
            self._fNbins = len(edges) - 1
            self._fXmin = edges[0]
            self._fXmax = edges[-1]
            if numpy.array_equal(edges, numpy.linspace(self._fXmin, self._fXmax, len(edges), dtype=edges.dtype)):
                self._fXbins = numpy.array([], dtype=">f8")
            else:
                self._fXbins = edges.astype(">f8")
github gsig / PyVideoResearch / datasets / something_something.py View on Github external
def _prepare(self, path, labels, split):
        gap, test_gap = 4, self.test_gap
        datadir = path
        image_paths, targets, ids, times = [], [], [], []

        for i, (vid, label) in enumerate(labels.items()):
            iddir = datadir + '/' + vid
            lines = glob(iddir + '/*.jpg')
            n = len(lines)
            if i % 1000 == 0:
                print("{} {}".format(i, iddir))
            if n == 0:
                continue
            if split == 'val_video':
                spacing = np.linspace(0, n - 1, test_gap)
            else:
                spacing = range(0, n - 1, gap)
            target = torch.IntTensor(self.num_classes).zero_()
            target[int(label['class'])] = 1
            for loc in spacing:
                ii = np.floor(loc)
                impath = '{}/{}-{:06d}.jpg'.format(iddir, vid, ii + 1)
                image_paths.append(impath)
                targets.append(target)
                ids.append(vid)
                times.append(ii + 1)
        return {'image_paths': image_paths, 'targets': targets, 'ids': ids, 'times': times}
github tutajrobert / grot / deformed.py View on Github external
def discrete_cmap(ndiv, base_cmap=None):
    """Create an n-div discrete colormap from the specified input map"""
    base = plt.cm.get_cmap(base_cmap)
    color_list = base(numpy.linspace(1 - (1 / ndiv), 1 / ndiv, ndiv))
    color_list[3] = [.918, .918, .918, 1.]
    #For edge colors retrieving: 0 is for max, 1 is for min, 2 is for min label
    down_up = [base(numpy.linspace(1 - (0.2 / ndiv), 0.2 / ndiv, ndiv))[0],
               base(numpy.linspace(1 - (0.2 / ndiv), 0.2 / ndiv, ndiv))[-1],
               base(numpy.linspace(1 - (0.2 / ndiv), 0.2 / ndiv, ndiv))[-1]]
    cmap_name = base.name + str(ndiv)
    return [clr.LinearSegmentedColormap.from_list(cmap_name, color_list, ndiv),
            down_up[0], down_up[1], down_up[2]]