def LocBeamInt(x, z):
    alpha_1 = (x+d/2)*(np.sqrt(2/(lam*10**z)))
    alpha_2 = (x-d/2)*(np.sqrt(2/(lam*10**z)))
    s1, c1 = fresnel(alpha_1) #Fresnel integrals
    s2, c2 = fresnel(alpha_2) #Fresnel integrals
    I = 0.5*((c2-c1)**2+(s2-s1)**2)    
    return I;
def Fres_Diff(write_wavelength, slitwidth, x_pos, screen_pos):
    alpha_1 = (x_pos + slitwidth/2)*(np.sqrt(2/(write_wavelength*screen_pos)))
    alpha_2 = (x_pos - slitwidth/2)*(np.sqrt(2/(write_wavelength*screen_pos)))
    s1, c1 = fresnel(alpha_1) #Fresnel integrals
    s2, c2 = fresnel(alpha_2) #Fresnel integrals
    Intensity = 0.5*((c2-c1)**2+(s2-s1)**2)
    return Intensity
Example #3
0
def motion_CSAA(state, dt):
    '''
    Constant Steering Angle and Acceleration.

    States: [x, y, theta, v, a, c]
            [0  1    2    3  4  5]
    '''
    x, y, th, v, a, c = state

    gamma1 = (c * v * v) / (4 * a) + th
    gamma2 = c * dt * v + c * dt * dt * a - th
    eta = np.sqrt(2 * np.pi) * v * c
    zeta1 = (2 * a * dt + v) * np.sqrt(c / 2 * a * np.pi)
    zeta2 = v * np.sqrt(c / 2 * a * np.pi)
    sz1, cz1 = fresnel(zeta1)
    sz2, cz2 = fresnel(zeta2)

    nx = x + (eta * (np.cos(gamma1) * cz1 + np.sin(gamma1) * sz1 -
                     np.cos(gamma1) * cz2 - np.sin(gamma1) * sz2) +
              2 * np.sin(gamma2) * np.sqrt(a * c) +
              2 * np.sin(th) * np.sqrt(a * c)) / 4 * np.sqrt(a * c) * c
    ny = y + (eta * (-np.cos(gamma1) * sz1 + np.sin(gamma1) * cz1 -
                     np.sin(gamma1) * cz2 - np.cos(gamma1) * sz2) +
              2 * np.cos(gamma2) * np.sqrt(a * c) -
              2 * np.sin(th) * np.sqrt(a * c)) / 4 * np.sqrt(a * c) * c
    nth = wrap_angle(th - c * dt * dt * a / 2 - c * dt * v)
    nv = v + a * dt

    state = np.copy(state)
    state[:4] = (nx, ny, nth, nv)
    return state
Example #4
0
def I2(k, horn_height, eplane_effective_length, theta, phi):
    """
    Calculate the integral used for far field calculations.
    :param k: The wavenumber (rad/m).
    :param horn_height: The height of the horn (m).
    :param eplane_effective_length: The horn effective length in the E-plane (m).
    :param theta: The theta angle to the field point (rad).
    :param phi: The phi angle to the field point (rad).
    :return: The integral used for far field calculations.
    """
    # Calculate the y-component of the wavenumber
    ky = k * sin(theta) * sin(phi)

    # Calculate the arguments for the Fresnel integrals
    t1 = sqrt(1.0 / (pi * k * eplane_effective_length)) * (
        -k * horn_height / 2.0 - ky * eplane_effective_length)
    t2 = sqrt(1.0 / (pi * k * eplane_effective_length)) * (
        k * horn_height / 2.0 - ky * eplane_effective_length)

    # Calculate the Fresnel integrals
    s1, c1 = fresnel(t1)
    s2, c2 = fresnel(t2)

    return sqrt(pi * eplane_effective_length / k) * exp(1j * ky ** 2 * eplane_effective_length / (2.0 * k)) * \
           ((c2 - c1) + 1j * (s1 - s2))
Example #5
0
    def elementarykernel_fresnel(t):
        #==========================================================================
        """Calculate kernel using Fresnel integrals (fast and accurate)"""

        # Calculation using Fresnel integrals
        if complex:
            ɸ = np.outer(t, ωr)
            κ = np.lib.scimath.sqrt(6 * ɸ / π)
            S, C = fresnel(κ)
            K0 = np.exp(-1j * ɸ) * (C + 1j * S)

        else:
            ɸ = np.outer(np.abs(t), ωr)
            κ = np.lib.scimath.sqrt(6 * ɸ / π)
            S, C = fresnel(κ)
            K0 = C * np.cos(ɸ) + S * np.sin(ɸ)

        # Supress divide by 0 warning
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            K0 = K0 / κ

        # Limit of K0(t,r) as t->0
        K0[t == 0] = 1

        return K0
Example #6
0
def directivity(horn_width, horn_height, eplane_effective_length, hplane_effective_length, frequency):
    """
    Calculate the directivity for a pyramidal horn.
    :param horn_width: The width of the horn (m).
    :param horn_height: The height of the horn (m).
    :param eplane_effective_length: The horn effective length in the E-plane (m).
    :param hplane_effective_length: The horn effective length in the H-plane (m).
    :param frequency: The operating frequency (Hz).
    :return: The directivity of the pyramidal horn.
    """
    # Calculate the wavelength
    wavelength = c / frequency
    
    # Calculate the arguments for the Fresnel integrals
    u = 1.0 / sqrt(2.0) * (sqrt(wavelength * hplane_effective_length) / horn_width + 
                           horn_width / sqrt(wavelength * hplane_effective_length))

    v = 1.0 / sqrt(2.0) * (sqrt(wavelength * hplane_effective_length) / horn_width - horn_width /
                           sqrt(wavelength * hplane_effective_length))

    # Calculate the Fresnel sin and cos integrals
    Su, Cu = fresnel(u)
    Sv, Cv = fresnel(v)

    arg = horn_height / sqrt(2.0 * wavelength * eplane_effective_length)

    S2, C2 = fresnel(arg)

    S2 *= S2
    C2 *= C2

    return 8.0 * pi * eplane_effective_length * hplane_effective_length / (horn_width * horn_height) * \
           ((Cu - Cv) ** 2 + (Su - Sv) ** 2) * (C2 + S2)
Example #7
0
def fresnel_analytical_rectangle(fresnel_number=None,
                                 propagation_distance=1.140,
                                 aperture_half=1e-3,
                                 wavelength=639e-9,
                                 detector_array=None,
                                 npoints=1000):

    if fresnel_number is None:
        fresnel_number = aperture_half**2 / (wavelength * propagation_distance)

    if detector_array is None:
        if fresnel_number > 1.0:
            window_aperture_ratio = 2.0
        else:
            window_aperture_ratio = 1.0 / fresnel_number
        x = numpy.linspace(-window_aperture_ratio * aperture_half,
                           window_aperture_ratio * aperture_half, npoints)
    else:
        x = detector_array.copy()

    s_plus = numpy.sqrt(2.0 * fresnel_number) * (1.0 + x / aperture_half)
    s_minus = numpy.sqrt(2.0 * fresnel_number) * (1.0 - x / aperture_half)

    fs_plus, fc_plus = fresnel(s_plus)
    fs_minus, fc_minus = fresnel(s_minus)

    Ux = (fc_minus + fc_plus) + 1j * (fs_minus + fs_plus)
    Ux *= 1.0 / numpy.sqrt(2.0)

    # TODO note that the global phase (Goldman 4-59) is missing

    return x, Ux  # note that wavefield is being returned, not intensity!
Example #8
0
def motion_CSAA(state: np.ndarray, dt: float) -> np.ndarray:
    '''
    Constant Steering Angle and Acceleration model.

    :param state: original state in format [x, y, theta, v, a, c]
                                           [0  1    2    3  4  5]
    :param dt: time difference after last update
    :return: updated state
    '''

    x, y, th, v, a, c = state

    gamma1 = (c * v * v) / (4 * a) + th
    gamma2 = c * dt * v + c * dt * dt * a - th
    eta = np.sqrt(2 * np.pi) * v * c
    zeta1 = (2 * a * dt + v) * np.sqrt(c / 2 * a * np.pi)
    zeta2 = v * np.sqrt(c / 2 * a * np.pi)
    sz1, cz1 = fresnel(zeta1)
    sz2, cz2 = fresnel(zeta2)

    nx = x + (eta * (np.cos(gamma1) * cz1 + np.sin(gamma1) * sz1 -
                     np.cos(gamma1) * cz2 - np.sin(gamma1) * sz2) +
              2 * np.sin(gamma2) * np.sqrt(a * c) +
              2 * np.sin(th) * np.sqrt(a * c)) / 4 * np.sqrt(a * c) * c
    ny = y + (eta * (-np.cos(gamma1) * sz1 + np.sin(gamma1) * cz1 -
                     np.sin(gamma1) * cz2 - np.cos(gamma1) * sz2) +
              2 * np.cos(gamma2) * np.sqrt(a * c) -
              2 * np.sin(th) * np.sqrt(a * c)) / 4 * np.sqrt(a * c) * c
    nth = wrap_angle(th - c * dt * dt * a / 2 - c * dt * v)
    nv = v + a * dt

    state = np.copy(state)
    state[:4] = (nx, ny, nth, nv)
    return state
 def LocBeamInt(x, z, lam): # function works out beam intensity as a function of distance from slit (z) and position along axis of slit (x)
     alpha_1 = (x+slit_width/2)*(np.sqrt(2/(lam*z)))
     alpha_2 = (x-slit_width/2)*(np.sqrt(2/(lam*z)))
     s1, c1 = fresnel(alpha_1) #Fresnel integrals
     s2, c2 = fresnel(alpha_2) #Fresnel integrals
     I = 0.5*((c2-c1)**2+(s2-s1)**2)    
     return I;
Example #10
0
def directivity(guide_height, horn_width, horn_effective_length, frequency):
    """
    Calculate the directivity for the H-plane horn.
    :param guide_height: The height of the waveguide feed (m).
    :param horn_width: The width of the horn (m).
    :param horn_effective_length: The effective length of the horn (m).
    :param frequency: The operating frequency (Hz).
    :return: The directivity for the H-plane horn.
    """
    # Calculate the wavelength
    wavelength = c / frequency

    # Calculate the arguments for the Fresnel integrals
    u = 1.0 / sqrt(2.0) * (
        sqrt(wavelength * horn_effective_length) / horn_width +
        horn_width / sqrt(wavelength + horn_effective_length))

    v = 1.0 / sqrt(2.0) * (
        sqrt(wavelength * horn_effective_length) / horn_width -
        horn_width / sqrt(wavelength + horn_effective_length))

    # Calculate the Fresnel integrals
    Cu, Su = fresnel(u)
    Cv, Sv = fresnel(v)

    return 4.0 * pi * guide_height * horn_effective_length / (horn_width * wavelength) * \
           ((Cu - Cv) ** 2 + (Su - Sv) ** 2)
Example #11
0
    def calc(self, s, x0=0, y0=0, kappa0=0, theta0=0):

        # Start
        C0 = x0 + 1j * y0

        if self._gamma == 0 and kappa0 == 0:
            # Straight line
            Cs = C0 + s * np.exp(1j * theta0)

        elif self._gamma == 0 and kappa0 != 0:
            # Arc
            Cs = C0 + np.exp(1j * theta0) / kappa0 * (np.sin(kappa0 * s) + 1j *
                                                      (1 - np.cos(kappa0 * s)))

        else:
            # Fresnel integrals
            Sa, Ca = fresnel((kappa0 + self._gamma * s) /
                             np.sqrt(np.pi * np.abs(self._gamma)))
            Sb, Cb = fresnel(kappa0 / np.sqrt(np.pi * np.abs(self._gamma)))

            # Euler Spiral
            Cs1 = np.sqrt(np.pi / np.abs(self._gamma)) * np.exp(
                1j * (theta0 - kappa0**2 / 2 / self._gamma))
            Cs2 = np.sign(self._gamma) * (Ca - Cb) + 1j * Sa - 1j * Sb

            Cs = C0 + Cs1 * Cs2

        # Tangent at each point
        theta = self._gamma * s**2 / 2 + kappa0 * s + theta0

        return (Cs.real, Cs.imag, theta)
Example #12
0
def I(k, r, theta, phi, horn_effective_length, horn_height, guide_width):
    """
    Calculate the integral used in the far field calculations.
    :param k: The wavenumber (rad/m).
    :param r: The distance to the field point (m).
    :param theta: The theta angle to the field point (rad).
    :param phi: The phi angle to the field point (rad).
    :param horn_effective_length: The horn effective length (m).
    :param horn_height: The horn height (m).
    :param guide_width: The width of the waveguide feed (m).
    :return: The result of the integral for far field calculations.
    """
    # Calculate the x and y components of the wavenumber
    kx = k * sin(theta) * cos(phi)
    ky = k * sin(theta) * sin(phi)

    # Two separate terms for the Fresnel integrals
    t1 = sqrt(1.0 /
              (pi * k * horn_effective_length)) * (-k * horn_height * 0.5 -
                                                   ky * horn_effective_length)
    t2 = sqrt(1.0 /
              (pi * k * horn_effective_length)) * (k * horn_height * 0.5 -
                                                   ky * horn_effective_length)

    # Get the Fresnel sin and cos integrals
    s1, c1 = fresnel(t1)
    s2, c2 = fresnel(t2)

    index = (kx * guide_width != pi) & (kx * guide_width != -pi)
    term2 = -ones_like(kx) / pi
    term2[index] = cos(kx[index] * guide_width * 0.5) / (
        (kx[index] * guide_width * 0.5)**2 - (pi * 0.5)**2)

    return exp(1j * ky ** 2 * horn_effective_length / (2.0 * k)) * -1j * guide_width * \
           sqrt(pi * k * horn_effective_length) / (8.0 * r) * exp(-1j * k * r) * term2 * ((c2 - c1) - 1j * (s2 - s1))
Example #13
0
 def _xy(s):
     if th == 0:
         return Coord2(0.0, 0.0)
     elif s <= Ltot / 2:
         (fsin, fcos) = fresnel(s / (sq2pi * a))
         X = sq2pi * a * fcos
         Y = sq2pi * a * fsin
     else:
         (fsin, fcos) = fresnel((Ltot - s) / (sq2pi * a))
         X = (
             sq2pi
             * a
             * (
                 facos
                 + np.cos(2 * th) * (facos - fcos)
                 + np.sin(2 * th) * (fasin - fsin)
             )
         )
         Y = (
             sq2pi
             * a
             * (
                 fasin
                 - np.cos(2 * th) * (fasin - fsin)
                 + np.sin(2 * th) * (facos - fcos)
             )
         )
     return Coord2(X, Y)
Example #14
0
def fresnel_prop_square_aperture_analitical(x2, y2, aperture_diameter,
                                            wavelength, propagation_distance):

    f_n = (aperture_diameter / 2)**2 / (wavelength * propagation_distance
                                        )  # Fresnel number

    # substitutions

    big_x = x2 / numpy.sqrt(wavelength * propagation_distance)
    big_y = y2 / numpy.sqrt(wavelength * propagation_distance)
    alpha1 = -numpy.sqrt(2) * (numpy.sqrt(f_n) + big_x)
    alpha2 = numpy.sqrt(2) * (numpy.sqrt(f_n) - big_x)
    beta1 = -numpy.sqrt(2) * (numpy.sqrt(f_n) + big_y)
    beta2 = numpy.sqrt(2) * (numpy.sqrt(f_n) - big_y)

    # Fresnel sine and cosine integrals
    cos_sin_a1 = fresnel(alpha1)
    cos_sin_a2 = fresnel(alpha2)
    cos_sin_b1 = fresnel(beta1)
    cos_sin_b2 = fresnel(beta2)

    # observation-plane field
    U = 1 / (2 * 1.0j) * ((cos_sin_a2[0] - cos_sin_a1[0]) + 1.0j *
                          (cos_sin_a2[1] - cos_sin_a1[1])) * (
                              (cos_sin_b2[0] - cos_sin_b1[0]) + 1.0j *
                              (cos_sin_b2[1] - cos_sin_b1[1]))

    return U
Example #15
0
    def __euler_function(self, t):
        # input (t) goes from 0->1
        # Returns an (x,y) tuple
        if t > 1.0 or t < 0.0:
            raise ValueError(
                "Warning! A value was given to __euler_function not between 0 and 1"
            )

        end_t = self.t  # (end-point)

        if abs(self.turnby) <= np.pi / 2.0:
            # Obtuse bend
            if t < 0.5:
                y, x = fresnel(2 * t * end_t)
                return x * self.scale_factor, self.sign * y * self.scale_factor
            else:
                y, x = fresnel(2 * (1 - t) * end_t)
                x, y = (
                    x * np.cos(-self.sign * self.turnby)
                    - y * np.sin(-self.sign * self.turnby),
                    x * np.sin(-self.sign * self.turnby)
                    + y * np.cos(-self.sign * self.turnby),
                )
                return (
                    self.output_port[0] - x * self.scale_factor,
                    self.output_port[1] + self.sign * y * self.scale_factor,
                )

        else:
            # Acute bend
            if t < 0.3:
                # First section of Euler bend
                y, x = fresnel((t / 0.3) * end_t)
                return x * self.scale_factor, self.sign * y * self.scale_factor
            elif t < 0.7:
                t0 = (t - 0.3) / 0.4
                return (
                    self.circle_center[0]
                    + self.wgt.bend_radius
                    * np.cos(
                        (-self.sign * np.pi / 4) + self.sign * self.circle_angle * t0
                    ),
                    self.sign * self.circle_center[1]
                    + self.wgt.bend_radius
                    * np.sin(
                        (-self.sign * np.pi / 4) + self.sign * self.circle_angle * t0
                    ),
                )
            else:
                y, x = fresnel(((1 - t) / 0.3) * end_t)
                x, y = (
                    x * np.cos(-self.sign * self.turnby)
                    - y * np.sin(-self.sign * self.turnby),
                    x * np.sin(-self.sign * self.turnby)
                    + y * np.cos(-self.sign * self.turnby),
                )
                return (
                    self.output_port[0] - x * self.scale_factor,
                    self.output_port[1] + self.sign * y * self.scale_factor,
                )
Example #16
0
def transfer_function(s, u):
    a = u[0]
    b = u[1]
    t = u[2]

    v = s[3]
    w = s[4]
    theta = s[2]

    s_n = np.array(s, copy=True)

    # The easy ones
    dz = 0.5*b*t*t + w*t
    dv = a*t
    dw = b*t

    # b = 0 and c = 0 case -> just linear acceleration
    if abs(b) < 0.001 and abs(w) < 0.001:
        l = 0.5*a*t*t + v*t
        dx = math.cos(theta) * l
        dy = math.sin(theta) * l
    # b = 0 case -> formula singularity covered
    elif abs(b) < 0.001:
        dx = a * (math.cos(w * t + theta) - math.cos(theta)) / (theta * theta) + ((a * t + v) * math.sin(w * t + theta) - v * math.sin(theta)) / w
        dy = a * (math.sin(w * t + theta) - math.sin(theta)) / (theta * theta) - ((a * t + v) * math.cos(w * t + theta) - v * math.cos(theta)) / w
    else:
        flipped = False
        if b < 0:
            b = -b
            w = -w
            flipped = True
        sb = math.sqrt(b)
        pb15 = math.pow(b, 1.5)
        gamma = math.cos(0.5 * w * w / b - theta)
        sigma = math.sin(0.5 * w * w / b - theta)
        SPI = math.pow(math.pi, 0.5)

        s1, c1 = special.fresnel((w + b*t) / (sb*SPI))
        s0, c0 = special.fresnel(w / (sb*SPI))
        S = s1 - s0
        C = c1 - c0

        dx = SPI * (b * v - a * w) * (sigma * S + gamma * C) / pb15 + (a / b) * (math.sin(0.5 * b * t * t + w * t + theta) - math.sin(theta))
        dy = SPI * (b * v - a * w) * (gamma * S - sigma * C) / pb15 - (a / b) * (math.cos(0.5 * b * t * t + w * t + theta) - math.cos(theta))

        if flipped:
            c2d = math.cos(2 * theta)
            s2d = math.sin(2 * theta)
            dxt = c2d * dx + s2d * dy
            dy = s2d * dx - c2d * dy
            dx = dxt

    s_n[0] += dx
    s_n[1] += dy
    s_n[2] += dz
    s_n[3] += dv
    s_n[4] += dw

    return s_n
Example #17
0
def Jacobian(s, u):
    a = u[0]
    b = u[1]
    t = u[2]

    x = s[0]
    y = s[1]
    theta = s[2]
    v = s[3]
    w = s[4]

    # The easy ones
    dxdt = (a*t + v) * math.cos(0.5*b*t*t + w*t)
    dydt = (a*t + v) * math.sin(0.5*b*t*t + w*t)
    dzda = 0.0
    dzdb = 0.5*t*t
    dzdt = b*t + w
    dvda = t
    dvdb = 0.0
    dvdt = a
    dwda = 0.0
    dwdb = t
    dwdt = b

    # b = 0 and w = 0 -> linear acceleration
    if abs(b) < 0.00001 and abs(w) < 0.00001:
        dxda = 0.5 * t * t
        dyda = 0.0
        # Singularity at b = 0
        dxdb = 0.0
        dydb = 1.0
    # b = 0
    elif abs(b) < 0.00001:
        dxda = (w*t*math.sin(w*t) + math.cos(w*t) - 1) / (w*w)
        dyda = (math.sin(w*t) - w*t*math.cos(w*t)) / (w*w)
        # Singularity at b = 0
        dxdb = -math.sin(w*t)
        dydb = math.cos(w*t)
    else:
        sgn = 1.0
        if b < 0.0:
            b = -b
            w = -w
            sgn = -1.0

        sb = math.sqrt(b)
        pb15 = pow(b, 1.5)
        pb25 = pow(b, 2.5)
        pb35 = pow(b, 3.5)
        gamma = math.cos(0.5*w*w/b)
        sigma = math.sin(0.5*w*w/b)
        kappa = math.cos(0.5*t*t*b + w*t)
        zeta = math.sin(0.5*t*t*b + w*t)
        SPI = math.pow(math.pi, 0.5)
        s1,c1 = special.fresnel((w + b*t)/(sb*SPI))
        s0,c0 = special.fresnel(w/(sb*SPI))
        c = c1 - c0
        s = s1 - s0
        dsdb = math.sin((b*t+w)*(b*t+w)/(2.0*b)) * ()
Example #18
0
 def f(theta):
     S_t, C_t = fresnel(arclength(theta))
     S_at, C_at = fresnel(arclength(alpha - theta))
     result = math.sqrt(theta) * (C_t * math.sin(alpha) - S_t *
                                  (k + math.cos(alpha)))
     result += math.sqrt(alpha - theta) * (S_at *
                                           (1 + k * math.cos(alpha)) -
                                           k * C_at * math.sin(alpha))
     return result
Example #19
0
def compute_fresnel_at_polar(rho, phi, phi0, wavelength):
    k = 2 * np.pi / wavelength  # wave number
    # Eq (3.4) Arguments of Fresnel Integrals are multiplied by sqrt(2 / pi) due to different definition of fresnels / c in matlab, use substitution to change between definitions...
    fresnels, fresnelc = fresnel(
        sqrt(2.0 / pi) * sqrt(2 * k * rho) * cos((phi - phi0) / 2.0))
    phiplus = (1 - 1j) / 2.0 + fresnelc - 1j * fresnels
    fresnels, fresnelc = fresnel(
        sqrt(2.0 / pi) * sqrt(2 * k * rho) * cos((phi + phi0) / 2.0))
    phiminus = (1 - 1j) / 2.0 + fresnelc - 1j * fresnels

    return phiplus, phiminus
Example #20
0
    def _calc_fresnel_integral(self, s, kappa0, theta0, C0):
        Sa, Ca = special.fresnel(
            (kappa0 + self._gamma * s) / np.sqrt(np.pi * np.abs(self._gamma)))
        Sb, Cb = special.fresnel(kappa0 / np.sqrt(np.pi * np.abs(self._gamma)))

        # Euler Spiral
        Cs1 = np.sqrt(np.pi / np.abs(self._gamma)) * np.exp(
            1j * (theta0 - kappa0**2 / 2 / self._gamma))
        Cs2 = np.sign(self._gamma) * (Ca - Cb) + 1j * Sa - 1j * Sb

        Cs = C0 + Cs1 * Cs2

        return Cs
Example #21
0
def spiralInterpolation(resolution, s, x, y, hdg, length, curvStart, curvEnd):
    points = np.zeros((int(length/resolution), 1))
    points = [i*resolution for i in range(len(points))]
    xx = np.zeros_like(points)
    yy = np.zeros_like(points)
    hh = np.zeros_like(points)
    if curvStart == 0 and curvEnd > 0:
        print("Case 1: curvStart == 0 and curvEnd > 0")
        radius = np.abs(1/curvEnd)
        A_sq = radius*length
        ss, cc = fresnel(np.square(points)/(2*A_sq*np.sqrt(np.pi/2)))
        xx = points*cc
        yy = points*ss
        hh = np.square(points)*2*radius*length
        xx, yy, hh = rotate(xx, yy, hh, hdg)
        xx, yy = translate(xx, yy, x, y)
        xx = np.insert(xx, 0, x, axis=0)
        yy = np.insert(yy, 0, y, axis=0)
        hh = np.insert(hh, 0, hdg, axis=0)

    elif curvStart == 0 and curvEnd < 0:
        print("Case 2: curvStart == 0 and curvEnd < 0")
        radius = np.abs(1/curvEnd)
        A_sq = radius*length
        ss, cc = fresnel(np.square(points)/(2*A_sq*np.sqrt(np.pi/2)))
        xx = points*cc
        yy = points*ss*-1
        hh = np.square(points)*2*radius*length
        xx, yy, hh = rotate(xx, yy, hh, hdg)
        xx, yy = translate(xx, yy, x, y)
        xx = np.insert(xx, 0, x, axis=0)
        yy = np.insert(yy, 0, y, axis=0)
        hh = np.insert(hh, 0, hdg, axis=0)

    elif curvEnd == 0 and curvStart > 0:
        print("Case 3: curvEnd == 0 and curvStart > 0")

    elif curvEnd == 0 and curvStart < 0:
        print("Case 4: curvEnd == 0 and curvStart < 0")

    else:
        print("The curvature parameters differ from the 4 predefined cases. Change curvStart and/or curvEnd")

    n_stations = int(length/resolution) + 1
    stations = np.zeros((n_stations, 3))
    for i in range(len(xx)):
        stations[i][0] = xx[i]
        stations[i][1] = yy[i]
        stations[i][2] = hh[i]

    return stations
    def XY(s):
        if th == 0:
            return np.array((0.0, 0.0))
        elif s <= Ltot / 2:
            (fsin, fcos) = fresnel(s / (sq2pi * a))
            X = sq2pi * a * fcos
            Y = sq2pi * a * fsin
        else:
            (fsin, fcos) = fresnel((Ltot - s) / (sq2pi * a))
            X = sq2pi * a * (facos + np.cos(2 * th) *
                             (facos - fcos) + np.sin(2 * th) * (fasin - fsin))
            Y = sq2pi * a * (fasin - np.cos(2 * th) *
                             (fasin - fsin) + np.sin(2 * th) * (facos - fcos))

        return np.array((X, Y))
Example #23
0
    def test_spiral(self):
        '''
		spiral test compares outcome of wrapped odrSpiral implementation with scipy fresnel calculation
		'''

        # spiral using scipy
        t = np.linspace(-7, 7, 250)
        y, x = fresnel(t)

        # spiral using odrSpiral
        x_odr = []
        y_odr = []
        for t_i in t:
            x_odr.append(fresnel_cos(t_i))
            y_odr.append(fresnel_sin(t_i))

        #plt.plot(x, y)
        #plt.plot(x_odr, y_odr, 'g')
        #plt.axes().set_aspect("equal")
        #plt.show()

        x_odr_np = np.asarray(x_odr)
        y_odr_np = np.asarray(y_odr)

        assert (np.allclose(x, x_odr_np) == 1)
        assert (np.allclose(y, y_odr_np) == 1)
Example #24
0
def PELDOR_matrix_kernel(r_usr, Pr_usr, time, moddepth):
    """"

    in:  time: (1xn) time vector in ns units
         r_usr: (1xm) user defined distance vector
         Pr_usr: (1xm) distance distribution vector

    out: signal: (1xn) PELDOR signal, normalized to the modulation depth

    The function takes a user defined ditance distribution (Pr_user) to
    create a corresponding PELDOR time trace.
    """
    time = time / 1000.0
    kernel = np.zeros((len(time), len(Pr_usr)))
    indext0 = np.argwhere(np.abs(time) < 1e-6)[0][0]
    for i in range(0, len(r_usr)):
        w = (327.0 / (np.power(r_usr[i], 3)))
        z = np.sqrt((6 * w * np.absolute(time)) / np.pi)
        tmpfresnel = fresnel(z)
        kernel[indext0, :] = 1.0
        z[indext0] = 1
        kernel[:, i] = ((np.cos(w * np.absolute(time)) / z) * tmpfresnel[1] +
                        (np.sin(w * np.absolute(time)) / z) * tmpfresnel[0])
    kernel[indext0][:] = 1.0
    signal = kernel @ Pr_usr
    return (moddepth * (signal / max(signal)))
Example #25
0
def fresnel_prop_square_ap(x2, y2, D1, wvl, Dz):
    N_F = (D1/2)**2/(wvl*Dz)
    bigX = x2/np.sqrt(wvl*Dz)
    bigY = y2/np.sqrt(wvl*Dz)
    alpha1 = -np.sqrt(2)*(np.sqrt(N_F)+bigX)
    alpha2 = np.sqrt(2)*(np.sqrt(N_F)-bigX)
    beta1 = -np.sqrt(2)*(np.sqrt(N_F)+bigY)
    beta2 = np.sqrt(2)*(np.sqrt(N_F)-bigY)

    sa1, ca1 = fresnel(alpha1)
    sa2, ca2 = fresnel(alpha2)
    sb1, cb1 = fresnel(beta1)
    sb2, cb2 = fresnel(beta2)

    U = 1/(2j)*((ca2-ca1)+1j*(sa2-sa1))*((cb2-cb1)+1j*(sb2-sb1))
    return U
def EulerEndPt(start_point=(0.0, 0.0),
               radius=10.0,
               input_angle=0.0,
               clockwise=False,
               angle_amount=np.pi / 2.):
    """Gives the end point of a simple Euler bend"""

    if clockwise:
        eth = (-angle_amount) % (2 * np.pi)
    else:
        eth = angle_amount % (2 * np.pi)

    th = eth / 2.0
    R = radius
    # clockwise = bool(angle_amount < 0)

    (fsin, fcos) = fresnel(np.sqrt(2 * th / np.pi))

    a = 2 * np.sqrt(2 * np.pi * th) * (np.cos(th) * fcos + np.sin(th) * fsin)
    r = a * R
    X = r * np.cos(th)
    Y = r * np.sin(th)

    if clockwise:
        Y *= -1

    pt = np.array((X, Y)) + np.array(start_point)
    pt = rotate(point=pt, angle=input_angle, origin=start_point)

    return pt
def fp(x):
    #   real, dimension(dimh) :: x
    #   real, dimension(dimh) :: rx
    rx = np.sqrt(x * 2 / np.pi)
    s_fresnel, c_fresnel = sp.fresnel(rx)
    return - 2 * 1j * np.sqrt(x) * np.exp(-1j * x) * np.sqrt(np.pi / 2.) * \
            (.5 - c_fresnel + 1j * (.5 - s_fresnel))
Example #28
0
def deer_ft(d, t, lambda_v=1.0, D_dip=2 * np.pi * 52.04 * 10**-3):
    """
    F_v/mu = C_F(x) cos(pi/6x^2) + S_F(x) sine(pi/6x^2)
    sin_f(x) = int_0^x sin(pi/2 t^2)
    cos_f(x) = int_o^x cos(pi/2 t^2)
    with x = [6 D_dip t / pi r^3]^0.5 and D_dip= 2pi 52.04 MHz nm^3

    Parameters
    -----------
    d: array
        Spin-spin distance [nm] for N structures
    t: array
        Time points [ns], M time points to be calculated
    D_dip: float
        2 pi 52.04 MHz nm^3 = 2 pi 52.04/1000 nm^3/ns
    lambda_v: float
        Modulation depth

    Returns
    -------
    vt: array
        DEER/PELDOR time traces for each of the N structures for M time points (NxM)
    """
    x = (6 * D_dip * t / (np.pi * d**3))**0.5

    # SciPy follows convention from Abramowitz and Stergun.
    # https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.fresnel.html#s

    sin_f, cos_f = fresnel(x)
    F_vmu = (cos_f * np.cos(np.pi / 6. * x**2) +
             sin_f * np.sin(np.pi / 6. * x**2)) / x

    return (1. - lambda_v) + lambda_v * F_vmu
Example #29
0
def FreF2(x):
    """ F function using numpy fresnel function

    Parameters
    ----------
    Not working for large argument

    """
    y = np.zeros(x.shape, dtype=complex)
    u1 = np.where(x > 5)[0]
    u2 = np.where(x <= 5)[0]
    xu1 = x[u1]
    xu2 = x[u2]
    x2 = xu1 * xu1
    x3 = x2 * xu1
    x4 = x3 * xu1
    w1 = 1 - 0.75 / x2 + 4.6875 / x4 + 1j * (0.5 / xu1 - 1.875 / x3)
    cst = np.sqrt(np.pi / 2.)
    sF, cF = sps.fresnel(np.sqrt(xu2 / cst))
    Fc = (0.5 - cF) * cst
    Fs = (0.5 - sF) * cst
    modx = np.mod(xu2, 2 * np.pi)
    expjx = np.exp(1j * modx)
    w2 = 2 * 1j * np.sqrt(xu2) * expjx * (Fc - 1j * Fs)
    y[u1] = w1
    y[u2] = w2
    return (y)
Example #30
0
def EffectiveDeformabilityFromDynamicalTides(orbital_freq, omega_fmode,
                                             ell_mode, q):
    """arxiv:1608.01907, eqn 6.51

   Inputs:
     orbital_freq -- orbital frequency of the binary
     omega_fmode  -- f-mode dimensionless angular frequency of the ell-polar
                     mode of the deformed object
     ell_mode     -- ell-polar deformability (2 = quadrupolar; 3 = octopolar)
     q            -- mass ratio
   Outputs:
     The effective amplification of the ell-polar tidal deformability as a
     function of the oribital frequency """

    if (ell_mode not in [2, 3]):
        raise ValueError(
            "ERROR: 'ell_mode' only implemented for ell=2 or ell=3!")

    # If the input to the universal relations is too small (lambda2<1), then the
    #   fits can return unphysical negative resonance frequencies, in such cases
    #   just assume there is no significant resonance
    if (omega_fmode <= 0):
        return np.ones(len(orbital_freq))

    # resonanace => freq_ratio == 1
    freq_ratio = omega_fmode / ell_mode / orbital_freq

    # Intermediate values
    # Because it only matters what the symmetric mass ratio is, XA*XB, it doesn't
    #   matter whether the input is q or 1/q
    X1 = q / (q + 1.)
    X2 = 1. - X1
    epsilon = 256. / 5. * X1 * X2 * pow(omega_fmode / ell_mode, 5. / 3.)
    t_hat = 8. / 5. / np.sqrt(epsilon) * (1 - pow(freq_ratio, 5. / 3.))
    omega_prime = 3. / 8.

    # Fresnel integral values
    ssa, csa = fresnel(t_hat * np.sqrt(2 * omega_prime / np.pi))

    betaDTOverA = (
        pow(omega_fmode, 2) /
        (pow(omega_fmode, 2) - pow(ell_mode * orbital_freq, 2)) +
        pow(freq_ratio, 2) / 2. / np.sqrt(epsilon) / t_hat / omega_prime +
        pow(freq_ratio, 2) / np.sqrt(epsilon) *
        np.sqrt(np.pi / 8. / omega_prime) *
        (np.cos(omega_prime * t_hat * t_hat) *
         (1 + 2. * ssa) - np.sin(omega_prime * t_hat * t_hat) *
         (1 + 2. * csa)))
    # When 'orbital_freq' is close enough to 0, this formula seems to be
    #   numerically unstable though the asympotic limit should be 1. So when small
    #   enough, just set it to that value
    # NOTE: this cutoff value should match value used in
    #   EffectiveDissipativeDynamicalTides
    omega_cutoff = 5.e-5
    betaDTOverA[abs(orbital_freq) <= omega_cutoff] = 1.

    if ell_mode == 2:
        return (1. + 3. * betaDTOverA) / 4.
    else:
        return (3. + 5. * betaDTOverA) / 8.
Example #31
0
def FreF2(x):
    """ F function using numpy fresnel function

    Parameters
    ----------
    Not working for large argument

    """
    y     = np.zeros(x.shape,dtype=complex)
    u1    = np.where(x>5)[0]
    u2    = np.where(x<=5)[0]
    xu1   = x[u1]
    xu2   = x[u2]
    x2    = xu1*xu1
    x3    = x2*xu1
    x4    = x3*xu1
    w1    = 1-0.75/x2+4.6875/x4 + 1j*( 0.5/xu1 -1.875/x3)
    cst   = np.sqrt(np.pi/2.)
    sF,cF = sps.fresnel(np.sqrt(xu2/cst))
    Fc    = (0.5-cF)*cst
    Fs    = (0.5-sF)*cst
    modx  = np.mod(xu2,2*np.pi)
    expjx = np.exp(1j*modx)
    w2    = 2*1j*np.sqrt(xu2)*expjx*(Fc-1j*Fs)
    y[u1] = w1
    y[u2] = w2
    return(y)
Example #32
0
    def get_pose(self, length):
        # This implements:
        # dx = http://www.wolframalpha.com/input/?i=integral+of+cos%28+w+*+0.5+*+t%5E2+%2B+q*t+%2B+theta+%29+dt+from+0+to+x
        # dy =
        time = length

        omega0 = self._start[3]
        theta0 = self._start[2]

        omega = omega0 + self._w * time
        theta = theta0 + self._w * time * time / 2 + omega0 * time

        w = self._w

        f1 = omega0 / cmath.sqrt(math.pi * w)
        S1, C1 = fresnel(f1)

        f2 = (omega0 + w * time) / cmath.sqrt(math.pi * w)
        S2, C2 = fresnel(f2)

        pi_w = cmath.sqrt(math.pi / self._w)

        t0 = (omega0 * omega0 / (2 * self._w)) - theta0

        dx = pi_w * (math.cos(t0) * (C2 - C1) + math.sin(t0) * (S2 - S1))
        dy = pi_w * (math.sin(t0) * (C1 - C2) + math.cos(t0) * (S2 - S1))
        imag = False
        if dx.imag != 0:
            print "WARNING: imaginary result for dx:", dx
            imag = True
        if dy.imag != 0:
            print "WARNING: imaginary result for dy:", dy
            imag = True
        if imag:
            print "  With w", w, ", length", self._length, "at", length
        dx = dx.real
        dy = dy.real

        # not quite sure why... but this works
        if w < 0:
            dx = -dx
            dy = -dy

        x = self._start[0] + dx
        y = self._start[1] + dy

        return (x, y, theta, omega)
Example #33
0
    def get_pose(self, length):
        # This implements:
        # dx = http://www.wolframalpha.com/input/?i=integral+of+cos%28+w+*+0.5+*+t%5E2+%2B+q*t+%2B+theta+%29+dt+from+0+to+x
        # dy =
        time = length

        omega0 = self._start[3]
        theta0 = self._start[2]

        omega = omega0 + self._w * time
        theta = theta0 + self._w * time * time / 2 + omega0 * time

        w = self._w

        f1 = omega0 / cmath.sqrt(math.pi * w)
        S1, C1 = fresnel(f1)

        f2 = (omega0 + w * time) / cmath.sqrt(math.pi * w)
        S2, C2 = fresnel(f2)

        pi_w = cmath.sqrt(math.pi / self._w)

        t0 = (omega0 * omega0 / (2 * self._w)) - theta0

        dx = pi_w * (math.cos(t0) * (C2 - C1) + math.sin(t0) * (S2 - S1))
        dy = pi_w * (math.sin(t0) * (C1 - C2) + math.cos(t0) * (S2 - S1))
        imag = False
        if dx.imag != 0:
            print "WARNING: imaginary result for dx:", dx
            imag = True
        if dy.imag != 0:
            print "WARNING: imaginary result for dy:", dy
            imag = True
        if imag:
            print "  With w", w, ", length", self._length, "at", length
        dx = dx.real
        dy = dy.real

        # not quite sure why... but this works
        if w < 0:
            dx = -dx
            dy = -dy

        x = self._start[0] + dx
        y = self._start[1] + dy

        return (x, y, theta, omega)
Example #34
0
def eulerBend(radius, theta, pts):
    length = 2 * radius * theta

    a = 1 / np.sqrt(2 * radius * length)
    s = np.linspace(0, length, pts)
    tprime = s * a * np.sqrt(2 / np.pi)
    y, x = fresnel(tprime)
    return (1 / a) * x, (1 / a) * y
 def test_fresnel_sin_small(self, dtype):
   x = np.random.uniform(0., 1., size=int(1e4)).astype(dtype)
   try:
     from scipy import special  # pylint: disable=g-import-not-at-top
     self.assertAllClose(
         special.fresnel(x)[0], self.evaluate(special_math_ops.fresnel_sin(x)))
   except ImportError as e:
     tf_logging.warn('Cannot test special functions: %s' % str(e))
Example #36
0
 def fresnelc(x):
     return sc.fresnel(x)[1]
Example #37
0
 def fresnels(x):
     return sc.fresnel(x)[0]
Example #38
0
def calc_resonant_pitchangle_change(crossing_df, L_target):

    # Start timer
    tstart = time.time()
    # # Generate energy and velocity arrays
    # E_tot_arr = pow(10,sc.E_EXP_BOT + sc.DE_EXP*np.arange(0,sc.NUM_E))
    # v_tot_arr = sc.C*np.sqrt(1 - pow(sc.E_EL/(sc.E_EL + E_tot_arr),2))


    L = L_target

    epsm = (1.0/L)*(sc.R_E + sc.H_IONO)/sc.R_E
    alpha_eq = np.arcsin(np.sqrt( pow(epsm, 3)/np.sqrt(1 + 3*(1 - epsm))  ))


    # Gen EA array (maybe pass this as an arg)
    EA_array = gen_EA_array(L_target)

    # Initialize alpha array

    DA_array_N = np.zeros((sc.NUM_E, sc.NUM_STEPS))
    DA_array_S = np.zeros((sc.NUM_E, sc.NUM_STEPS))


    tstop = time.time()

    # Loop through EA segments:
    #for EA_ind, EA_row in EA_array.iterrows():
    for EA_ind in np.unique(crossing_df['EA_index']):   
    # For each EA segment, CALCULATE:
    #     - wh
    #     - dwh/ds
    #     - flight-time constant
    #     - alpha_lc


        lat = EA_array['lam'][EA_ind]
        print 'EA segment at latitude = ',lat

        slat = np.sin(lat*sc.D2R)
        clat = np.cos(lat*sc.D2R)
        slat_term = np.sqrt(1 + 3*slat*slat)

        # Lower hybrid frequency
        wh = (sc.Q_EL*sc.B0/sc.M_EL)*(1.0/pow(L,3))*slat_term/pow(clat,6)
        #wh = (2*np.pi*880000) / (pow(L,3)*slat_term/pow(clat,6))       # Jacob used a hard coded value for qB/m
        dwh_ds = (3.0*wh/(L*sc.R_E)) *(slat/slat_term) * (1.0/(slat_term*slat_term) + 2.0/(clat*clat))

        # flight time constants (divide by velocity to get time to ionosphere, in seconds)
        ftc_N, ftc_S = get_flight_time_constant(L, lat, alpha_eq)

        # Local loss cone angle
        alpha_lc = np.arcsin(np.sqrt(slat_term/pow(clat,6) )*np.sin(alpha_eq))
        salph = np.sin(alpha_lc)
        calph = np.cos(alpha_lc)

        ds = L*sc.R_E*slat_term*clat*sc.EAIncr*np.pi/180.0
        dv_para_ds = -0.5*(salph*salph/(calph*wh))*dwh_ds


        # # Sometimes Python is pretty and readable, but now is not one of those times
        # for cell_ind, cells in crossing_df[crossing_df['EA_index'] == EA_ind].iterrows():
        #     print np.shape(cell)

        # Mask out just the entries which cross the current EA segment:
        cells = crossing_df[crossing_df['EA_index'] == EA_ind]
        #print cells
        for ir, c in cells.iterrows():
            #print c


            # where you left off: time and frequency (line 1800)
            t = c.tg + sc.T_STEP/2.0
            f = c.frequency + sc.F_STEP/2.0
            # Jacob divides by num_rays too -- since he stores total power in each cell. Average?
            # Do we need to do that here? I'm not doing that right now.
            pwr = c.power/(sc.T_STEP*EA_array['EA_length'][EA_ind])      
            # pwr = c.power/sc.T_STEP
            psi = c.psi*sc.D2R

            # print "EA_length: ",EA_array['EA_length'][EA_ind]
            # print "Pwr: ",pwr       
            # print "DT: ",sc.DT
            #print pwr

            # Maybe threshold power here?

            # Misc. parameters and trig
            mu = c.mu
            stixP = c.stixP
            stixR = c.stixR
            stixL = c.stixL

            spsi = np.sin(psi)
            cpsi = np.cos(psi)
            spsi_sq = spsi*spsi
            cpsi_sq = cpsi*cpsi
            n_x  = mu*abs(spsi)
            n_z  = mu*cpsi
            mu_sq = mu*mu
            w = 2.0 * np.pi * f
            k = w*mu/sc.C
            kx = w*n_x/sc.C
            kz = w*n_z/sc.C
            Y = wh / w

            stixS = (stixR + stixL)/2.0
            stixD = (stixR - stixL)/2.0
            stixA = stixS + (stixP-stixS)*cpsi_sq
            stixB = stixP*stixS + stixR*stixL + (stixP*stixS - stixR*stixL)*cpsi_sq
            stixX = stixP/(stixP - mu_sq*spsi_sq)
          
            rho1=((mu_sq-stixS)*mu_sq*spsi*cpsi)/(stixD*(mu_sq*spsi_sq-stixP))
            rho2 = (mu_sq - stixS) / stixD

            #print num
            Byw_sq = ( (2.0*sc.MU0/sc.C) * (pwr*stixX*stixX*rho2*rho2*mu*abs(cpsi)) /
                     np.sqrt( pow((np.tan(psi)-rho1*rho2*stixX),2) + pow((1+rho2*rho2*stixX),2)) )


            # print ("t: %g, f: %g, pwr: %g, psi: %g\nmu: %g, stixP: %g, stixR: %g, stixL: %g Byw_sq: %g"%(t,f,pwr,psi,mu, stixP, stixR, stixL, Byw_sq))
            # RMS wave components
            Byw = np.sqrt(Byw_sq);
            Exw = abs(sc.C*Byw * (stixP - n_x*n_x)/(stixP*n_z))
            Eyw = abs(Exw * stixD/(stixS-mu_sq))
            Ezw = abs(Exw *n_x*n_z / (n_x*n_x - stixP))
            Bxw = abs((Exw *stixD*n_z/sc.C)/ (stixS - mu_sq))
            Bzw = abs((Exw *stixD *n_x) /(sc.C*(stixX - mu_sq)));

            # Oblique integration quantities
            R1 = (Exw + Eyw)/(Bxw+Byw)
            R2 = (Exw - Eyw)/(Bxw-Byw)
            w1 = (sc.Q_EL/(2*sc.M_EL))*(Bxw+Byw)
            w2 = (sc.Q_EL/(2*sc.M_EL))*(Bxw-Byw)
            alpha1 = w2/w1
          

            # Loop at line 1897 -- MRES loop
            # Since we're trying to keep it vectorized:
            # target dimensions are num(cell rows) rows x num(mres) columns.
            # (Sometimes Python is beautiful, but now is not one of those times)
            #  --> Note to future editors: the (vec)[:,np.newaxis] command is similar to repmat or tile:
            #  It will tile the vector along the new axis, with length dictated by whatever operation 
            #  follows it. In Python lingo this is "broadcasting"

            # Resonant modes to sum over: Integers, positive and negative            
            for mres in np.linspace(-5,5,11):

                # Parallel resonance velocity V_z^res  (pg 5 of Bortnik et al)
                t1 = w*w*kz*kz
                t2 = pow(mres*wh, 2)-(w*w)
                t3 = kz*kz + pow((mres*wh),2)/(pow(sc.C*np.cos(alpha_lc),2))
                

                #print np.diff(t3[0,:])
                if mres==0:
                    direction = -1.0*np.sign(kz)
                else:
                    direction = np.sign(kz)*np.sign(mres)

                v_para_res = ( direction*np.sqrt(t1 + t2*t3) - w*kz) / t3

                # # Getting some obnoxious numerical stuff in the case of m=0:
                # if mres==0:
                #     v_para_res = (w/kz)
                # else: 
                #     v_tot_res = v_para_res / np.cos(alpha_lc)

                v_tot_res = v_para_res / np.cos(alpha_lc)
                E_res = sc.E_EL*(1.0/np.sqrt( 1-(v_tot_res*v_tot_res/(sc.C*sc.C)) ) - 1 )

                # Start and end indices in the energy array (+-20% energy band)
                e_starti = np.floor((np.log10(E_res)-sc.E_EXP_BOT-sc.E_BANDWIDTH)/sc.DE_EXP)
                e_endi   = np.ceil(( np.log10(E_res)-sc.E_EXP_BOT+sc.E_BANDWIDTH)/sc.DE_EXP)


                # Threshold to range of actual indexes (some energies may be outside our target range)
                e_starti = np.clip(e_starti,0,sc.NUM_E)
                e_endi   = np.clip(e_endi,  0,sc.NUM_E)

               

                # energy bins to calculate at:
                evec_inds = np.arange(e_starti,e_endi,dtype=int)

                v_tot = direction*sc.v_tot_arr[evec_inds]
                v_para = v_tot*calph
                v_perp = abs(v_tot*salph)

                # Relativistic factor
                gamma = 1.0/np.sqrt(1.0 - pow(v_tot/sc.C, 2))

                alpha2 = sc.Q_EL*Ezw /(sc.M_EL*gamma*w1*v_perp)
                
                beta = kx*v_perp/wh

                wtau_sq = (pow((-1),(mres-1)) * w1/gamma * 
                            ( jn( (mres-1), beta ) - 
                              alpha1*jn( (mres+1) , beta ) +
                              gamma*alpha2*jn( mres , beta ) ))

                T1 = -wtau_sq*(1 + calph*calph/(mres*Y - 1))

                # Analytical evaluation! (Line 1938)
                if (abs(lat) < 1e-3):        

                    eta_dot = mres*wh/gamma - w - kz*v_para
                    dalpha_eq = np.zeros_like(eta_dot)
                    
                    eta_mask = eta_dot < 10
                    dalpha_eq[eta_mask]  = abs(T1[eta_mask] /v_para[eta_mask])*ds/np.sqrt(2)
                    dalpha_eq[~eta_mask] = abs(T1[~eta_mask]/eta_dot[~eta_mask])*np.sqrt(1-np.cos(ds*eta_dot[~eta_mask]/v_para[~eta_mask]))

                else:
                    v_para_star = v_para - dv_para_ds*ds/2.0
                    v_para_star_sq = v_para_star*v_para_star

                    AA =( (mres/(2.0*v_para_star*gamma))*dwh_ds* 
                          (1 + ds/(2.0*v_para_star)*dv_para_ds) - 
                           mres/(2.0*v_para_star_sq*gamma)*wh*dv_para_ds + 
                           w/(2.0*v_para_star_sq)*dv_para_ds )

                    BB =( mres/(gamma*v_para_star)*wh - 
                          mres/(gamma*v_para_star)*dwh_ds*(ds/2.0) -
                          w/v_para_star - kz )

                    Farg = (BB + 2.0*AA*ds) / np.sqrt(2.0*np.pi*abs(AA))
                    Farg0 = BB / np.sqrt(2*np.pi*abs(AA))

                    Fs,  Fc  = fresnel(Farg)
                    Fs0, Fc0 = fresnel(Farg0)

                    dFs_sq = pow(Fs - Fs0, 2)
                    dFc_sq = pow(Fc - Fc0, 2)

                    dalpha = np.sqrt( (np.pi/4.0)/abs(AA))*abs(T1/v_para)*np.sqrt(dFs_sq + dFc_sq)
                    alpha_eq_p = np.arcsin( np.sin(alpha_lc+dalpha)*pow(clat,3) / np.sqrt(slat_term) )
                    dalpha_eq  = alpha_eq_p - alpha_eq
                    #print "dalpha_eq:", dalpha_eq
                    #print "output vec shape:", np.shape(dalpha_eq)
                    #print "end - start:", endi - starti

                    #print "t offset:",t.iloc[index[0]]
                    # Add net change in alpha to total array:
                    if direction > 0: 
                        #print "Norf!"
                        iono_time = t + abs(ftc_N/v_para)
                        tt = np.round( iono_time/sc.T_STEP ).astype(int)
                        #print tt
                        tt = np.clip(tt,0,sc.NUM_STEPS - 1)
                        #tt.clip(0,sc.NUM_STEPS)
                        DA_array_N[evec_inds,tt] += dalpha_eq*dalpha_eq
                    else:
                        #print "Souf!" 
                        iono_time = t + abs(ftc_S/v_para)
                        tt = np.round( iono_time/sc.T_STEP ).astype(int)
                        tt = np.clip(tt,0,sc.NUM_STEPS - 1)
                        #print tt
                        DA_array_S[evec_inds,tt] += dalpha_eq*dalpha_eq






        # --------------------- Vector-ish version that isn't working ---------------
        # if cells.shape[0] > 0:
        #     print cells.shape
        #     #print cells.columns

        #     # where you left off: time and frequency (line 1800)
        #     t = cells.tg + sc.DT/2.0
        #     f = cells.frequency + sc.DF/2.0
        #     pwr = cells.power/sc.DT       # Jacob divides by num_rays too, but it looks like it's always 1
        #     psi = cells.psi*sc.D2R       

        #     #print pwr

        #     # Maybe threshold power here?

        #     # Misc. parameters and trig
        #     mu = cells.mu
        #     stixP = cells.stixP
        #     stixR = cells.stixR
        #     stixL = cells.stixL

        #     spsi = np.sin(psi)
        #     cpsi = np.cos(psi)
        #     spsi_sq = spsi*spsi
        #     cpsi_sq = cpsi*cpsi
        #     n_x  = mu*abs(spsi)
        #     n_z  = mu*cpsi
        #     mu_sq = mu*mu
        #     w = 2.0 * np.pi * f
        #     k = w*mu/sc.C
        #     kx = w*n_x/sc.C
        #     kz = w*n_z/sc.C
        #     Y = wh / w

        #     stixS = (stixR + stixL)/2.0
        #     stixD = (stixR - stixL)/2.0
        #     stixA = stixS + (stixP-stixS)*cpsi_sq
        #     stixB = stixP*stixS + stixR*stixL + (stixP*stixS - stixR*stixL)*cpsi_sq
        #     stixX = stixP/(stixP - mu_sq*spsi_sq)
          
        #     rho1=((mu_sq-stixS)*mu_sq*spsi*cpsi)/(stixD*(mu_sq*spsi_sq-stixP))
        #     rho2 = (mu_sq - stixS) / stixD

        #     #print num
        #     Byw_sq = ( (2.0*sc.MU0/sc.C) * (pwr*stixX*stixX*rho2*rho2*mu*abs(cpsi)) /
        #              np.sqrt( pow((np.tan(psi)-rho1*rho2*stixX),2) + pow((1+rho2*rho2*stixX),2)) )
        #     #print Byw_sq
        #     # RMS wave components
        #     Byw = np.sqrt(Byw_sq);
        #     Exw = abs(sc.C*Byw * (stixP - n_x*n_x)/(stixP*n_z))
        #     Eyw = abs(Exw * stixD/(stixS-mu_sq))
        #     Ezw = abs(Exw *n_x*n_z / (n_x*n_x - stixP))
        #     Bxw = abs((Exw *stixD*n_z/sc.C)/ (stixS - mu_sq))
        #     Bzw = abs((Exw *stixD *n_x) /(sc.C*(stixX - mu_sq)));

        #     # Oblique integration quantities
        #     R1 = (Exw + Eyw)/(Bxw+Byw)
        #     R2 = (Exw - Eyw)/(Bxw-Byw)
        #     w1 = (sc.Q_EL/(2*sc.M_EL))*(Bxw+Byw)
        #     w2 = (sc.Q_EL/(2*sc.M_EL))*(Bxw-Byw)
        #     alpha1 = w2/w1
          

        #     # Loop at line 1897 -- MRES loop
        #     # Since we're trying to keep it vectorized:
        #     # target dimensions are num(cell rows) rows x num(mres) columns.
        #     # (Sometimes Python is beautiful, but now is not one of those times)
        #     #  --> Note to future editors: the (vec)[:,np.newaxis] command is similar to repmat or tile:
        #     #  It will tile the vector along the new axis, with length dictated by whatever operation 
        #     #  follows it. In Python lingo this is "broadcasting"

        #     # Resonant modes to sum over: Integers, positive and negative
        #     mres = np.linspace(-5,5,11)
            
        #     # Parallel resonance velocity V_z^res  (pg 5 of Bortnik et al)
        #     t1 = w*w*kz*kz
        #     t2 = (mres*mres*wh*wh)[np.newaxis,:]-(w*w)[:,np.newaxis]
        #     t3 = (kz*kz)[:,np.newaxis] + ((mres*wh*mres*wh)[np.newaxis,:]/(pow(sc.C*np.cos(alpha_lc),2)))
            

        #     #print np.diff(t3[0,:])
        #     direction = np.outer(np.sign(kz),np.sign(mres))
        #     direction[:,mres==0] = -1*np.sign(kz)[:,np.newaxis] # Sign 

        #     # v_para_res = (ta - tb)
        #     v_para_res = ( direction*np.sqrt(abs(t1[:,np.newaxis] + t2*t3)) - (w*kz)[:,np.newaxis] ) / t3

        #     # Getting some obnoxious numerical stuff in the case of m=0:
        #     v_para_res[:,mres==0] = (w/kz)[:,np.newaxis]
        #     v_tot_res = v_para_res / np.cos(alpha_lc)

        #     E_res = sc.E_EL*(1.0/np.sqrt( 1-(v_tot_res*v_tot_res/(sc.C*sc.C)) ) - 1 )

        #     # Start and end indices in the energy array (+-20% energy band)
        #     e_starti = np.floor((np.log10(E_res)-sc.E_EXP_BOT-sc.E_BANDWIDTH)/sc.DE_EXP)
        #     e_endi   = np.ceil(( np.log10(E_res)-sc.E_EXP_BOT+sc.E_BANDWIDTH)/sc.DE_EXP)


        #     # Threshold to range of actual indexes (some energies may be outside our target range)
        #     np.clip(e_starti,0,sc.NUM_E, out=e_starti)
        #     np.clip(e_endi,  0,sc.NUM_E, out=e_endi)

        #     #print "Start index:",e_starti
        #     #print "Stop index: ",e_endi


        #     #inds = zip(e_starti.ravel(), e_endi.ravel())
        #     #print np.shape(inds)
        #     #v_tot = direction*v_tot_arr[e_]


        #     # emask = np.zeros((len(cells), len(mres), sc.NUM_E),dtype=bool)



        #     # for index, starti in np.ndenumerate(e_starti):
        #     #     emask[index[0], index[1],e_starti[index]:e_endi[index]] = True

        #     # print "total emask: ",np.sum(emask)

        #     # emask[:,:,e_starti:e_endi] = True
        #     #print "emask is: ", np.shape(emask)

        #     # Where you left off: Adding in the next loop (V_TOT). Need to iterate from estarti to eendi
        #     # for each cell in the 2d arrays... hmm.... how to vectorize nicely. Hmm.
        #     #print "e_starti is", np.shape(e_starti)
        #     for index, starti in np.ndenumerate(e_starti):
        #         endi = e_endi[index]

        #         #print starti, endi
        #         # Energies to do
        #         #print Ezw.index.values
                    
        #         #print Ezw[index(0)]

        #         if endi >= starti:
        #             # Dimensions of matrices: (num cells) rows x (num energies) columns
        #             #print "Index is", index

        #             v_tot = direction[index]*sc.v_tot_arr[starti:endi]
        #             v_para = v_tot*calph
        #             v_perp = abs(v_tot*salph)

        #             # Relativistic factor
        #             gamma = 1.0/np.sqrt(1.0 - pow(v_tot/sc.C, 2))

        #             alpha2 = (sc.Q_EL/sc.M_EL)*(Ezw.iloc[index[0]]/w1.iloc[index[0]])/(gamma*v_perp)
                    
        #             #print "gamma:", gamma
        #             #print "alpha2:",alpha2
        #             # beta = np.outer(kx/wh,v_perp)
        #             beta = (kx.iloc[index[0]]/wh)*v_perp
        #             #print "beta:", beta

        #             mr = mres[index[1]]
        #             # wtau_sq = (pow((-1),(mr-1))*np.outer(w1, 1.0/gamma) *
        #             #                     (jn(mr -1, beta) -
        #             #                      alpha1[:,np.newaxis]*jn(mr + 1, beta) +
        #             #                      gamma[np.newaxis,:]*alpha2*jn(mr, beta)))
        #             wtau_sq = (pow((-1),(mr-1))*(w1.iloc[index[0]]/gamma)*
        #                        jn(mr - 1, beta) -
        #                        alpha1.iloc[index[0]]*jn(mr + 1, beta) +
        #                        gamma*alpha2*jn(mr,beta))

        #             #T1 = -wtau_sq*(1 + calph*calph/(mr*Y[:,np.newaxis] - 1))
        #             T1 = -wtau_sq*(1 + calph*calph/(mr*Y.iloc[index[0]] - 1))

        #             # Analytical evaluation! (Line 1938)
        #             if (abs(lat) < 1e-3):
        #                 eta_dot = mr*wh/gamma - w.iloc[index[0]] - kz.iloc[index[0]]*v_para
        #                 dalpha_eq = abs(T1/eta_dot)*np.sqrt(1 - np.cos(ds*eta_dot/v_para))
        #             else:
        #                 v_para_star = v_para - dv_para_ds*ds/2.0
        #                 v_para_star_sq = v_para_star*v_para_star

        #                 AA = ((mr/(2.0*v_para_star*gamma))*dwh_ds * 
        #                       (1 + ds/(2.0*v_para_star)*dv_para_ds) - 
        #                       (mr/(2.0*v_para_star_sq*gamma))*wh*dv_para_ds + 
        #                       (w.iloc[index[0]]/(2.0*v_para_star_sq))*dv_para_ds)

        #                 BB = ((mr/(gamma*v_para_star))*wh - 
        #                       (mr/(gamma*v_para_star))*dwh_ds*(ds/2.0) -
        #                        w.iloc[index[0]]/v_para_star - kz.iloc[index[0]])

        #                 Farg = (BB + 2.0*AA*ds) / np.sqrt(2.0*np.pi*abs(AA))
        #                 Farg0 = BB / np.sqrt(2*np.pi*abs(AA))

        #                 Fs,  Fc  = fresnel(Farg)
        #                 Fs0, Fc0 = fresnel(Farg0)

        #                 dFs_sq = pow(Fs - Fs0, 2)
        #                 dFc_sq = pow(Fc - Fc0, 2)

        #                 dalpha = np.sqrt( (np.pi/4.0)*abs(AA))*abs(T1/v_para)*np.sqrt(dFs_sq + dFc_sq)
        #                 alpha_eq_p = np.arcsin( np.sin(alpha_lc+dalpha)*pow(clat,3) / np.sqrt(slat_term) )
        #                 dalpha_eq  = alpha_eq_p - alpha_eq
        #                 #print dalpha_eq
        #                 #print "output vec shape:", np.shape(dalpha_eq)
        #                 #print "end - start:", endi - starti

        #                 #print "t offset:",t.iloc[index[0]]
        #                 # Add net change in alpha to total array:
        #                 if direction[index] > 0:
        #                     #print "Norf!"

        #                     tt = np.round( (t.iloc[index[0]] + ftc_N/v_para)/sc.T_STEP ).astype(int)
        #                     #print tt
        #                     np.clip(tt,0,sc.NUM_STEPS - 1, out=tt)
        #                     #tt.clip(0,sc.NUM_STEPS)
        #                     DA_array_N[starti:endi,tt] += dalpha_eq*dalpha_eq
        #                 else:
        #                     #print "Souf!"
        #                     tt = np.round( (t.iloc[index[0]] + ftc_S/v_para)/sc.T_STEP ).astype(int)
        #                     np.clip(tt,0,sc.NUM_STEPS - 1, out=tt)
        #                     #print tt
        #                     DA_array_S[starti:endi,tt] += dalpha_eq*dalpha_eq
    tstop = time.time()

    print "Scattering took %g seconds"%(tstop - tstart)
    return DA_array_N, DA_array_S
def euler_spiral_parametric(t):
    s, c = fresnel(t)
    return numpy.column_stack((t, c, s))



d = 0.75             # slitwidth mm
lam = 2.66e-4       # wavelength mm
x = np.linspace(-1.5*d,1.5*d,5000) # distance in x direction mm
z = np.linspace(0,3,1000) # log10 of the distance to the screen mm

I1 = np.zeros((len(x),len(z))) # set up array to receive the intensity data

# fix slitwidth, vary screen location
for i in range (0,len(z)-1):
    alpha_1 = (x+d/2)*(np.sqrt(2/(lam*10**z[i])))
    alpha_2 = (x-d/2)*(np.sqrt(2/(lam*10**z[i])))
    s1, c1 = fresnel(alpha_1) #Fresnel integrals
    s2, c2 = fresnel(alpha_2) #Fresnel integrals
    Intensity = 0.5*((c2-c1)**2+(s2-s1)**2)
    I1[:,i]= Intensity


zplot = 310 # distance at which you would  like to plot the intesity pattern mm

plt.figure(1)
plt.plot(x,I1[:,np.where(10**z>zplot-1)[0][0]])
plt.xlabel("x (mm)")
plt.ylabel("Intensity (au)")
plt.title("Intensity profile " +  str(int(10**z[np.where(10**z>zplot-1)[0][0]])) + "mm behind a slit of width " + str(d) + "mm")


# plot limts
Example #41
0
        def integrand(u, N):
            fS, fC = fresnel((self.mu[0] * N * np.pi + self.mu[1] * u) / np.sqrt(self.mu[1] * N * np.pi**2))
            term1 = np.cos(np.pi * self.mu[0]**2 * N / (2. * self.mu[1]) + 2. * np.pi * self.nu0 * N)
            term2 = np.sin(np.pi * self.mu[0]**2 * N / (2. * self.mu[1]) + 2. * np.pi * self.nu0 * N)

            return fC * term1 + fS * term2
Example #42
0
File: join.py Project: auro666/666
def dist(alpha):
	fresnelS, fresnelC = fresnel(math.sqrt(2 * alpha / math.pi))
	return math.cos(alpha) * fresnelC + math.sin(alpha) * fresnelS
Example #43
0
def fres(t):
	s, c = fresnel(math.sqrt(2.0 * t / math.pi))
	return math.cos(t) * c + math.sin(t) * s
Example #44
0
def fresnel0(s):
    im, re = special.fresnel(s);
    return complex(re, im);
def LocBeamInt2(x, z):
    s3, c3 = fresnel(x*(np.sqrt(2/(lam*10**z))))
    I = 0.5*((c3[0:steplen]-c3[steplen:])**2+(s3[0:steplen]-s3[steplen:])**2)    
    return I;
### ch 1.4 Integration
# p10



###-----------------------------------
### ch 1.4.1 General integration(quad)

from scipy import integrate, special

result = integrate.quad(lambda x:special.jv(2.5,x), 0, 4.5)
print result

I = sqrt(2/pi) * (18.0/27 *sqrt(2) *cos(4.5) - 4.0 /27 *sqrt(2) *sin(4.5) + sqrt(2 *pi) *special.fresnel(3 /sqrt(pi))[0])
print I

print abs(result[0] - I)



###-----------------------------------
### p11
from scipy.integrate import quad

def integrand(t,n,x):
    return exp(-x*t) / t**n

def expint(n,x):
    return quad(integrand, 1, Inf, args=(n, x))[0]

vec_expint = vectorize(expint)
pointval = 500 #number of points
d = 1.0#0.75        #slitwidth mm
lam = 2.66e-4       # wavelength mm
zposlim = 500
RefSpace = np.empty([pointval, zposlim]) #Array of Reflection values
IntSpace = np.empty([pointval, zposlim])
xpos1 = np.linspace(-GratLimP/2,GratLimP/2,GratLenOutside)# distance in x direction mm
xpos2 = np.linspace(-GratLimP/2,GratLimP/2,pointval)
zpos = np.linspace(0.5,3.5,zposlim) # log10 of the distance to the screen mm
lampos = np.linspace(1.498,1.503,pointval) #wavelength range microns

steplen = (GratLenOutside+(d/Period)*10**3)/2

xpos3 = np.linspace(-(GratLimP+d)/2, (GratLimP+d)/2, steplen*2)

s3, c3 = fresnel(xpos3)

#tiamat = LocBeamInt(xpos3, zpos[300])
#
plt.plot(s3)
plt.plot(c3)
plt.show()

#dpos = np.linspace(0.5,1.5,zposlim)
#for y in range(0,10,1):#zposlim,1):
#    d = dpos[y]
#    for x in range(0,pointval,1):
#        RefSpace[x,y] = CompRef(lampos[x], xpos1, 2.5).real
#        IntSpace[x,y] = LocBeamInt(xpos2[x], 2.5)

#for tep in range(1,9,1):
Example #48
0
def fresnel_k0_abg(a, s):
    c0 = sqrt(abs(a) / math.pi)
    y, x = special.fresnel(c0 * s)
    return complex(x / c0, copysign(1, a) * y / c0)