Beispiel #1
0
def main(data_files1, data_files2,
         err, B=0.5003991, l=2e-2, w=1e-2,
         outfile=None):
    mu_H = lambda V_5, V_1: V_5 * l / ( V_1 * B * w)
    mu_He = lambda V_5, V_1, V_5e, V_1e: pylab.sqrt(\
                ( (l / ( V_1 * B * w)) * V_5e )**2 +\
                ( (V_5 / ( V_1 * B * w)) * 1e-4 )**2 +\
                ( (V_5 * l / ( V_1 * B * w)) * 1e-4 )**2 +\
                ( (V_5 * l / ( V_1**2 * B * w)) * V_1e )**2 +\
                ( (V_5 * l / ( V_1 * B**2 * w)) * 2e-8 )**2 +\
                ( (V_5 * l / ( V_1 * B * w**2)) * 1e-4 )**2)
    x5, x1, V5, V1, N5, N1 = [], [], [], [], [], []
    for df in data_files1:
        databox = spinmob.data.load(df)
        x, V, N = interpolate(databox)
        x5 += x
        V5 += V
        N5 += N
    for df in data_files2:
        databox = spinmob.data.load(df)
        x, V, N = interpolate(databox)
        x1 += x
        V1 += V
        N1 += N
    min_len = min([len(x5), len(x1)])
    xs = pylab.array(x5[:min_len])
    V5, V1 = pylab.array(V5[:min_len]), pylab.array(V1[:min_len])
    N5, N1 = pylab.array(N5[:min_len]), pylab.array(N1[:min_len])
    e5, e1 = err / pylab.sqrt(N5), err / pylab.sqrt(N1)
    ys, es = mu_H(V5, V1), mu_He(V5, V1, e5, e1)
    make_fig(xs, ys, es, outfile)
Beispiel #2
0
 def calibrate_delay(requested_time):
     for n_points in itertools.count(5000, 1000):
         args = generate_params(n_points)
         time_started = time.time()
         interpolate(*args)
         if time.time() - time_started > requested_time:
             return args
Beispiel #3
0
 def calibrate_delay(requested_time):
     for n_points in itertools.count(5000, 1000):
         args = generate_params(n_points)
         time_started = time.time()
         interpolate(*args)
         if time.time() - time_started > requested_time:
             return args
def correlationTest(arr1, arr2, display=False):
    print "correlation test"
    if display:
        print 'arr1'
        showArrayWithAxes(arr=arr1)
        print 'arr2'
        showArrayWithAxes(arr=arr2)
    i_arr1, j_arr1 = getCentroid(arr1)
    i_arr2, j_arr2 = getCentroid(arr2)
    M1 = getMomentMatrix(arr1, display=display)
    M2 = getMomentMatrix(arr2, display=display)
    eigenvalues1, eigenvectors1 = getAxes(M1, display=display)
    eigenvalues2, eigenvectors2 = getAxes(M2, display=display)
    arr1_coords = transform(arr1, i_arr1, j_arr1, eigenvectors=eigenvectors1,
                            eigenvalues=eigenvalues1)
    arr2_coords = transform(arr2, i_arr2, j_arr2, eigenvectors=eigenvectors2,
                            eigenvalues=eigenvalues2)

    arr1_transformed = interpolate(arr1, arr1_coords[0], arr1_coords[1])
    arr2_transformed = interpolate(arr2, arr2_coords[0], arr2_coords[1])
    correlation = getCorrelation(arr1_transformed, arr2_transformed)
    if display:
        print 'arr1_transformed'
        showArrayWithAxes(arr1_transformed)
        print 'arr2_transformed'
        showArrayWithAxes(arr2_transformed)
        print 'correlation', correlation
        print 'arr1.sum()', arr1.sum()
        print 'arr2.sum()', arr2.sum()
        print 'arr1_transformed.sum()', arr1_transformed.sum()
        print 'arr2_transformed.sum()', arr2_transformed.sum()

    return_value= {'correlation':correlation, 'arr1_transformed': arr1_transformed, 
            'arr2_transformed': arr2_transformed, }
    return return_value
Beispiel #5
0
def my_optimization(data):
    p = data[0]
    big_R = data[1]
    small_r = data[2]

    #set up boundary condition
    g = Constant(0.0)
    bc = DirichletBC(Q, g, DirichletBoundary())

    #Define initial condition
    indata = Expression(
        "pow(big_R-sqrt(pow(x[0],2)+pow(x[1],2)),2)+pow(x[2],2)<=pow(small_r,2) ? p : 0",
        degree=3,
        small_r=small_r,
        big_R=big_R,
        p=p)  #enter initial condition
    u0 = Function(Q)
    u0 = interpolate(indata, Q)

    # Define variational problem
    u = TrialFunction(Q)
    v = TestFunction(Q)
    f = Constant(0.0)

    #copy initial data
    u_initial = Function(Q)
    u_initial = interpolate(indata, Q)

    #form finite element
    a = u * v * dx + alpha * dt * dot(grad(u), grad(v)) * dx
    L = (u0 + dt * f) * v * dx

    u = u0
    t = 0.0

    save_t = []
    save_mass = []
    i = 0

    while t < T:

        t += dt
        save_t.append(t)
        solve(a == L, u, bc)
        M = (u_initial - u) * dx
        mass = assemble(M)
        save_mass.append(mass)
        u0.assign(u)

    mass_interpolate = scipy.interpolate.interp1d(save_t, save_mass)
    #key time {5, 7, 30}
    #compare with target {10, 15, 30}
    M5 = mass_interpolate(5.0)
    M7 = mass_interpolate(7.0)
    M30 = mass_interpolate(30.0)

    F = (M5 - 10.0)**2 + (M7 - 15.0)**2 + (M30 - 30.0)**2

    return F
Beispiel #6
0
def getMinimaSpline(minima, minimaValues, data):
    if len(minima) >= 4:
        minimaSpline = interpolate(minima, minimaValues, len(data),3)
    elif len(minima) == 3:
        minimaSpline = interpolate(minima, minimaValues, len(data,),2)
    else:
        minimaSpline = interpolate(minima, minimaValues, len(data),1)
    return minimaSpline
Beispiel #7
0
def getMinimaSpline(minima, minimaValues, data):
    if len(minima) >= 4:
        minimaSpline = interpolate(minima, minimaValues, len(data), 3)
    elif len(minima) == 3:
        minimaSpline = interpolate(minima, minimaValues, len(data, ), 2)
    else:
        minimaSpline = interpolate(minima, minimaValues, len(data), 1)
    return minimaSpline
Beispiel #8
0
def LS_CE(Y,pilotValue,pilotCarriers,K,P,int_opt):
    index = np.arange(P)
    LS_est = np.zeros(P, dtype=complex)
    LS_est[index] = Y[pilotCarriers] / pilotValue[index]    #complex
    if int_opt == 0:
        H_LS = interpolate(LS_est,pilotCarriers,K,0)
    if int_opt == 1:
        H_LS = interpolate(LS_est,pilotCarriers,K,1)
    return H_LS
Beispiel #9
0
    def _insert_by_distance(self, interpol_type='quadratic'):
        """Inserts nodes if distance exceeds par.MAX_SEGLEN"""
        # Raise Error if points not in strict ascending order.
        if np.any(self.x[1:] <= self.x[:-1]):
            index = tuple(np.where(self.x[1:] <= self.x[:-1])[0])
            # self.x = np.delete(self.x, index)
            # self.y = np.delete(self.y, index)
            raise ValueError(
                'Adaptive Grid: Nodes not in strictly ascending order at indices:',
                index)

        # Calculate distances of nodes
        x_dist = np.abs(self.x[1:] - self.x[:-1])
        y_dist = np.abs(self.y[1:] - self.y[:-1])
        distance = np.insert(np.sqrt(x_dist**2 + y_dist**2), 0, 0)

        # Find where and how many nodes to insert by distance criteria
        dist_index, = np.where(distance > par.MAX_SEGLEN)
        # insert_nodes = np.floor_divide(distance[dist_index], par.MAX_SEGLEN)
        insert_nodes = np.int32(np.ceil(distance[dist_index] / par.MAX_SEGLEN))
        new_points = np.split(self.x, dist_index)

        # Insert equally spaced points in x-axis
        for i in range(len(dist_index)):
            line = np.linspace(self.x[dist_index[i] - 1],
                               self.x[dist_index[i]],
                               insert_nodes[i] + 1,
                               endpoint=True)
            line = line[1:-1]
            new_points[i] = np.append(new_points[i], line)

        interpolate = scipy.interpolate.interp1d(self.x, self.y, interpol_type)
        self.x = np.concatenate(new_points)
        self.y = interpolate(self.x)
Beispiel #10
0
def convolve_gaussian(x, y, cw, fwhm, integrate=False, points=10):
    """\
    Convolve x,y with cw,fwhm.
    """
    x = np.asarray(x, dtype='f8')
    y = np.asarray(y, dtype='f8')
    cw = np.asarray(cw, dtype='f8')
    fwhm = np.asarray(fwhm, dtype='f8')

    if np.std(np.diff(x)) / np.mean(np.diff(x)) > 1e-9:
        print(np.std(np.diff(x)), np.mean(np.diff(x)))
        print('x need to be equidistant!')

    if integrate:
        ssi = sampling_interval(cw)

        z = []
        for i in range(cw.size):
            wmin = cw[i] - 0.5 * ssi[i]
            wmax = cw[i] + 0.5 * ssi[i]

            w = np.linspace(wmin, wmax, points)
            h = interpolate(w, cw, fwhm, k=3)

            zi = np.mean(convx.convolve(x, y, w, h, 'gauss'))
            z.append(zi)

        return np.array(z)

    else:
        return convx.convolve(x, y, cw, fwhm, 'gauss')
Beispiel #11
0
def make_graph(calib, results, technique):
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    calib_xy = tuple(zip(*calib))
    results_yx = tuple(zip(*results))
    ymin = min(calib[0][1], results[0][0])
    ymax = max(calib[-1][1], results[-1][0])
    ys = range(int(ymin), int(ymax + 1))
    interp_results = interpolate(ys, technique, calib)
    ax.plot(tuple(zip(*interp_results))[1],
            ys,
            color="cyan",
            label="calibration curve")
    ax.plot(results_yx[1],
            results_yx[0],
            "+",
            mec="black",
            mew=0.5,
            label="interpolated step")
    ax.plot(calib_xy[0],
            calib_xy[1],
            "o",
            mfc="none",
            mec="red",
            label="calibration point")
    ax.legend(loc="best")
    plt.savefig("test.pdf")
Beispiel #12
0
def compute_ctf(self):
    r = int(round(float(self.radius), 0))
    ctf_final = []
    bounds = np.linspace(0, r, r)
    ang, val = interpolate(self, 3)
    N = len(ang)

    ctf = np.absolute(scipy.fftpack.fft(val - np.mean(val)))
    func = 2.0 / N * np.abs(ctf[:N // 2])
    max = np.amax(func)
    # print(ind)
    qf = find_main_peak(self)

    for ri in bounds:
        xf, yf, N, func = get_fft(self, ri)

        peaks, indexes = find_peaks(self)
        ap = 0.0
        for peak in range(len(peaks)):
            if abs(peaks[peak] - qf) < 0.01:
                ap = func[indexes[peak]]
        ctf_final.append(ap)
    xr = np.linspace(0, r, r)
    db_3_interp = np.interp(0.5 * max, ctf_final, xr)

    return qf * 1 / xr, ctf_final, qf * 1 / db_3_interp, qf * 1 / self.radius, max
Beispiel #13
0
 def run(self, wpRs=None, wpts=None):
     run = True
     while run:
         run, wpRs, wpts = self.create_waypoints(wpRs, wpts)
         if run:
             self.playback_waypoints(*interpolate(wpRs, wpts))
     return wpRs, wpts
def compute_trsfs(p):
    # Create the output folder for the transfomrations
    if not os.path.exists(p.trsf_folder):
        os.makedirs(p.trsf_folder)

    trsf_fmt = 't{flo:06d}-{ref:06d}.txt'
    try:
        run_produce_trsf(p, nb_cpu=1)
        if p.sequential:
            if min(p.to_register) != p.ref_TP:
                compose_trsf(min(p.to_register), p.ref_TP, p.trsf_folder,
                             list(p.to_register))
            if max(p.to_register) != p.ref_TP:
                compose_trsf(max(p.to_register), p.ref_TP, p.trsf_folder,
                             list(p.to_register))
        np.savetxt(('{:s}' + trsf_fmt).format(p.trsf_folder,
                                              flo=p.ref_TP,
                                              ref=p.ref_TP), np.identity(4))
    except Exception as e:
        print(p.trsf_folder)
        print(e)

    if p.lowess:
        trsf_fmt = lowess_filter(p, trsf_fmt)
    if p.trsf_interpolation:
        trsf_fmt = interpolate(p, trsf_fmt)
    if p.padding:
        pad_trsfs(p, trsf_fmt)
Beispiel #15
0
def generate_object(job_id: int):
    # generate mesh with equally distributed points on surface
    mesh, n_points = generate_unity_sphere(settings.n_iter)
    r0, phi0, theta0 = cartesian_to_spherical_coordinates(
        *points_to_xyz(mesh['points']))

    # generate random radii
    r, theta, phi = generate_random_radii(
        settings.f_max, settings.n_pnts,
        settings.frequency_power_decrease_rate)

    # map random radii on the equal distributed mesh
    r_new = interpolate(theta, phi, r, theta0, phi0)

    # change the mesh
    mesh['points'] = np.vstack(
        spherical_to_cartesian_coordinates(r_new, theta0, phi0)).T

    # create and save step file
    step_file = generate_step_file(mesh)
    with open(constants.SrcPaths.object(job_id), 'w') as file:
        file.write(step_file)

    convert_shell_stp_to_object_stp(constants.SrcPaths.object(job_id))

    # return the mesh
    return mesh
Beispiel #16
0
def curved_line(endpoints):
    """Draws a curved line between the endpoints."""
    p = np.array([
        endpoints[0,:],
        # in the middle is the midpoint, except a bit higher up
        np.mean(endpoints, axis=0) + (0, 0.4),
        endpoints[1,:] ])
    return interpolate(p)
Beispiel #17
0
def drawPlot(self, mode):
    plt.figure()
    ang, val = interpolate(self, mode)
    r = int(round(self.radius, 0))
    plt.plot(ang, val, label='r={}'.format(r))
    plt.xlabel('degrees from polar axis at r')
    plt.ylabel('pixel greyscale values')
    plt.show()
Beispiel #18
0
 def map_profile_onto_turb_grid(self, profileTango):
     """Since Tango's domain is larger than GENE's in both directions, we can use a simple interpolating spline to 
     resample the profile on GENE's grid.
     """
     interpolate = scipy.interpolate.InterpolatedUnivariateSpline(
         self.psiTango, profileTango)
     profileGene = interpolate(self.psiGene)
     return profileGene
Beispiel #19
0
def test_interpolation_with_given_weights():
    for rank in [2, 3, 4, 5, 6, 7]:
        for degree in [1, 2, 3]:
            if degree >= rank - 1:
                break
            sizes = np.random.randint(5, 10, rank)
            t = np.random.randn(*sizes)

            weights = np.ones(degree)
            indices = np.array(
                [np.random.randint(max(s - 1, 0)) for s in sizes[:degree]])
            r = interpolate(t, weights, indices)
            assert (np.all(np.isclose(r, t[tuple(indices)])))

            weights = np.zeros(degree)
            r = interpolate(t, weights, indices)
            assert (np.all(np.isclose(r, t[tuple([i + 1 for i in indices])])))
Beispiel #20
0
    def createsurface(pts,
                      mode='thin_plate',
                      rbfmode=True,
                      gridCount=20,
                      zfactor=1,
                      bound=10**5,
                      matplot=False):

        modeColor = {
            'linear': (1.0, 0.3, 0.0),
            'thin_plate': (0.0, 1.0, 0.0),
            'cubic': (0.0, 1.0, 1.0),
            'inverse': (1.0, 1.0, 0.0),
            'multiquadric': (1.0, .0, 1.0),
            'gaussian': (1.0, 1.0, 1.0),
            'quintic': (0.5, 1.0, 0.0)
        }

        x = [v[1] for v in pts]
        y = [v[0] for v in pts]
        z = [zfactor * v[2] for v in pts]

        x = np.array(x)
        y = np.array(y)
        z = np.array(z)

        gridsize = gridCount

        rbf, xi, yi, zi1 = interpolate(x, y, z, gridsize, mode, rbfmode)

        # hilfsebene
        xe = [100, -100, 100, -100]
        ye = [100, 100, -100, -100]
        ze = [20, 10, 20, 5]

        rbf2, xi2, yi2, zi2 = interpolate(xe, ye, ze, gridsize, mode, rbfmode,
                                          zi1.shape)
        zi = zi1

        color = (1.0, 0.0, 0.0)
        showFace(rbf, rbf2, x, y, gridsize, color, bound)

        App.ActiveDocument.ActiveObject.Label = mode + " ZFaktor " + str(
            zfactor) + " #"
        rc = App.ActiveDocument.ActiveObject
Beispiel #21
0
def createElevationGrid(pts,mode='thin_plate',rbfmode=True,source=None,gridCount=20,zfactor=1,bound=10**5,matplot=False):
    
    modeColor={
    'linear' : ( 1.0, 0.3, 0.0),
    'thin_plate' : (0.0, 1.0, 0.0),
    'cubic' : (0.0, 1.0, 1.0),
    'inverse' : (1.0, 1.0, 0.0),
    'multiquadric' : (1.0, .0, 1.0),
    'gaussian' : (1.0, 1.0, 1.0),
    'quintic' :(0.5,1.0, 0.0)
    }


    k=0.0001
    k=0
    pts2=[p+FreeCAD.Vector(random.random(),random.random(),random.random())*k for p in pts]
    pts=pts2

    #say("points",pts)
    x=np.array(pts)[:,0]
    y=np.array(pts)[:,1]
    z=np.array(pts)[:,2]
    say(x)
    say(y)
    say(z)
    say("----------")
    
    #x=np.array(x)
    #y=np.array(y)
    #z=np.array(z)

    gridsize=gridCount

    rbf,xi,yi,zi1 = interpolate(x,y,z, gridsize,mode,rbfmode)
    
    # hilfsebene
    xe=[10,-10,10,-10]
    ye=[10,-9,10,-10]
    ze=[0,0,0,0]


    #rbf2,xi2,yi2,zi2 = interpolate(xe,ye,ze, gridsize,mode,rbfmode,zi1.shape)
    rbf2=0
    #zi=zi1-zi2
    zi=zi1

    try: color=modeColor[mode]
    except: color=(1.0,0.0,0.0)

    xmin=np.min(x)
    ymin=np.min(y)

    points=showFace(rbf,rbf2,x,y,gridsize,color,bound)
    say("XXXX points",points)

 
    return points
Beispiel #22
0
def segmentize(start, end, maxLength):
    l = distance(start, end)
    if l <= maxLength:
        return [end]
    else:
        output = []
        n = int(math.ceil(l / maxLength))
        for i in range(1, n + 1):
            output.append(interpolate(start, end, i, n))
        return output
Beispiel #23
0
def animate(i):
	i = 40*i
	x = Ix2
	y = np.zeros(len(Ix2))
	z = interpolate(sol_left[i,:],sol_right[i,:],sol_val[i,:],Ix)
	for i in range(len(Ix2)):
		y[i] = np.average(z[40*i:40*(i+1)])
	line.set_data(x, y)
	#ax.set_title('t = {0}s'.format(str(np.around(dt*i*100,decimals=2))))
	return line,
def segmentize(start,end,maxLength):
    l=distance(start,end)
    if l<=maxLength:
        return [end]
    else:
        output=[]
        n=int(math.ceil(l/maxLength))
        for i in range(1,n+1):
            output.append(interpolate(start,end,i,n))
        return output
Beispiel #25
0
def fftconvolve(x,y,yres,xres=None,normalize=False):
  if (xres is not None):
    yres = interpolate(xres,yres,x,fill_value=0)
  fft  = scipy.signal.fftconvolve(y,yres,"full")
  _idx = np.argmin( np.abs(x) ); # find t=0
  fft  = fft[_idx:_idx+len(x)]
  if normalize:
    norm = fftconvolve_find_norm(x,yres,xres=None)
  else:
    norm = 1
  return fft/norm
def envelope(signal: np.ndarray, x: np.ndarray = None, top=True, iterations=1):
    if x is None:
        x = np.arange(len(signal))
    comparator = np.greater if top else np.less

    for i in range(iterations):
        # noinspection PyUnresolvedReferences
        local_extrema = sp.signal.argrelextrema(signal, comparator)[0]
        signal = interpolate(local_extrema, signal[local_extrema], x)

    return signal
Beispiel #27
0
def align_graph(graph):
    al = GraphAlignment(graph)
    points, edges = al.align()
    points = GraphAlignment.normalize_points(points)

    pts = []
    for i in xrange(len(points)):
        pts.append(points[i])

    edges = interpolate(pts, edges)

    print "got points %s" % len(pts)
    return pts, edges
Beispiel #28
0
def regrid(a, b):
    """
    a is the object to be resized
    b provides the relevant shape information for the process
    """
    gridSizeOld = a.matrix.shape
    gridSizeNew = b.matrix.shape
    height, width = gridSizeNew
    X, Y = np.meshgrid(range(width), range(height))
    J, I = X, Y        
    # I, J = I_new, J_new
    a_new = DBZ(name=a.name+"rescaled to "+str(gridSizeNew),
                matrix = np.zeros(gridSizeNew), 
                lowerLeftCornerLatitudeLongitude=b.lowerLeftCornerLatitudeLongitude,
                )

    latOld, longOld = a.lowerLeftCornerLatitudeLongitude
    latNew, longNew = b.lowerLeftCornerLatitudeLongitude
    latDegreePerGridOld = 1.*(a.upperRightCornerLatitudeLongitude[0]-latOld)/gridSizeOld[0]
    longDegreePerGridOld= 1.*(a.upperRightCornerLatitudeLongitude[1]-longOld)/gridSizeOld[1]
    latDegreePerGridNew = 1.*(b.upperRightCornerLatitudeLongitude[0]-latOld)/gridSizeNew[0]
    longDegreePerGridNew= 1.*(b.upperRightCornerLatitudeLongitude[0]-longOld)/gridSizeNew[1]


    #I_old = (1.* I/gridSizeNew[0]+latNew -latOld) * gridSizeOld[0]  # this is wrong
    #J_old = (1.* J/gridSizeNew[0]+latNew -latOld) * gridSizeOld[0]  # we should convert
                                                                # with the degree per grid
                                                                # as the replacement below

    I_old = (1.* I*latDegreePerGridNew  +latNew  -latOld) / latDegreePerGridOld 
    J_old = (1.* J*longDegreePerGridNew +longNew -longOld) /longDegreePerGridOld 
    # debug
    print I, J
    print I_old, J_old, I_old.shape
    print "latDegreePerGridOld , longDegreePerGridOld", latDegreePerGridOld , longDegreePerGridOld 
    print "latDegreePerGridNew , longDegreePerGridNew", latDegreePerGridNew , longDegreePerGridNew
    print "gridSizeOld", gridSizeOld
    print "gridSizeNew", gridSizeNew
    print "I_old[0,0], J_old[0,0]", I_old[0,0], J_old[0,0]
    testmat = np.zeros((1000,1000))
    for ii in range(I_old.shape[0]):
        for jj in range(I_old.shape[1]):
            testmat[I_old[ii,jj]*(I_old[ii,jj]>0), J_old[ii,jj]*(J_old[ii,jj]>0)] = 1
    from matplotlib import pyplot as plt
    plt.imshow(testmat)
    plt.show()
    # end debug                                                                
    arr_old = a.matrix
    arr_new = np.zeros((height, width))
    a_new.matrix = interpolate(arr_old, arr_new, I_old, J_old)
    return a_new
Beispiel #29
0
 def do_subtract_dataset(self, dataset, object_):
   '''
     Subtract one dataset from another using interpolation.
   '''
   from copy import deepcopy
   interpolate=scipy.interpolate.interp1d
   xdata=numpy.array(dataset.data[dataset.xdata].values)
   ydata=numpy.array(dataset.data[dataset.ydata].values)
   error=numpy.array(dataset.data[dataset.yerror].values)
   x2data=numpy.array(object_.data[object_.xdata].values)
   y2data=numpy.array(object_.data[object_.ydata].values)
   error2=numpy.array(object_.data[object_.yerror].values)
   if x2data[0]>x2data[-1]:
     x2data=numpy.array(list(reversed(x2data.tolist())))
     y2data=numpy.array(list(reversed(y2data.tolist())))
     error2=numpy.array(list(reversed(error2.tolist())))
   func2=interpolate(x2data, y2data, kind='cubic', bounds_error=False, fill_value=0.)
   efunc2=interpolate(x2data, error2, kind='cubic', bounds_error=False, fill_value=0.)
   y2interp=func2(xdata)
   error2interp=efunc2(xdata)
   x2_start=x2data.min()
   x2_stop=x2data.max()
   y2_start=y2data[0]
   y2_stop=y2data[-1]
   e2_start=error2[0]
   e2_stop=error2[-1]
   for i, x in enumerate(xdata):
     if x<x2_start:
       y2interp[i]=y2_start
       error2interp[i]=e2_start
     if x>x2_stop:
       y2interp[i]=y2_stop
       error2interp[i]=e2_stop
   newdata=deepcopy(dataset)
   newdata.data[newdata.ydata].values=(ydata-y2interp).tolist()
   newdata.data[newdata.yerror].values=(numpy.sqrt(error**2+error2interp**2)).tolist()
   newdata.short_info=dataset.short_info+' - '+object_.short_info
   return newdata
Beispiel #30
0
def make_graph(calib, results, technique):
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    calib_xy = tuple(zip(*calib))
    results_yx = tuple(zip(*results))
    ymin = min(calib[0][1], results[0][0])
    ymax = max(calib[-1][1], results[-1][0])
    ys = range(int(ymin), int(ymax+1))
    interp_results = interpolate(ys, technique, calib)
    ax.plot(tuple(zip(*interp_results))[1], ys, color="cyan", label="calibration curve")
    ax.plot(results_yx[1], results_yx[0], "+", mec="black", mew=0.5, label="interpolated step")
    ax.plot(calib_xy[0], calib_xy[1], "o", mfc="none", mec="red", label="calibration point")
    ax.legend(loc="best")
    plt.savefig("test.pdf")
Beispiel #31
0
def interpolate_file_old(filename, low, high, dt):
    numlines = 0
    
    infile = open(filename)
    for l in infile:
        if l[0] == '#':
            continue
        numlines += 1
    infile.close()

    old_ts   = numpy.zeros(numlines)
    new_ts   = numpy.arange(low, high, dt)
    old_amp  = numpy.zeros(numlines)
    old_phi  = numpy.zeros(numlines)

    infile  = open(filename)
    idx     = 0

    for l in infile:
        if l[0] == '#':
            continue

        old_ts[idx], old_amp[idx], old_phi[idx] = map(float,l.strip().split())
        idx += 1

    infile.close()

    new_amp = interpolate(old_ts, new_ts, old_amp)
    new_phi = interpolate(old_ts, new_ts, old_phi)
    
    hplus   = new_amp * numpy.cos(new_phi)
    hcross  = new_amp * numpy.sin(new_phi)

    outfile = open(filename.replace('.minimal',''), 'w')
    for t, hp, hc in zip(new_ts, hplus, hcross):
        print >>outfile, '%f %e %e' % (t, hp, hc)
    outfile.close()
Beispiel #32
0
def _mcmc_lnprob(p,dspec,dspecerr,
                 teff,logg,vm,metals,cm,nm,am,
                 fixteff,fixlogg,fixvm,fixmetals,fixcm,fixnm,fixam,
                 sixd,pca,dr,lib,inter,f_format,f_access):
    # First fill in the fixed parameters
    parIndx= 0
    if fixteff:
        tteff= teff*numpy.ones(len(p))
    else:
        tteff= p[:,parIndx]
        parIndx+= 1
    if fixlogg:
        tlogg= logg*numpy.ones(len(p))
    else:
        tlogg= p[:,parIndx]
        parIndx+= 1
    if fixvm and not sixd:
        tvm= vm*numpy.ones(len(p))
    elif sixd:
        tvm= None
    else:
        tvm= 10.**p[:,parIndx]
        parIndx+= 1
    if fixmetals:
        tmetals= metals*numpy.ones(len(p))
    else:
        tmetals= p[:,parIndx]
        parIndx+= 1
    if fixcm:
        tcm= cm*numpy.ones(len(p))
    else:
        tcm= p[:,parIndx]
        parIndx+= 1
    if fixnm:
        tnm= nm*numpy.ones(len(p))
    else:
        tnm= p[:,parIndx]
        parIndx+= 1
    if fixam:
        tam= am*numpy.ones(len(p))
    else:
        tam= p[:,parIndx]
    # Get the interpolated spectra
    ispec= interpolate(tteff,tlogg,tmetals,tam,tnm,tcm,vm=tvm,
                       sixd=True,apStarWavegrid=False,dr=dr,pca=pca,
                       lib=lib,inter=inter,f_format=f_format,f_access=f_access)
    # Compute the chi^2
    chi2= _chi2(ispec,dspec[:len(ispec)],dspecerr[:len(ispec)])
    return -chi2/2.
Beispiel #33
0
def get_multid_data(data):
    data_data = [get_data(d) for d in data]
    x_vals, y_vals = interpolate(data_data, sampling_freq=3600)
    out_data = y_vals
    ret_data = []

    for index in range(len(out_data[0])):
        found_nan = False
        for x in out_data:
            if isnan(x[index]):
                found_nan = True
                break
        if found_nan:
            continue
        ret_data.append([x[index] for x in out_data])
    return ret_data
Beispiel #34
0
def get_multid_data(data):
    data_data = [get_data(d) for d in data]
    x_vals, y_vals = interpolate(data_data, sampling_freq=3600)
    out_data = y_vals
    ret_data = []

    for index in range(len(out_data[0])):
        found_nan = False
        for x in out_data:
            if isnan(x[index]):
                found_nan = True
                break
        if found_nan:
            continue
        ret_data.append([x[index] for x in out_data])
    return ret_data
Beispiel #35
0
def main():
    if len(sys.argv) < 2:
        print(' Usage:\n  python3 InterpXRange <paramFile>')
        print(' Requires python 3.x. Not compatible with python 2.x\n')
        return

    TFile = os.path.splitext(sys.argv[1])[0]
    if dP.setRange:
        TFile += '_Interp' + str(dP.rangeMin) + '-' + str(dP.rangeMax) + '.csv'
    else:
        TFile += '_Interp.csv'
    dfP = readParamFile(sys.argv[1])

    dfPint = interpolate(dfP)

    dfPint.to_csv(TFile, index=True)
Beispiel #36
0
def createNurbs(pts4,mode,gridsize):

	# calculate quadmesh
	[x,y,z]=np.array(pts4).swapaxes(0,1)
	# add some noise to avoid singular matrix

	x+= np.random.random(len(x))
	y+= np.random.random(len(x))


	x,y=y,x
	rbfmode=True

	rbf,xi,yi,zi = interpolate(x,y,z, gridsize,mode,rbfmode)
	rc=showNurbs(rbf,x,y,gridsize,z.max(),z.min(),mode)
	#showHeightMap(x,y,z,zi)
	return rc
Beispiel #37
0
def main():

    usage = "usage: %prog [options] <calibration_file>"
    parser = OptionParser(usage = usage)
    parser.add_option("-i", "--interpolation", dest="interp", default="spl",
                      help="spl spline, pwl piecewise linear, lsq least-squares",
                      metavar="TYPE")
    parser.add_option("-s", "--steps", dest="steps", default="35",
                      help="number of steps",
                      metavar="N")
    parser.add_option("-m", "--min", dest="min", default="3.3",
                      help="minimum field (mT)",
                      metavar="MILLITESLA")
    parser.add_option("-a", "--max", dest="max", default="1000",
                      help="maximum field (mT)",
                      metavar="MILLITESLA")
    parser.add_option("-g", "--graph", dest="graph", default=None,
                      help="produce a PDF graph of the calibration and steps",
                      metavar="FILENAME")
    parser.add_option("-d", "--distribution", dest="dist", default="exp",
                      help="step distribution: lin[ear] or exp[onential]",
                      metavar="TYPE")
    (opt, args) = parser.parse_args()

    if len(args) != 1:
        print("Incorrect number of arguments.")
        print(usage)
        return
    
    calibration_file = args[0]
    
    calib = make_calibration(calibration_file)
    
    desired_fields =  pick_desired_fields(float(opt.min),
                                          float(opt.max),
                                          float(opt.steps),
                                          opt.dist.startswith('e'))
    results = interpolate(desired_fields, opt.interp, calib)
    
    for result in results:
        print('%6.1f\t%5.1f' % (result[0], result[1]))

    if opt.graph:
        make_graph(calib, results, opt.interp)
Beispiel #38
0
def extend_with_zeros_both_sides(xSmall,
                                 fSmall,
                                 xLarge,
                                 enforcePositive=False):
    """Extending a function to a larger domain, with zeros where it was not originally defined.
    
    The domain xSmall should be fully contained within xLarge.  That is, xLarge extends farther outward
    on both sides of the domain.
    
    This function operates by resampling within the overlapping region xSmall, and then extending with zeros.
    
    Sometimes, interpolation might produce negative values when zero is the minimum for physical reasons.
        The diffusion coefficient is one example where one wants to maintain positivity.  In this case, one
        can optionally enforce positivity of the returned value by zeroing out negative values.
        
    Inputs:
      xSmall                independent variable on the smaller domain (array)
      fSmall                dependent variable on the smaller domain (array)
      xLarge                independent variable on the larger domain (array)
      enforcePositive       (optional) If True, set any negative values to zero before returning (boolean)
        
    Outputs:
      fLarge                dependent variable on the larger domain (array)
    """
    assert xLarge[0] <= xSmall[0] and xLarge[-1] >= xSmall[-1]
    # resample within the overlapping region
    fLarge = np.zeros_like(xLarge)  # initialize with zeros
    ind = np.where(xLarge > xSmall[0])
    indstart = ind[0][0]
    ind = np.where(xLarge < xSmall[-1])
    indfinal = ind[0][-1]
    xLargeTemp = xLarge[indstart:indfinal + 1]

    interpolate = scipy.interpolate.InterpolatedUnivariateSpline(
        xSmall, fSmall)
    fLarge[indstart:indfinal + 1] = interpolate(xLargeTemp)

    # extend with zeros -- automatically performed because fLarge was initialized with zeros
    if enforcePositive == True:
        ind = fLarge < 0
        fLarge[ind] = 0

    return fLarge
Beispiel #39
0
def renormalise(a, display=False):
    '''
    from armor.geometry import transformedCorrelations as test
    reload(test) ; a_ren = test.renormalise(a, display=True)
    '''
    arr = a.matrix
    centroid_i, centroid_j = getCentroid(arr)
    M1 = getMomentMatrix(arr)
    eigenvalues1, eigenvectors1 = getAxes(M1, display=display)
    I, J = transform(arr, centroid_i, centroid_j,
                     eigenvectors = eigenvectors1, 
                     eigenvalues = eigenvalues1,)
    arr_renormalised = interpolate(arr, I, J)
    a_renormalised = pattern.DBZ(matrix=arr_renormalised, 
                                  name= a.name+'renormalised',
                                  )
    if display:
        a_renormalised.show4()
    return a_renormalised
def r2calc(xMeas, yMeas, xRef, yRef):
    """Calculates the R-squared value for two vectors"""
    # =========================================================================
    # If the number of y points in the measured and reference vectors are not
    # equivalent, iterpolates the measured vector to have the same number of
    # data points as the reference spectra.
    # =========================================================================
    if len(yMeas) != len(yRef):
        interpolate = scipy.interpolate.interp1d
        yMeas = interpolate(xMeas,
                            yMeas,
                            kind='linear',
                            fill_value='extrapolate')(xRef)
    # =========================================================================
    # Produces a correlation coefficient matrix of the y values.
    # =========================================================================
    rMatrix = np.corrcoef(yMeas, yRef)
    r2 = rMatrix[0][1]**2
    return r2
Beispiel #41
0
 def calcMagneticFieldMap(self):
     """Calculate the magnetic field map for given solenoid and BC currents."""
     if isinstance(self.b_field, tuple):
         # Coefficients describing how the B-field depends on the sol/BC currents
         X = self.bc_current * self.b_field.bc_turns / self.b_field.bc_area
         Y = self.sol_current * self.b_field.sol_turns / self.b_field.sol_area
         # Use a subset of coefficients
         A = np.array([
             Y, Y**2, Y**3, X, X * Y, X * Y**2, X**2, X**2 * Y, X**2 * Y**2,
             X**2 * Y**3, X**3, X**3 * Y
         ]).T
         self.B_map = np.dot(self.b_field.coeffs, A)
         self.z_map = self.b_field.z_map
     else:
         # we've defined it as just an array, multiply by sol current to get field
         self.z_map, B_map = self.b_field
         self.B_map = B_map * self.sol_current
     self.B_interp = interpolate(self.z_map, self.B_map)
     self.calc_done = True
Beispiel #42
0
    def determing_rms_for_surrounding_atoms(sts):
        # change of rms on each step compared to first structure
        #here first and last structures should correspond to first and last images

        st1 = sts[0]

        st_interp = interpolate(sts[0], sts[-1], 1)[0]
        rms_list = []

        for st in sts:
            rms = rms_pos_diff(st_interp, st)
            rms_list.append(rms)
            print('rms is {:.3f}'.format(rms))

        print('d rms is {:.3f}'.format(abs(rms_list[3] - rms_list[0])))

        rms_change = abs(min(rms_list) - max(rms_list))

        return rms_change
    def swipe(self,
              x0,
              y0,
              x1,
              y1,
              move_duraion=1,
              hold_before_release=0,
              interpolation='linear'):
        if interpolation == 'linear':
            interpolate = lambda x: x
        elif interpolation == 'spline':
            import scipy.interpolate
            xs = [0, random.uniform(0.7, 0.8), 1, 2]
            ys = [0, random.uniform(0.9, 0.95), 1, 1]
            tck = scipy.interpolate.splrep(xs, ys, s=0)
            interpolate = lambda x: scipy.interpolate.splev(x, tck, der=0)
        frame_time = 1 / 100

        start_time = time.perf_counter()
        end_time = start_time + move_duraion
        self.scrcpy.control.touch(x0, y0, scrcpy_const.ACTION_DOWN)
        t1 = time.perf_counter()
        step_time = t1 - start_time
        if step_time < frame_time:
            time.sleep(frame_time - step_time)
        while True:
            t0 = time.perf_counter()
            if t0 > end_time:
                break
            time_progress = (t0 - start_time) / move_duraion
            path_progress = interpolate(time_progress)
            self.scrcpy.control.touch(int(x0 + (x1 - x0) * path_progress),
                                      int(y0 + (y1 - y0) * path_progress),
                                      scrcpy_const.ACTION_MOVE)
            t1 = time.perf_counter()
            step_time = t1 - t0
            if step_time < frame_time:
                time.sleep(frame_time - step_time)
        self.scrcpy.control.touch(x1, y1, scrcpy_const.ACTION_MOVE)
        if hold_before_release > 0:
            time.sleep(hold_before_release)
        self.scrcpy.control.touch(x1, y1, scrcpy_const.ACTION_UP)
Beispiel #44
0
def main():
    parser = script_parser()
    (options, args) = parser.parse_args()
    if len(args)!=1: # print the help message if number of args is not one.
        parser.print_help()
        sys.exit()
    optdic = vars(options)
    filein = args[0]
    navlon,navlat,data = read(filein,**optdic)
    if optdic['showmap'] is True:
       plt.pcolormesh(navlon,navlat,data)
       plt.colorbar()
       plt.show()
    x_reg,y_reg,data_reg = interpolate(data,navlon,navlat,interp=optdic['interp'])
    pspec,kstep = get_spectrum_1d(data_reg,x_reg,y_reg)
    if optdic['plotname']=='0':
       return pspec,kstep
    else:   
       plot_spectrum(pspec,kstep,**optdic)
       return
Beispiel #45
0
def main():
    parser = script_parser()
    (options, args) = parser.parse_args()
    if len(args)!=1: # print the help message if number of args is not one.
        parser.print_help()
        sys.exit()
    optdic = vars(options)
    filein = args[0]
    navlon,navlat,data = read(filein,**optdic)
    if optdic['showmap'] is True:
       plt.pcolormesh(navlon,navlat,data)
       plt.colorbar()
       plt.show()
    x_reg,y_reg,data_reg = interpolate(data,navlon,navlat,interp=optdic['interp'])
    pspec,kstep = get_spectrum_1d(data_reg,x_reg,y_reg)
    if optdic['plotname']=='0':
       return pspec,kstep
    else:   
       plot_spectrum(pspec,kstep,**optdic)
       return
Beispiel #46
0
def main():

    try:
        f = open(sys.argv[1], "r")
        lines = f.readlines()
        f.close()
    except IndexError:
        print "\nusage: " + sys.argv[0] + "  TPZ.dat\n"
        sys.exit(0)

    T, P, z, count = [], [], [], -1
    for line in lines:
        row = line.split()
        if float(row[0]) not in T:
            T.append(float(row[0]))
            P.append([])
            z.append([])
            count += 1
        P[count].append(float(row[1]))
        z[count].append(float(row[2]))

    # Interpolate
    dP = 10.0
    Pmin = 0.0
    Pmax = 200.0
    P_new = numpy.arange(Pmin, Pmax, dP / 10.0)

    z_new = []
    for i in range(len(z)):
        tck = interpolate.splrep(P[i], z[i], s=0, k=1)  # s=0: no smoothing, k=1: linear spline
        z_new.append(interpolate(P_new, tck))
    z_new = numpy.array(z_new)

    fig = pylab.figure(figsize=(12, 6), facecolor="w", edgecolor="k")
    pylab.contourf(P_new, T, z_new, 10, linewidth=0.05)
    pylab.xlim((max(y), 1.22))
    pylab.colorbar()
    pylab.savefig("test.png")
Beispiel #47
0
  sall_time = asarray(all_time)
  #print sall_time[3]
  sall_current = asarray(all_current)
  #print sall_current[3]
  new_currents = []
  with open(result_file,'wb') as ofile:
    for new_point in new_points:
      new_current = mini_interpolate(original_file,new_point)
      new_currents.append(new_current)
      ofile.write('%e %e\n' % (new_point,new_current))
  
    
  #splrepint = interpolate.splrep(sall_time, sall_current)
#  splrepint = interpolate.splrep(sall_time, sall_current, s=0)
#  currentnew = interpolate.splev(snew_points, splrepint, der=0)
  
#  index = 0
#  for icurrentnew in currentnew:
#    print index,new_points[index],currentnew[index]
  
  
if __name__ == "__main__":
  if (len(sys.argv)!=4):
    print "Usage:",sys.argv[0],"<original file> <points file> <new results file>"
    exit(2)
  original_filename = sys.argv[1]
  points_filename  = sys.argv[2]
  new_filename = sys.argv[3]
  interpolate(original_filename,points_filename,new_filename)
  print "interpolated file is:", new_filename
Beispiel #48
0
def regrid(a, b):
    """
    a is the object to be resized
    b provides the relevant shape information for the process
    """
    gridSizeOld = a.matrix.shape
    gridSizeNew = b.matrix.shape
    height, width = gridSizeNew
    X, Y = np.meshgrid(range(width), range(height))
    J, I = X, Y        
    # I, J = I_new, J_new

    latOld, longOld = a.lowerLeftCornerLatitudeLongitude
    latNew, longNew = b.lowerLeftCornerLatitudeLongitude
    latDegreePerGridOld = 1.*(a.upperRightCornerLatitudeLongitude[0]-latOld)/gridSizeOld[0]
    longDegreePerGridOld= 1.*(a.upperRightCornerLatitudeLongitude[1]-longOld)/gridSizeOld[1]
    latDegreePerGridNew = 1.*(b.upperRightCornerLatitudeLongitude[0]-latNew)/gridSizeNew[0]
    longDegreePerGridNew= 1.*(b.upperRightCornerLatitudeLongitude[1]-longNew)/gridSizeNew[1]


    #I_old = (1.* I/gridSizeNew[0]+latNew -latOld) * gridSizeOld[0]  # this is wrong
    #J_old = (1.* J/gridSizeNew[0]+latNew -latOld) * gridSizeOld[0]  # we should convert
                                                                # with the degree per grid
                                                                # as the replacement below

    I_old = 1.* (I*latDegreePerGridNew  +latNew  -latOld) / latDegreePerGridOld 
    J_old = 1.* (J*longDegreePerGridNew +longNew -longOld) /longDegreePerGridOld 
    # debug
    #print I, J
    #print I_old, J_old, I_old.shape
    #return I_old, J_old #debug
    #print "latDegreePerGridOld , longDegreePerGridOld", latDegreePerGridOld , longDegreePerGridOld 
    #print "latDegreePerGridNew , longDegreePerGridNew", latDegreePerGridNew , longDegreePerGridNew
    #print "gridSizeOld", gridSizeOld
    #print "gridSizeNew", gridSizeNew
    #print "I_old[0,0], J_old[0,0]", I_old[0,0], J_old[0,0]
    #testmat = np.zeros((1000,1000))
    #for ii in range(I_old.shape[0]):
    #    for jj in range(I_old.shape[1]):
    #        testmat[I_old[ii,jj]*(I_old[ii,jj]>0), J_old[ii,jj]*(J_old[ii,jj]>0)] = 1
    #from matplotlib import pyplot as plt
    #plt.imshow(testmat)
    #plt.show()
    # end debug                                                                
    arr_old = a.matrix
    arr_new = np.zeros((height, width))
    a_new_matrix = interpolate(arr_old, arr_new, I_old, J_old)
    a_new_matrix = a_new_matrix.view(ma.MaskedArray)
    a_new_matrix.fill_value = -999
    a_new_matrix.mask = (a_new_matrix < missingDataThreshold)   # anything below " missingDataThreshold is marked as "masked"
                                                # have to do it here
                                                # since the mask is constructed in pattern
                                                # in the pattern.load() function
                                                # which is not called here
    a_new = DBZ(name=a.name+" regridded to "+str(gridSizeNew) +\
                            "\nwith lowerleft corner" + str(b.lowerLeftCornerLatitudeLongitude),
                matrix = a_new_matrix,
                dataTime = a.dataTime,
                lowerLeftCornerLatitudeLongitude=b.lowerLeftCornerLatitudeLongitude,
                upperRightCornerLatitudeLongitude=b.upperRightCornerLatitudeLongitude,
                coordinateOrigin = b.coordinateOrigin
                )


    return a_new
Beispiel #49
0
def interpolateAlongCurve(curve, t, **kwargs):
    """Interpolate along curve.

    Return curve coordinates for a piecewise linear curve :math:`C(t) = {x_i,y_i,z_i}`
    at positions :math:`t`.
    Curve and :math:`t` values are expected to be sorted along distance from the
    origin of the curve.

    Parameters
    ----------
    curve : [[x,z]] | [[x,y,z]] | [:gimliapi:`GIMLI::RVector3`] | :gimliapi:`GIMLI::R3Vector`
        Discrete curve for 2D :math:`x,z` curve=[[x,z]], 3D :math:`x,y,z`

    t : 1D iterable
        Query positions along the curve in absolute distance

    kwargs :
        If kwargs are given an additional curve smoothing is applied using
        :py:mod:`pygimli.meshtools.interpolate`. The kwargs will be delegated.

    Returns
    -------

    p : np.array
        Curve positions at query points :math:`t`.
        Dimension of p match the size of curve the coordinates.

    Examples
    --------
    >>> # no need to import matplotlib. pygimli's show does
    >>> import numpy as np
    >>> import pygimli as pg
    >>> import pygimli.meshtools as mt
    >>> fig, axs = pg.plt.subplots(2,2)
    >>> topo = np.array([[-2., 0.], [-1., 0.], [0.5, 0.], [3., 2.], [4., 2.], [6., 1.], [10., 1.], [12., 1.]])
    >>> t = np.arange(15.0)
    >>> p = mt.interpolateAlongCurve(topo, t)
    >>> _= axs[0,0].plot(topo[:,0], topo[:,1], '-x', mew=2)
    >>> _= axs[0,1].plot(p[:,0], p[:,1], 'o', color='red') #doctest: +ELLIPSIS
    >>>
    >>> p = mt.interpolateAlongCurve(topo, t, method='spline')
    >>> _= axs[1,0].plot(p[:,0], p[:,1], '-o', color='black') #doctest: +ELLIPSIS
    >>>
    >>> p = mt.interpolateAlongCurve(topo, t, method='harmonic', nc=3)
    >>> _= axs[1,1].plot(p[:,0], p[:,1], '-o', color='green') #doctest: +ELLIPSIS
    >>>
    >>> pg.plt.show()
    >>> pg.wait()
    """
    xC = np.zeros(len(curve))
    yC = np.zeros(len(curve))
    zC = np.zeros(len(curve))

    tCurve = kwargs.pop('tCurve', None)
    if tCurve is None:
        tCurve = pg.utils.cumDist(curve)
    dim = 3

    ## extrapolate starting overlaps
    if min(t) < min(tCurve):
        d = pg.RVector3(curve[1]) - pg.RVector3(curve[0])
        #d[2] = 0.0
        d.normalise()
        curve = np.insert(curve, [0],
                          [curve[0] - np.array(d*(min(tCurve)-min(t)))[0:curve.shape[1]]],
                          axis=0)
        tCurve = np.insert(tCurve, 0, min(t), axis=0)

    ## extrapolate ending overlaps
    if max(t) > max(tCurve):
        d = pg.RVector3(curve[-2]) - pg.RVector3(curve[-1])
        #d[2] = 0.0
        d.normalise()
        curve = np.append(curve,
                          [curve[-1] - np.array(d*(max(t)-max(tCurve)))[0:curve.shape[1]]],
                          axis=0)
        tCurve = np.append(tCurve, max(t))

    if isinstance(curve, pg.R3Vector) or isinstance(curve, pg.stdVectorRVector3):
        xC = pg.x(curve)
        yC = pg.y(curve)
        zC = pg.z(curve)
    else:
        if curve.shape[1] == 2:
            xC = curve[:, 0]
            zC = curve[:, 1]
            dim = 2
        else:
            xC = curve[:, 0]
            yC = curve[:, 1]
            zC = curve[:, 2]

    if len(kwargs.keys()) > 0:
        #interpolate more curve points to get a smooth line
        dTi = min(pg.utils.dist(pg.utils.diff(curve))) / 10.
        ti = np.arange(min(tCurve), max(tCurve)+dTi, dTi)
        xC = pg.interpolate(ti, tCurve, xC, **kwargs)
        zC = pg.interpolate(ti, tCurve, zC, **kwargs)

        if dim == 3:
            yC = pg.interpolate(ti, tCurve, yC, **kwargs)
        tCurve = ti

    xt = interpolate(t, tCurve, xC)
    zt = interpolate(t, tCurve, zC)

    if dim == 2:
        return np.vstack([xt, zt]).T

    yt = interpolate(t, tCurve, yC)

    return np.vstack([xt, yt, zt]).T
def createElevationGrid(mode,rbfmode=True,source=None,gridCount=20,zfactor=20,bound=10**5,matplot=False):
	
	modeColor={
	'linear' : ( 1.0, 0.3, 0.0),
	'thin_plate' : (0.0, 1.0, 0.0),
	'cubic' : (0.0, 1.0, 1.0),
	'inverse' : (1.0, 1.0, 0.0),
	'multiquadric' : (1.0, .0, 1.0),
	'gaussian' : (1.0, 1.0, 1.0),
	'quintic' :(0.5,1.0, 0.0)
	}

	print ("Source",source,"mode",mode)
	if source<>None:

		if hasattr(source,"Shape"):
			# part object
			pts=[v.Point for v in  source.Shape.Vertexes]

			p=Points.Points(pts)
			Points.show(p)
			pob=App.ActiveDocument.ActiveObject
			pob.ViewObject.PointSize = 10.00
			pob.ViewObject.ShapeColor=(1.0,0.0,0.0)

		elif hasattr(source,"Points"):
			# point cloud

			pts=source.Points.Points

		elif source.__class__.__name__ == 'DocumentObjectGroup':
			hls=App.ActiveDocument.hoehenlinien
			apts=[]
			for l in hls.OutList:
				pts=[v.Point for v in  l.Shape.Vertexes]
				apts += pts

			pts=apts

		else:
			raise Exception("don't know to get points")

		x=[v[1] for v in pts]
		y=[v[0] for v in pts]
		z=[0.01*v[2] for v in pts]
		# staerker
		z=[zfactor*v[2] for v in pts]
		px= coordLists2points(x,y,z)
		Points.show(Points.Points(px))


	else:
		# testdata
		x,y,z= text2coordList(datatext)
		p= coordLists2points(x,y,z)

	x=np.array(x)
	y=np.array(y)
	z=np.array(z)

	gridsize=gridCount

	rbf,xi,yi,zi1 = interpolate(x,y,z, gridsize,mode,rbfmode)
	
	# hilfsebene
	xe=[100,-100,100,-100]
	ye=[100,100,-100,-100]
	ze=[20,10,20,5]

	rbf2,xi2,yi2,zi2 = interpolate(xe,ye,ze, gridsize,mode,rbfmode,zi1.shape)
	
	#print zi1.shape
	#print zi2.shape
	
	#zi=zi1-zi2
	zi=zi1

	try: color=modeColor[mode]
	except: color=(1.0,0.0,0.0)

	xmin=np.min(x)
	ymin=np.min(y)

	showFace(rbf,rbf2,x,y,gridsize,color,bound)
 
	App.ActiveDocument.ActiveObject.Label=mode + " ZFaktor " + str(zfactor) + " #"
	rc=App.ActiveDocument.ActiveObject


	if matplot: showHeightMap(x,y,z,zi)
	return rc

	# interpolation for image
	gridsize=400
	rbf,xi,yi,zi = interpolate(x,y,z, gridsize,mode,rbfmode)
	rbf2,xi2,yi2,zi2 = interpolate(xe,ye,ze, gridsize,mode,rbfmode,zi.shape)
	return [rbf,rbf2,x,y,z,zi,zi2]
        from scipy.interpolate import interp1d
        self.intp = [interp1d(np.linspace(0, Ls, len(r)), r) for r in cqt]
    def __call__(self,x):
        try:
            len(x)
        except:
            return np.array([i(x) for i in self.intp])
        else:
            return np.array([[i(xi) for i in self.intp] for xi in x])

real = 1
Ls = 8            
c = np.random.randint(0, 255, (10,4)).astype(float)
x = np.linspace(0, Ls, 32)
hf = -1 if real else len(c)/2
grid = interpolate(imap(np.abs, c[2:hf]), Ls)(x)
# display grid
img = np.log(np.flipud(grid.T))

fig = plt.figure()
plt.imshow(img, cmap=plt.cm.gray, 
           aspect=float(grid.shape[0]) / grid.shape[1] * 0.5,
            interpolation='nearest')
plt.show()



from scipy import interpolate
x = np.arange(0, 10)
y = np.exp(-x/3.0)
f = interpolate.interp1d(x, y)
Beispiel #52
0
upvpb  = ppcompute.mean(up*vp ,axis=0) ; etape("upvpb" ,time0) ; del up ; del vp
print upvpb.shape
upvpbc = ppcompute.mean(upvpb ,axis=2) ; etape("upvpbc",time0) ; del upvpb

### stationary: negligible
#us  = pp(file=fileAP,var="u"    ,compute="pert_x").getf() ; etape("us",time0)
#vs  = pp(file=fileAP,var="v"    ,compute="pert_x").getf() ; etape("vs",time0)
#us_b  = ppcompute.mean(us    ,axis=0) ; etape("usb"  ,time0) ; del us
#vs_b  = ppcompute.mean(vs    ,axis=0) ; etape("vsb"  ,time0) ; del vs
#usvsbc = ppcompute.mean(us_b,axis=2)*ppcompute.mean(vs_b,axis=2) ; etape("usvsbc",time0)
#usvsbc = interpolate(targetp1d,press,usvsbc) ; etape("usvsbc",time0)


####################################################
print "... interpolating !"
ubc    = interpolate(targetp1d,press,ubc)    ; etape("ubc"   ,time0) ; addvar(outfile,nam4,'ubc',ubc)
vbc    = interpolate(targetp1d,press,vbc)    ; etape("vbc"   ,time0) ; addvar(outfile,nam4,'vbc',vbc)
#tbc    = interpolate(targetp1d,press,tbc)    ; etape("tbc"   ,time0)
upvpbc = interpolate(targetp1d,press,upvpbc) ; etape("upvpbc",time0)
dudt = interpolate(targetp1d,press,dudt)    ; etape("dudt"   ,time0) ; addvar(outfile,nam4,'dudt',dudt)

####################################################
nz,nlat = ubc.shape
nlon = 1
lat2d = np.tile(ydim,(nz,1))
acosphi2d = myp.acosphi(lat=lat2d)
cosphi2d = acosphi2d / myp.a
latrad,lat2drad = ydim*np.pi/180.,lat2d*np.pi/180.
beta = myp.beta(lat=lat2d)
f = myp.fcoriolis(lat=lat2d)
print f
def interpolate(x,y,z,xi,yi,type):
	
	X,Y = meshgrid(x,y)
	outgrid = interp2d( X,Y,z,kind=type)
	zi=outgrid(xi,yi)
	return zi



# digitizing the camber factor Kc from ESDU 00027
x_kc = [ 0,0.1,0.2,0.3,0.4,0.5,0.6,0.65,0.7,0.75]
y_kc = [0,0.5,1,1.5,2,2.5,3,3.5,4]
readfile('Kc_z.txt',z_kc)
c=0.7
d=3
Kc= interpolate(x_kc,y_kc,z_kc,c,d,'linear')
# print 'Kc =',Kc

# digitizing the mach number factor Km from ESDU 00027

if M>=0.5 and tm_by_c>=0.08:
	x_Km_35_1 = [ 0.5,0.6,0.65,0.7,0.75]
	y_Km_35_1 = [0.08,0.1,0.12,0.14,0.16,0.18,0.2]
	readfile('Km_35_1.txt',Km_35_1)
	Km_35 = interpolate( x_Km_35_1,y_Km_35_1, Km_35_1, M , tm_by_c,'linear')
	#print Km_35

if M>=0.5 and tm_by_c<0.08:
	x_Km_35_2 = [ 0.02,0.04,0.06,0.08]
	y_Km_35_2 = [0.5,0.6,0.65,0.7,0.75]
	readfile('Km_35_2.txt',Km_35_2)
Beispiel #54
0
bs.interpolate(bsp3)
bss=bs.toShape()

if 0:
	prof=FreeCAD.getDocument("Unnamed").addObject("Part::Feature","Length Profile")
	prof.Shape=bss



lls2=np.array(lls).swapaxes(0,1)
(y,x,z)=lls2

mode="linear"
gridsize=5
if 0:
	rbf,xi,yi,zi1 = interpolate(x,y,z, gridsize,mode)
	showHeightMap(x,y,z,zi1)

import random



lan=50
ll=[[l[0],l[1]] for l in lls if l[2]<lan+1 and l[2]>=lan]

'''
from scipy.spatial import Voronoi, voronoi_plot_2d
vor = Voronoi(ll)

import matplotlib.pyplot as plt
voronoi_plot_2d(vor)
Beispiel #55
0
def powspec_initialise(cosm):
  if choose():
    z = raw_input("Enter z value of produced spectrum:")
    ident = raw_input("Enter identification number:")
    k,P = import_powerspectrum(ident,z)
    return interpolate(k,P)
Beispiel #56
0
def run():
	x, values, header = extract(IN_FILE)
	newX = np.linspace(0, 1, NUM_ROWS)
	newValues = interpolate(x, newX, values)
	output(newX, newValues, header)
Beispiel #57
0
def elemchi2(spec,specerr,
             elem,elem_linspace=(-0.5,0.5,11),tophat=False,
             fparam=None,
             teff=4750.,logg=2.5,metals=0.,am=0.,nm=0.,cm=0.,vm=None,
             lib='GK',pca=True,sixd=True,dr=None,
             offile=None,
             inter=3,f_format=1,f_access=None,
             verbose=False):
    """
    NAME:
       elemchi2
    PURPOSE:
       Calculate the chi^2 for a given element
    INPUT:
       Either:
          (1) location ID - single or list/array of location IDs
              APOGEE ID - single or list/array of APOGEE IDs; loads aspcapStar
          (2) spec - spectrum: can be (nwave) or (nspec,nwave)
              specerr - spectrum errors: can be (nwave) or (nspec,nwave)
       elem - element to consider (e.g., 'Al')
       elem_linspace= ((-0.5,0.5,11)) numpy.linspace range of abundance, relative to the relevant value in fparam / metals,am,nm,cm
       tophat= (False) if True, don't use the value of weights, just use them to define windows that have weight equal to one
       Input parameters (can be 1D arrays)
          Either:
             (1) fparam= (None) output of ferre.fit
             (2) teff= (4750.) Effective temperature (K)
                 logg= (2.5) log10 surface gravity / cm s^-2
                 metals= (0.) overall metallicity
                 am= (0.) [alpha/M]
                 nm= (0.) [N/M]
                 cm= (0.) [C/M]
                 vm= if using the 7D library, also specify the microturbulence
       Library options:
          lib= ('GK') spectral library
          pca= (True) if True, use a PCA compressed library
          sixd= (True) if True, use the 6D library (w/o vm)
          dr= data release
       FERRE options:
          inter= (3) order of the interpolation
          f_format= (1) file format (0=ascii, 1=unf)
          f_access= (None) 0: load whole library, 1: use direct access (for small numbers of interpolations), None: automatically determine a good value (currently, 1)
       verbose= (False) if True, run FERRE in verbose mode
    OUTPUT:
       chi^2
    HISTORY:
       2015-03-12 - Written - Bovy (IAS)
    """
    # Parse fparam
    if not fparam is None:
        teff= fparam[:,paramIndx('TEFF')]
        logg= fparam[:,paramIndx('LOGG')]
        metals= fparam[:,paramIndx('METALS')]
        am= fparam[:,paramIndx('ALPHA')]
        nm= fparam[:,paramIndx('N')]
        cm= fparam[:,paramIndx('C')]
        if sixd:
            vm= None
        else:
            vm= fparam[:,paramIndx('LOG10VDOP')]        
    # parse spec, specerr input
    nspec= len(teff)
    if len(spec.shape) == 1:
        spec= numpy.reshape(spec,(1,spec.shape[0]))
        specerr= numpy.reshape(specerr,(1,specerr.shape[0]))
    # Read the weights
    if tophat:
        weights= apwindow.tophat(elem,apStarWavegrid=False,dr=dr)
    else:
        weights= apwindow.read(elem,apStarWavegrid=False,dr=dr)
        weights/= numpy.sum(weights)
    # Decide which parameter to vary
    nvelem= elem_linspace[2]
    var_elem= numpy.tile(numpy.linspace(*elem_linspace),(nspec,1))   
    if elem.lower() == 'c':
        cm= var_elem+numpy.tile(cm,(nvelem,1)).T
    elif elem.lower() == 'n':
        nm= var_elem+numpy.tile(nm,(nvelem,1)).T
    elif elem.lower() in ['o','mg','s','si','ca','ti']:
        am= var_elem+numpy.tile(am,(nvelem,1)).T
    else:
        metals= var_elem+numpy.tile(metals,(nvelem,1)).T
    # Upgrade dimensionality of other parameters for interpolate input
    teff= numpy.tile(teff,(nvelem,1)).T
    logg= numpy.tile(logg,(nvelem,1)).T
    if not sixd:
        vm= numpy.tile(vm,(nvelem,1)).T.flatten()
    if not elem.lower() == 'c':
        cm= numpy.tile(cm,(nvelem,1)).T
    if not elem.lower() == 'n':
        nm= numpy.tile(nm,(nvelem,1)).T
    if not elem.lower() in ['o','mg','s','si','ca','ti']:
        am= numpy.tile(am,(nvelem,1)).T
    if elem.lower() in ['c','n','o','mg','s','si','ca','ti']:
        metals= numpy.tile(metals,(nvelem,1)).T
    # Get interpolated spectra, [nspec,nwave]
    ispec= interpolate(teff.flatten(),logg.flatten(),metals.flatten(),
                       am.flatten(),nm.flatten(),cm.flatten(),vm=vm,
                       lib=lib,pca=pca,sixd=sixd,dr=dr,
                       inter=inter,f_format=f_format,f_access=f_access,
                       verbose=verbose,apStarWavegrid=False)
    dspec= numpy.tile(spec,(1,nvelem)).reshape((nspec*nvelem,spec.shape[1]))
    dspecerr= numpy.tile(specerr,
                         (1,nvelem)).reshape((nspec*nvelem,spec.shape[1]))
    tchi2= _chi2(ispec,dspec,dspecerr,numpy.tile(weights,(nspec*nvelem,1)))
    return numpy.reshape(tchi2,(nspec,nvelem))