예제 #1
0
def linear(x, y, xx):
    """
    Linear Interpolation

    Parameters
    ----------
    x : ndarray shape:(n)
        x of data points
    y : ndarray shape:(n)
        y of data points
    xx : ndarray shape:(k)
        x of target points

    Returns
    -------
    yy : ndarray shape:(k)
        y of target points

    """
    yy = numpy.zeros(len(xx))
    n = len(x)
    for k in range(0, n - 1):
        flag = ((xx >= x[k]) & (xx < x[k + 1]))
        yy[flag] = lagrange(x[k:k + 2], y[k:k + 2], xx[flag])
    return yy
예제 #2
0
 def __init__(self,points):
     """
     @points : a dictionary whose keys are x values and values are
     y values to be considered as fixed points for interpolation.  
     """
     Function.__init__(self)
     self.polynom = lagrange.lagrange(points)
def lagrange1st(N):
    # Calculation of 1st derivatives of Lagrange polynomials
    # at GLL collocation points
    # out = legendre1st(N)	
    # out is a matrix with columns -> GLL nodes
    #                        rows -> order
    
    from gll import gll
    from lagrange import lagrange
    from legendre import legendre
    import numpy as np
    
    out = np.zeros([N+1, N+1])
    
    
    [xi, w] = gll(N)
    
    # initialize dij matrix (see Funaro 1993 or Diploma thesis Bernhard Schuberth)
    

    d = np.zeros([N+1, N+1])
    
    for i in range (-1, N): 
        for j in range (-1, N): 
            if i != j:
                d[i+1,j+1] = legendre(N,xi[i+1])/legendre(N,xi[j+1])*1/(xi[i+1]-xi[j+1])
    
            if i == -1:
                if j == -1:
                    d[i+1,j+1] = float(-1)/float(4)*N*(N+1)
    
    
            if i == N-1:
                if j == N-1:
                    d[i+1,j+1] = float(1)/float(4)*N*(N+1)
    
    # Calculate matrix with 1st derivatives of Lagrange polynomials
    
    for n in range (-1, N):
        for i in range (-1, N):
            sum=0
            for j in range(-1, N):
                sum = sum + d[i+1,j+1]*lagrange(N,n,xi[j+1])
    
            out[n+1,i+1] = sum  
        
        
    return(out)
예제 #4
0
def lagrange1st(N):
    """
    # Calculation of 1st derivatives of Lagrange polynomials
    # at GLL collocation points
    # out = legendre1st(N)
    # out is a matrix with columns -> GLL nodes
    #                        rows -> order
    """
    out = np.zeros([N+1, N+1])

    [xi, w] = gll(N)

    # initialize dij matrix (see Funaro 1993 or Diploma thesis Bernhard
    # Schuberth)
    d = np.zeros([N + 1, N + 1])

    for i in range(-1, N):
        for j in range(-1, N):
            if i != j:
                d[i + 1, j + 1] = legendre(N, xi[i + 1]) / \
                    legendre(N, xi[j + 1]) * 1.0 / (xi[i + 1] - xi[j + 1])
            if i == -1:
                if j == -1:
                    d[i + 1, j + 1] = -1.0 / 4.0 * N * (N + 1)
            if i == N-1:
                if j == N-1:
                    d[i + 1, j + 1] = 1.0 / 4.0 * N * (N + 1)

    # Calculate matrix with 1st derivatives of Lagrange polynomials
    for n in range(-1, N):
        for i in range(-1, N):
            sum = 0
            for j in range(-1, N):
                sum = sum + d[i + 1, j + 1] * lagrange(N, n, xi[j + 1])

            out[n + 1, i + 1] = sum
    return(out)
예제 #5
0
def keys_to_secret(xs, keys):
    y = np.zeros(M,dtype=int)
    for m in range(M):
        points = []
        for i in range(len(keys)):
            x = xs[i]
            key = keys[i]*P/255
            key = key.reshape(128*128)
            key = key[0:M]
            points.append((x,key[m]))
        y[m] = lagrange(points, P)

    secret_str = ''
    print(len(y))
    #print(y)
    for yi in range(len(y)):
        secret_str = secret_str + '{:04x}'.format(y[yi])

    print(len(secret_str))
    #print(secret_str)
    data = bytes.fromhex(secret_str)
    print(len(secret_str))
    print(len(data))
    return data
예제 #6
0
파일: iterate.py 프로젝트: KevinKSY/TEA
    print("pre-loop setup:     " + str(elapsed))

# ====================== PERFORM MAIN TEA LOOP ====================== #

while repeat:
    # Output iteration number
    if ((not doprint) & (not times)):
        stdout.write(' ' + str(it_num) + '\r')
        stdout.flush()

    # Time / speed testing for lagrange.py
    if times:
        ini = time.time()
    
    # Execute Lagrange minimization
    lagrange_data = lg.lagrange(it_num, datadir, doprint, lambdacorr_data)
    
    # Time / speed testing for lagrange.py
    if times:
        fin = time.time()
        elapsed = fin - ini
        print("lagrange" + str(it_num).rjust(4) + " :      " + str(elapsed))    
      
    # Print for debugging purposes
    if doprint:
        printout('Iteration %d Lagrange complete. Starting lambda correction...', it_num)
    
    # Take final x_i mole numbers from last Lagrange calculation 
    lagrange_x = lagrange_data[4]
    
    # Check if x_i have negative mole numbers, and if yes perform lambda correction
# -*- coding: utf-8 -*-
# Linjen over er for å tillate bruk av æ, ø og å.

import numpy as np  # For NumPy
import matplotlib.pyplot as plt  # For plotting med matplotlib
from lagrange import lagrange  # Importerer lagrange-funksjonen fra lagrange.py.

x = np.array([-1.5, -0.75, 0, 0.75, 1.5])  # Interpoleringspunkter
f = np.array([-14.1014, -0.931597, 0.0, 0.931597, 14.1014])  # Kjente verdier.
X = np.linspace(-1.5, 1.5, 100)  # 100 jevnt fordelte punkter fra -1,5 til 1,5
F = lagrange(X, x, f)  # OBS: I en tidligere utgave av koden stod det
# her "interpolate" istedet for "lagrange". Beklager!

# Følgende plottekode kan bare kopieres direkte.
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, f, "o", color="black", label="kjente punkter")
ax.plot(X, np.tan(X), color="black", linestyle="dashed", label="tan")
ax.plot(X, F, color="black", label="interpolert")
ax.set_xlim(-1.55, 1.55)
ax.legend(loc="upper left")
plt.show()
예제 #8
0
def iterator(head, destination, location_out):
    # Correct location_TEA name
    if location_out[-1] != '/':
        location_out += '/'

    # Time / speed testing
    if times:
        end = time.time()
        elapsed = end - start
        print("iterate.py imports: " + str(elapsed))

    # Read run-time arguments
    header = head              # Name of header file
    desc   = destination              # Directory name

    # Create and name outputs and results directories if they do not exist
    datadir   = location_out + desc + '/outputs/' + 'transient/'
    datadirr  = location_out + desc + '/results'                

    if not os.path.exists(datadir): os.makedirs(datadir)
    if not os.path.exists(datadirr): os.makedirs(datadirr)

    # Retrieve header info
    inhead    = form.readheader(header)
    pressure  = inhead[0]
    temp      = inhead[1]

    # Locate and read initial iteration output from balance.py
    infile    = datadir + '/lagrange-iteration-0-machine-read.txt'
    input     = form.readoutput(infile)

    # Retrieve and set initial values
    speclist  = input[2]
    x         = input[3]
    x_bar     = input[6]

    # Set up first iteration 
    it_num  = 1
    repeat  = True

    # Prepare data object for iterative process 
    #         (see description of the 'direct' object in lagrange.py)
    lambdacorr_data = [header, 0, speclist, x, x, 0, x_bar, x_bar, 0]

    # Time / speed testing
    if times:
        new = time.time()
        elapsed = new - end
        print("pre-loop setup:     " + str(elapsed))

    # ====================== PERFORM MAIN TEA LOOP ====================== #

    while repeat:
        # Output iteration number
        if ((not doprint) & (not times)):
            stdout.write(' ' + str(it_num) + '\r')
            stdout.flush()

        # Time / speed testing for lagrange.py
        if times:
            ini = time.time()
        
        # Execute Lagrange minimization
        lagrange_data = lg.lagrange(it_num, datadir, doprint, lambdacorr_data)
        
        # Time / speed testing for lagrange.py
        if times:
            fin = time.time()
            elapsed = fin - ini
            print("lagrange" + str(it_num).rjust(4) + " :      " + str(elapsed))    
          
        # Print for debugging purposes
        if doprint:
            printout('Iteration %d Lagrange complete. Starting lambda correction...', it_num)
        
        # Take final x_i mole numbers from last Lagrange calculation 
        lagrange_x = lagrange_data[4]
        
        # Check if x_i have negative mole numbers, and if yes perform lambda correction
        if where((lagrange_x < 0) == True)[0].size != 0:
            # Print for debugging purposes 
            if doprint:
                printout('Correction required. Initializing...')
                
            # Time / speed testing for lambdacorr.py
            if times:
                ini = time.time()
            
            # Execute lambda correction
            lambdacorr_data = lc.lambdacorr(it_num, datadir, doprint, \
                                                       lagrange_data)
            
            # Print for debugging purposes
            if times:
                fin = time.time()
                elapsed = fin - ini
                print("lambcorr" + str(it_num).rjust(4) + " :      " + \
                                                          str(elapsed))
            
            # Print for debugging purposes
            if doprint:
                printout('Iteration %d lambda correction complete. Checking precision...', it_num)

        # Lambda correction is not needed
        else:
            # Pass previous Lagrange results as inputs to next iteration
            lambdacorr_data = lagrange_data

            # Print for debugging purposes
            if doprint:
                printout('Iteration %d did not need lambda correction.', it_num)
        
        # Retrieve most recent iteration values
        input_new = lambdacorr_data

        # Take most recent x_i and x_bar values    
        x_new     = input_new[4]
        x_bar_new = input_new[7]
        
        # If max iteration not met, continue with next iteration cycle
        if it_num < maxiter: 
            # Add 1 to iteration number
            it_num += 1

            # Print for debugging purposes
            if doprint:
                printout('Max interation not met. Starting next iteration...\n')
        
        # ============== Stop the loop, max iteration reached ============== #

        # Stop if max iteration is reached 
        else:
            # Print to screen
            printout('Maximum iteration reached, ending minimization.\n')

            # Set repeat to False to stop the loop
            repeat = False

            # Calculate delta values
            delta = x_new - x

            # Calculate delta_bar values
            delta_bar = x_bar_new - x_bar
            
            # Name output files with corresponding iteration number name
            file_results       = datadirr + '/results-machine-read.txt'
            file_fancyResults  = datadirr + '/results-visual.txt'

            # Export all values into machine and human readable output files  
            form.output(datadirr, header, it_num, speclist, x, x_new, delta,    \
                        x_bar, x_bar_new, delta_bar, file_results, doprint)
            form.fancyout_results(datadirr, header, it_num, speclist, x, x_new, \
                                  delta, x_bar, x_bar_new, delta_bar, pressure, \
                                  temp, file_fancyResults, doprint)
예제 #9
0
    # nova imagem
    new_img = np.zeros(shape=(dimensions[1], dimensions[0]), dtype=np.uint8)

    for row in range(0, new_img.shape[0]):
        for col in range(0, new_img.shape[1]):
            coord = np.array([[row], [col]])
            new_coord = inverse @ coord

            if mode == "neighbor":
                new_img[row][col] = neighbor(img,
                                             new_coord.ravel()[0],
                                             new_coord.ravel()[1])
            elif mode == "bilinear":
                new_img[row][col] = bilinear(img,
                                             new_coord.ravel()[0],
                                             new_coord.ravel()[1])
            elif mode == "bicubic":
                new_img[row][col] = bicubic(img,
                                            new_coord.ravel()[0],
                                            new_coord.ravel()[1])
            else:
                new_img[row][col] = lagrange(img,
                                             new_coord.ravel()[0],
                                             new_coord.ravel()[1])

    io.imsave(outputname, new_img)

    elapsed_time = time.time() - start_time
    print("Elapsed time: %1f s" % (elapsed_time))
예제 #10
0
파일: runge_test.py 프로젝트: davxy/numeric
#
minpoints, maxpoints = 5, 17  # min and max number of nodes
ibeg, iend = -5, 5  # interval begin and end
step = 4
func = runge_func

#get_nodes = equis_nodes
get_nodes = cheby_nodes

xx = np.linspace(ibeg, iend, 100)
yy = [func(x) for x in xx]
for n in range(minpoints, maxpoints + 1, step):
    _, ax = plt.subplots()
    ax.plot(xx, yy)
    xpoints = get_nodes(ibeg, iend, n)
    ypoints = [func(x) for x in xpoints]
    yy1 = lagrange(xpoints, ypoints, xx)
    ax.plot(xx, yy1)
    ax.scatter(xpoints, ypoints, s=15, color='black')
    ax.text(0.2,
            0.9,
            'n={}'.format(n),
            fontsize=20,
            transform=plt.gcf().transFigure)
    # Print Lebesgue constant
    lamb = lebesgue_const(xx, xpoints)
    print("n = {:2}   lambda = {}".format(n, lamb))

# Show the graphs
plt.show()
예제 #11
0
파일: iterate.py 프로젝트: obowman/TEA
#    for as long as is necessary given max iterations, precision, etc.  Loop is
#    performed in chunks of two to allow comparison between two most recent loops
#    without isolting the first loop.
while repeat:
    # Simple progress info
    if ((not doprint) & (not times)):
        stdout.write(' ' + str(it_num) + '\r')
        stdout.flush()
        
    # ### Perform 'starting' iteration
    # Time / speed testing for first lagrange
    if times:
        ini = time.time()
    
    # Execute lagrange minimization
    ini_iter = lg.lagrange(it_num, datadir, doprint, fin_iter2)
    
    if times:
        fin = time.time()
        elapsed = fin - ini
        print("lagrange" + str(it_num).rjust(4) + " :      " + str(elapsed))
    
    # Cleanup files that are no longer needed
    #form.cleanup(datadir, it_num, clean)
    
    if doprint:
        printout('Iteration %d Lagrange complete. Starting lambda correction...', it_num)
    
    # Recieve files by memory or file
    #if fin_iter2:
    lag_dat, lag_dat2 = ini_iter[4], ini_iter[7]
예제 #12
0
import lagrange
import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 3, 4])
y = np.array([1, 2, 5])

input_x = np.sort(np.random.rand(100) * 6 - 1)

ans = lagrange.lagrange(x, y, input_x)

plt.scatter(x, y)
plt.plot(input_x, ans)
plt.show()
예제 #13
0
# Lagrange interpolating polynomial test

from lagrange import lagrange
import matplotlib.pyplot as plt
import numpy as np

# Three points are sufficient to interpolate a polynomial of degree 2
x = np.array([15, 42, 30])
y = np.square(x)
X = np.linspace(0, 100, 100)
Y = lagrange(x, y, X)

# Plot the result
plt.scatter(x, y)
plt.plot(X, Y)
plt.show()