Exemple #1
0
def secondDerivative(u, dimNo, grid, *args):
    """Compute the 2nd derivative of numerical array. This implements now only the 2nd derivative over the same dimenion
    The method of taking the derivative is specified in src.config (SECONDDERMETHOD)
    NB. when requesting a shape that has more dimensions that the data, this method fails. Needs fixing (TODO)
    NB. allows for grid contractions, but only in a single direction

    Parameters:
        u (ndarray or scalar) - data to take derivative of.
                                length of the data on each axis should be either 1 or the same as the grid over that axis. Length 1 axes at the end may be omitted.
        dimNo (int or str) - number or name of dimension to take the derivative of
        grid (DataContainer) - DataContainer containing grid information
        args (ndarray/list, optional) - indices at which the derivative is requested.
                                      When omitted data is requested at the original grid.
                                      For omitting dimensions, the same rules hold as for the .v method of the DataContainer

    Returns:
        ux (ndarray) - Numerical derivative of u in dimension dimNo on indices or original grid
    """
    # find dimension name corresponding to dimNo (or vv)
    if isinstance(dimNo, int):
        dim = grid.v('grid', 'dimensions')[dimNo]
    else:  # else assume dimNo is a string with dimension name
        dim = dimNo
        dimNo = grid.v('grid', 'dimensions').index(dim)

    # take derivative along this axis, ignoring grid contraction
    der = axisSecondDerivative(u, dim, dimNo, grid, *args)

    # add effects of grid contraction
    contr = grid.v('grid', 'contraction')[:, dimNo]
    for contrDimNo, i in enumerate(contr):
        if i == 1:
            # if u has less dimensions than the grid, ignore these dimensions in the axes
            axisrequest = {}
            for j in grid.v('grid', 'dimensions')[len(u.shape):]:
                axisrequest[j] = 0
            axis = ny.dimensionalAxis(grid, contrDimNo, **axisrequest)
            # take derivative of axis
            u_i = derivative(u, contrDimNo, grid,
                             *args)  # first derivative wrt i
            u_di = derivative(derivative(u, contrDimNo, grid), dimNo, grid,
                              *args)  # mixed derivative
            u_ii = axisSecondDerivative(u,
                                        grid.v('grid',
                                               'dimensions')[contrDimNo],
                                        contrDimNo, grid,
                                        *args)  # 2nd derivative wrt i
            axis_d = axisDerivative(axis, dim, dimNo, grid, *args)
            axis_dd = axisSecondDerivative(axis, dim, dimNo, grid, *args)

            # grid contraction
            der = der - 2. * u_di * axis_d - u_ii * axis_d**2 - u_i * axis_dd  # TODO does not work yet for arrays with more dimensions than the grid

    return der
def dbeta_dE(Eimg, En):
        beamline = imagedbeamline(Eimg)
        beamline.gamma = En/emass

        def calcR11(E):
                beamline.gamma = E/emass
                return beamline.R[0, 0]

        def calcR12(E):
                beamline.gamma = E/emass
                return beamline.R[0, 1]

        R11 = beamline.R[0, 0]
        R12 = beamline.R[0, 1]
        R11p = derivative(calcR11, En)
        R12p = derivative(calcR12, En)

        print('dbeta/dE = {}'.format(R11*twiss.beta**2*R11p + R12*R12p))
def dalpha_dE(Eimg, En):
        beamline = imagedbeamline(Eimg)
        beamline.gamma = En/emass

        def calcalpha(E):
                beamline.gamma = E/emass
                return beamline.twiss_x_end.alpha

        ap = derivative(calcalpha, En, tol=1e-6)

        print('dalpha/dE = {}'.format(ap))
 def __init__(self):
     self.ps = der.derivative(date(2015,9,16),0.007,0,np.asarray(pd.read_excel(file,header=None, skiprows=10,parse_cols="B")))
     self.rs = der.derivative(date(2015,9,2),0.012,0,np.asarray(pd.read_excel(file,header=None, skiprows=10,parse_cols="C")))
     self.sc = der.derivative(date(2015,8,7),0.0035,0,np.asarray(pd.read_excel(file,header=None, skiprows=10,parse_cols="D")))
     self.lc = der.derivative(date(2015,7,20),0.0062,0,np.asarray(pd.read_excel(file,header=None, skiprows=10,parse_cols="E")))
     self.lf = der.derivative(date(2015,7,7),-0.003,0,np.asarray(pd.read_excel(file,header=None, skiprows=10,parse_cols="F")))
     self.ldf = der.derivative(date(2015,7,7),-0.0045,0.02,np.asarray(pd.read_excel(file,header=None, skiprows=10,parse_cols="G")))
 def __init__(self):
     self.ps = der.derivative(
         date(2015, 9, 16), 0.007, 0,
         np.asarray(
             pd.read_excel(file, header=None, skiprows=10, parse_cols="B")))
     self.rs = der.derivative(
         date(2015, 9, 2), 0.012, 0,
         np.asarray(
             pd.read_excel(file, header=None, skiprows=10, parse_cols="C")))
     self.sc = der.derivative(
         date(2015, 8, 7), 0.0035, 0,
         np.asarray(
             pd.read_excel(file, header=None, skiprows=10, parse_cols="D")))
     self.lc = der.derivative(
         date(2015, 7, 20), 0.0062, 0,
         np.asarray(
             pd.read_excel(file, header=None, skiprows=10, parse_cols="E")))
     self.lf = der.derivative(
         date(2015, 7, 7), -0.003, 0,
         np.asarray(
             pd.read_excel(file, header=None, skiprows=10, parse_cols="F")))
     self.ldf = der.derivative(
         date(2015, 7, 7), -0.0045, 0.02,
         np.asarray(
             pd.read_excel(file, header=None, skiprows=10, parse_cols="G")))
Exemple #6
0
def newton( f, guess, tolerance = .0000000000001 ):
	max_iterations = 10**6
	iterations = 0
	x = guess	
	while abs( f( x ) ) > tolerance :
		derivativef = derivative(f)(x)
		if derivativef == 0:
			return None
		x = x - ( f(x) / derivativef )
		iterations += 1
		if iterations > max_iterations:
			return None
	return x
Exemple #7
0
def take_derivative(u, grid, dif_type, scheme_order=1, boundary_order=2):
    const, var, order, power = dif_type
    var = 1 - var
    h = grid[var]
    der = u
    for i in range(order):
        # der = np.gradient(der, h, axis=var, edge_order=1)
        der = derivative(der,
                         h,
                         var,
                         scheme_order=scheme_order,
                         boundary_order=boundary_order)
        # der = derivative_4p(der, h, var)
    der = const * der**power
    return der
Exemple #8
0
def generate_ode_data(
    problem,
    x0,
    t,
    ode_params=None,
    noise_amplitude=0,
    noise_pdf=None,
    noise_params=None,
    noise_kind="additive",
    diff_params=None,
):
    """Generate a trajectory and estimate its derivate.

    Noise will be added as measurement noise before estimating the derivatives.

    Args:
        problem: ode generator
        x0: initial conditions
        t: timestamps of the output
        ode_params: kwargs for problem
        noise_kind: proportional or additive
        noise_amplitude: noise amplitude
        noise_pdf: function which generates noise
        noise_params: kwargs passed to noise_pdf
        derive_max_order: maximum order derivative

    Returns:
        x, dx: trajectory and derivative

    """
    dy = problem(**(ode_params or {}))
    x = scipy.integrate.odeint(dy, x0, t)

    x = add_measurement_noise(
        x,
        noise_amplitude=noise_amplitude,
        noise_pdf=noise_pdf,
        noise_params=noise_params,
        noise_kind=noise_kind,
    )
    dx = derivative(t, x, **(diff_params or {}))
    return x, dx
Exemple #9
0
    print (line)'''

import sys
sys.path.append(r'D:\Program files\JetBrains\my_module')



from math import sin, pi
from integral import Integral
from derivative import derivative

G = Integral(sin, 0, n=100)
result = G(0.5*pi)
print(result)

res=derivative(sin, pi/3)
print(res)

from deriv_central import Central

def g(x):
    return sin(x)

df=Central(g)
print(df(pi/4))





Exemple #10
0
def extrema( f, guess ):
	return roots( derivative(f), guess )
Exemple #11
0
 def test_derivative(self):
     der = derivative([2, 3, 4, 3])
     print("\nDeriviate: {}".format(der))
     self.assertEqual(der, [6, 6, 4, 0])
Exemple #12
0
from derivative import derivative
import numpy as np
import math 

def f(x):
    return math.sin(0.5*(x**(1/2)))/x

point = 1
h = 0.2
derivative(f=f, a=point, h=h)
#print()
    dalpha_dE(val, res.x[0])

for i, val in enumerate(Escan):
    beamline = imagedbeamline(val)

    def calcR11(E):
        beamline.gamma = E/emass
        return beamline.R[0, 0]

    def calcR12(E):
        beamline.gamma = E/emass
        return beamline.R[0, 1]

    R11 = beamline.R[0, 0]
    R12 = beamline.R[0, 1]
    R11p = derivative(calcR11, val)
    R12p = derivative(calcR12, val)

    Eres2[i] = val - (R11*R11p*twiss.beta**2+R12*R12p)/(R11p**2*twiss.beta**2 + R12p**2)
    print('Energy should be {}'.format(Eres2[i]))

fig = plt.figure()
plt.plot(Escan, Eres, '.-')
mt.addlabel('Pinch Energy Proportional to Imaging Energy', 'Image Energy', 'Pinch Energy')
pp.savefig(fig)
pp.close()

for i, val in enumerate(Escan):
        Eres3[i] = betafromE(20.35, val)
        Eres4[i] = alphafromE(20.35, val)