예제 #1
0
파일: lab2cm.py 프로젝트: yano404/A5tools
def dOmega(theta_lab, n):
    """
    function to find dΩlab/dΩcm

    Arguments
    ---------
    theta_lab : scattering angle in the lab system [rad]
    n         : A_t / A_i; A_t, A_i means mass number of target particle or incident particle

    Return
    ------
      dΩlab/dΩcm : factor to convert differential cross-section in the lab system to differential cross-section in the center-of-mass system

    Notice
    ------
    This function do not consider relativity
    """
    if isinstance(theta_lab, uncertainties.core.AffineScalarFunc):
        return umath.pow(
            2.0 * umath.cos(theta_lab) / n +
            (1.0 + umath.cos(2.0 * theta_lab) / (n**2.0)) /
            umath.sqrt(1.0 - umath.pow(umath.sin(theta_lab) / n, 2.0)), -1.0)
    elif isinstance(theta_lab, np.ndarray) and isinstance(
            theta_lab[0], uncertainties.core.AffineScalarFunc):
        return unp.pow(
            2.0 * unp.cos(theta_lab) / n +
            (1.0 + unp.cos(2.0 * theta_lab) /
             (n**2.0)) / unp.sqrt(1.0 - unp.pow(unp.sin(theta_lab) / n, 2.0)),
            -1.0)
    else:
        return np.power(
            2.0 * np.cos(theta_lab) / n +
            (1.0 + np.cos(2.0 * theta_lab) /
             (n**2.0)) / np.sqrt(1.0 - np.power(np.sin(theta_lab) / n, 2.0)),
            -1.0)
예제 #2
0
파일: cm2lab.py 프로젝트: yano404/A5tools
def dOmega(theta_cm, n):
    """
    function to find dΩcm/dΩlab

    Arguments
    ---------
    theta_cm : scattering angle in the center-of-mass system [rad]
    n        : A_t / A_i; A_t, A_i means mass number of target particle or incident particle

    Return
    ------
      dΩcm/dΩlab : factor to convert differential cross-section in the center-of-mass system to one in the lab system

    Notice
    ------
    This function does not consider relativity
    """
    if isinstance(theta_cm, uncertainties.core.AffineScalarFunc):
        return umath.pow(1.0 + 2.0 * umath.cos(theta_cm) / n + 1.0 / n**2.0, 3 / 2) \
            / (1.0 + umath.cos(theta_cm) / n)
    elif isinstance(theta_cm, np.ndarray) and isinstance(
            theta_cm[0], uncertainties.core.AffineScalarFunc):
        return unp.pow(1.0 + 2.0 * unp.cos(theta_cm) / n + 1.0 / n**2.0, 3 / 2) \
            / (1.0 + unp.cos(theta_cm) / n)
    else:
        return np.power(1.0 + 2.0 * np.cos(theta_cm) / n + 1.0 / n**2.0, 3 / 2) \
            / (1.0 + np.cos(theta_cm) / n)
    def cornerFidDist(self, cornerData):
        angle = np.mean(self.angles())
        diff = []
        # rotMat=np.array([[unp.cos(angle),unp.sin(angle)],[-unp.sin(angle),unp.cos(angle)]])

        #v1=np.matmul(rotMat,self.points[0].means.T)
        #v2=np.matmul(rotMat,cornerData[0].T)
        #diff=abs(v2-v1)

        for i in range(4):
            #v1=unp.matmul(rotMat,self.points[i].means.T)
            #v2=unp.matmul(rotMat,cornerData[i].T)
            v1 = np.array([
                self.points[i].means[0] * unp.cos(angle) +
                self.points[i].means[1] * unp.sin(angle),
                -self.points[i].means[0] * unp.sin(angle) +
                self.points[i].means[1] * unp.cos(angle)
            ])
            v2 = np.array([
                cornerData[i][0] * unp.cos(angle) +
                cornerData[i][1] * unp.sin(angle),
                -cornerData[i][0] * unp.sin(angle) +
                cornerData[i][1] * unp.cos(angle)
            ])
            diff.append(abs(v2 - v1))
        return diff
예제 #4
0
def f_unc(coordinates, amplitude, xo, yo, sigma_x, sigma_y, theta, offset):
    """
    similar to the raw function call, but uses unp instead of np for uncertainties calculations.
    :return:
    """
    x = coordinates[0]
    y = coordinates[1]
    xo = float(xo)
    yo = float(yo)
    a = (unp.cos(theta)**2)/(2*sigma_x**2) + (unp.sin(theta)**2)/(2*sigma_y**2)
    b = -(unp.sin(2*theta))/(4*sigma_x**2) + (unp.sin(2*theta))/(4*sigma_y**2)
    c = (unp.sin(theta)**2)/(2*sigma_x**2) + (unp.cos(theta)**2)/(2*sigma_y**2)
    g = offset + amplitude*unp.exp(- (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) + c*((y-yo)**2)))
    return g.ravel()
예제 #5
0
def rutherford(theta, T, Zi, Zt, which="inc"):
    """
    Rutherford Scattering in the center-of-mass system

    Arguments
    ---------
    theta : scattering angle in the center-of-mass system
    T     : kinetic energy of incident particle in the center-of-mass system
    Zi    : atomic number of incident particle; charge in units of e
    Zt    : atomic number of target particle; charge in units of e
    which : if which="inc", calc dσ/dΩ(θ) of incident particle.
            if which="tar", calc dσ/dΩ(θ) of target particle.
            if which="sum", calc dσ/dΩ(θ) of incident particle + dσ/dΩ(θ) of target particle.

    Return
    ------
    dσ/dΩ(θ) in the center-of-mass system [mb/str]
    """
    # dσ/dΩ[mb/str]
    # 10.0 : fm^2 --> mb
    if which == "inc":
        # incident particle
        if isinstance(theta, uncertainties.core.AffineScalarFunc):
            return 10.0 * (Zi * Zt * E2 / (4.0 * T))**2.0 * umath.pow(umath.sin(theta / 2.0), -4.0)
        elif isinstance(theta, np.ndarray) and isinstance(theta[0], uncertainties.core.AffineScalarFunc):
            return 10.0 * (Zi * Zt * E2 / (4.0 * T))**2.0 * unp.pow(unp.sin(theta / 2.0), -4.0)
        else:
            return 10.0 * (Zi * Zt * E2 / (4.0 * T))**2.0 * np.power(np.sin(theta / 2.0), -4.0)
    elif which == "tar":
        # target particle
        if isinstance(theta, uncertainties.core.AffineScalarFunc):
            return 10.0 * (Zi * Zt * E2 / (4.0 * T))**2.0 * umath.pow(umath.cos(theta / 2.0), -4.0)
        elif isinstance(theta, np.ndarray) and isinstance(theta[0], uncertainties.core.AffineScalarFunc):
            return 10.0 * (Zi * Zt * E2 / (4.0 * T))**2.0 * unp.pow(unp.cos(theta / 2.0), -4.0)
        else:
            return 10.0 * (Zi * Zt * E2 / (4.0 * T))**2.0 * np.power(np.cos(theta / 2.0), -4.0)
    elif which == "sum":
        # incident particle + target particle
        if isinstance(theta, uncertainties.core.AffineScalarFunc):
            return 10.0 * (Zi * Zt * E2 / (4.0 * T))**2.0 \
                * (umath.pow(umath.sin(theta / 2.0), -4.0) + umath.pow(umath.cos(theta / 2.0), -4.0))
        elif isinstance(theta, np.ndarray) and isinstance(theta[0], uncertainties.core.AffineScalarFunc):
            return 10.0 * (Zi * Zt * E2 / (4.0 * T))**2.0 \
                * (unp.pow(unp.sin(theta / 2.0), -4.0) + unp.power(unp.cos(theta / 2.0), -4.0))
        else:
            return 10.0 * (Zi * Zt * E2 / (4.0 * T))**2.0 \
                * (np.power(np.sin(theta / 2.0), -4.0) + np.power(np.cos(theta / 2.0), -4.0))
    else:
        raise ValueError(
            f"Unrecognized which option:{which}. which must be inc/tar/sum.")
예제 #6
0
def unfunc(x, a, b, c):
    lock_effect = lock * np.heaviside(
        x - lock_start, 0.5) * (x - lock_start) + amp * (unp.cos(
            (x - ph) * (1 / 365) * math.pi * 2) - 1)
    lock_effect += np.exp(-vacc_const * (x**2))
    return a * unp.exp((b) * x + lock_effect) + c * unp.exp(
        (b + mut_effect) * x + lock_effect)
예제 #7
0
파일: cm2lab.py 프로젝트: yano404/A5tools
def theta(theta_cm, n):
    """
    function to convert θ in the center-of-mass system to θ in the lab system

    Arguments
    ---------
    theta_cm : scattering angle in the center-of-mass system [rad]
    n        : A_t / A_i; A_t, A_i means mass number of target particle or incident particle

    Return
    ------
    theta_lab : scattering angle in the lab system [rad]

    Notice
    ------
    This function does not consider relativity
    """
    if isinstance(theta_cm, uncertainties.core.AffineScalarFunc):
        return umath.arctan(
            umath.sin(theta_cm) / (1.0 / n + umath.cos(theta_cm)))
    elif isinstance(theta_cm, np.ndarray) and isinstance(
            theta_cm[0], uncertainties.core.AffineScalarFunc):
        return unp.arctan(unp.sin(theta_cm) / (1.0 / n + unp.cos(theta_cm)))
    else:
        return np.arctan(np.sin(theta_cm) / (1.0 / n + np.cos(theta_cm)))
예제 #8
0
def inertia_components(jay, beta):
    '''Returns the 2D orthogonal inertia tensor.

    When at least three moments of inertia and their axes orientations are
    known relative to a common inertial frame of a planar object, the orthoganl
    moments of inertia relative the frame are computed.

    Parameters
    ----------
    jay : ndarray, shape(n,)
        An array of at least three moments of inertia. (n >= 3)
    beta : ndarray, shape(n,)
        An array of orientation angles corresponding to the moments of inertia
        in jay.

    Returns
    -------
    eye : ndarray, shape(3,)
        Ixx, Ixz, Izz

    '''
    sb = unumpy.sin(beta)
    cb = unumpy.cos(beta)
    betaMat = unumpy.matrix(np.vstack((cb**2, -2 * sb * cb, sb**2)).T)
    eye = np.squeeze(np.asarray(np.dot(betaMat.I, jay)))
    return eye
예제 #9
0
파일: correct.py 프로젝트: yano404/A5tools
    def dS(self, a):
        """
        Arguments
        ---------
        a : angle of rotation [rad]

        Return
        ------
        ΔS : detection area [mm^2]
        """
        Rd = self.R + self.d
        r = self.r
        AT = self.AT
        D0 = self.D(0.0)
        A0 = umath.acos((Rd**2.0 + D0**2.0 - r**2.0) / (2.0 * Rd * D0))
        d = self.d
        w = self.w
        h = self.h
        if isinstance(a, (int, float, np.number, uncertainties.core.AffineScalarFunc)):
            phi = umath.fabs(a - A0 - self.theta(a))
            # ΔS
            return w * h * umath.cos(phi) - d * h * umath.sin(phi)
        elif isinstance(a, np.ndarray):
            phi = unp.fabs(a - A0 - self.theta(a))
            return w * h * unp.cos(phi) - d * h * unp.sin(phi)
        else:
            raise ValueError(
                f"This function not supported for the input types. argument 'a' must be number or array")
예제 #10
0
파일: correct.py 프로젝트: yano404/A5tools
    def theta(self, a):
        """
        Arguments
        ---------
        a : angle of rotation [rad]

        Return
        ------
        θ : scattering angle in the lab system [rad]
        """
        D0 = self.D(0.0)
        D = self.D(a)
        Rd = self.R + self.d
        if isinstance(a, (int, float, np.number, uncertainties.core.AffineScalarFunc)):
            return np.sign(a) * umath.acos(
                (D0**2.0 + D**2.0 - 2.0 * Rd**2.0 *
                 (1.0 - umath.cos(a))) / (2.0 * D0 * D)
            )
        elif isinstance(a, np.ndarray):
            return np.sign(a) * unp.arccos(
                (D0**2.0 + D**2.0 - 2.0 * Rd**2.0 *
                 (1.0 - unp.cos(a))) / (2.0 * D0 * D)
            )
        else:
            raise ValueError(
                f"This function not supported for the input types. argument 'a' must be number or array")
예제 #11
0
def cos(
    x: np.ndarray,
    amp: float = 1.0,
    freq: float = 1 / (2 * np.pi),
    phase: float = 0.0,
    baseline: float = 0.0,
) -> np.ndarray:
    r"""Cosine function.

    .. math::
        y = {\rm amp} \cdot \cos\left(2 \pi {\rm freq} \cdot x
            + {\rm phase}\right) + {\rm baseline}
    """
    return amp * unp.cos(2 * np.pi * freq * x + phase) + baseline
예제 #12
0
def bloch_oscillation_z(x: np.ndarray,
                        px: float = 0.0,
                        py: float = 0.0,
                        pz: float = 0.0,
                        baseline: float = 0.0):
    r"""Bloch oscillation in z basis.

    .. math::
        y = \frac{\left( p_z^2 + (p_x^2 + p_y^2) \cos (\omega x) \right)}{\omega^2}
        + {\rm baseline},

    where :math:`\omega = \sqrt{p_x^2 + p_y^2 + p_z^2}`. The `p_i` stands for the
    measured probability in :math:`i \in \left\{ X, Y, Z \right\}` basis.
    """
    w = unp.sqrt(px**2 + py**2 + pz**2)

    return (pz**2 + (px**2 + py**2) * unp.cos(w * x)) / (w**2) + baseline
예제 #13
0
def e_geo(x, d=0):
    d /= 2
    a = unumpy.sqrt(x**2 + (2 - d) ** 2)
    # Look at geometric_efficiency.png to see what these mean
    h1 = ufloat(2,0.1)
    h2 = ufloat(3,0.1)
    w1 = ufloat(22, 0.1)
    w2 = ufloat(30, 0.1)

    if x < 8:
        c = unumpy.sqrt(((w1 + w2) / 2)**2 + (h2 - h1)**2)
        b = unumpy.sqrt((h2 - d)**2 + ((w1 + w2) / 2 - x)**2)
    else:
        c = w1
        b = unumpy.sqrt((w1 - x)**2 + (h1 - d)**2)
    theta = unumpy.arccos((a**2 + b**2 - c**2) / (2 * a * b))
    return (1 - unumpy.cos(theta / 2)) / 2
예제 #14
0
def cos(number):
    if isinstance(number, fr.Fraction):
        number = Mixed(number)
    elif isinstance(number, uc.UFloat):
        number = Mixed(number)
    elif isinstance(number, float):
        number = Mixed(number)
    elif isinstance(number, int):
        number = Mixed(number)
    assert isinstance(number, Mixed), \
        "Connot calculate cos of an object of type %s." % (type(number))
    if isinstance(number.value, fr.Fraction):
        return Mixed(np.cos(float(number.value)))
    elif isinstance(number.value, uc.UFloat):
        return Mixed(unumpy.cos(number.value).item())
    elif isinstance(number.value, float):
        return Mixed(np.cos(number.value))
    elif isinstance(number.value, int):
        return Mixed(np.cos(number.value))
예제 #15
0
def cos(number):
    if isinstance(number, fr.Fraction):
        number = Mixed(number)
    elif isinstance(number, uc.UFloat):
        number = Mixed(number)
    elif isinstance(number, float):
        number = Mixed(number)
    elif isinstance(number, int):
        number = Mixed(number)
    assert isinstance(number, Mixed), \
        "Connot calculate cos of an object of type %s." % (type(number))
    if isinstance(number.value, fr.Fraction):
        return Mixed(np.cos(float(number.value)))
    elif isinstance(number.value, uc.UFloat):
        return Mixed(unumpy.cos(number.value).item())
    elif isinstance(number.value, float):
        return Mixed(np.cos(number.value))
    elif isinstance(number.value, int):
        return Mixed(np.cos(number.value))
예제 #16
0
def plotphase(frequenz, spannung):
    verschiebung = 250e-9  # s
    frequenz = unp.uarray(frequenz, 0.005)
    spannung = unp.uarray(spannung, 0.001)
    frequenz *= 10**(6)
    umlaufdauer = 1 / frequenz
    phase = 2 * np.pi * verschiebung / umlaufdauer
    # print('Umlaufdauer=', umlaufdauer)
    # print('Phase= ', phase)
    y = unp.cos(phase)
    x = spannung

    plt.errorbar(unp.nominal_values(x),
                 unp.nominal_values(y),
                 xerr=unp.std_devs(x),
                 yerr=unp.std_devs(y),
                 fmt='kx',
                 label='Messwerte')

    # fitten:
    params, covariance = curve_fit(fitfunktion,
                                   unp.nominal_values(x),
                                   unp.nominal_values(y),
                                   p0=[-0.1, 1])
    errors = np.sqrt(np.diag(covariance))
    print('m= ', params[0], '±', errors[0], ' yabschnitt= ', params[1], '±',
          errors[1])
    x_fit = np.linspace(-0.2, 0.2)
    plt.plot(x_fit, fitfunktion(x_fit, *params), label='Fit')

    # aussehen:
    plt.xlim(-0.19, 0.19)
    plt.ylabel(r'$\cos(\Delta\phi)$')
    plt.xlabel(r'$U \:/\: \si{\volt}$')
    plt.legend(loc='best')

    # in matplotlibrc leider (noch) nicht möglich
    plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
    plt.savefig('build/plotphase.pdf')
    plt.close()

    return phase
예제 #17
0
def test_broadcast_funcs():
    """
    Test of mathematical functions that work with NumPy arrays of
    numbers with uncertainties.
    """

    x = uncertainties.ufloat((0.2, 0.1))
    arr = numpy.array([x, 2*x])
    assert unumpy.cos(arr)[1] == uncertainties.umath.cos(arr[1])

    # Some functions do not bear the same name in the math module and
    # in NumPy (acos instead of arccos, etc.):
    assert unumpy.arccos(arr)[1] == uncertainties.umath.acos(arr[1])
    # The acos() function should not exist in unumpy because it does
    # not exist in numpy:
    assert not hasattr(numpy, 'acos')
    assert not hasattr(unumpy, 'acos')

    # Test of the __all__ variable:
    assert 'acos' not in unumpy.__all__
예제 #18
0
def test_broadcast_funcs():
    """
    Test of mathematical functions that work with NumPy arrays of
    numbers with uncertainties.
    """

    x = uncertainties.ufloat((0.2, 0.1))
    arr = numpy.array([x, 2*x])
    assert unumpy.cos(arr)[1] == uncertainties.umath.cos(arr[1])

    # Some functions do not bear the same name in the math module and
    # in NumPy (acos instead of arccos, etc.):
    assert unumpy.arccos(arr)[1] == uncertainties.umath.acos(arr[1])
    # The acos() function should not exist in unumpy because it does
    # not exist in numpy:
    assert not hasattr(numpy, 'acos')
    assert not hasattr(unumpy, 'acos')

    # Test of the __all__ variable:
    assert 'acos' not in unumpy.__all__
예제 #19
0
파일: correct.py 프로젝트: yano404/A5tools
    def D(self, a):
        """
        Arguments
        ---------
        a : angle of rotation [rad]

        Return
        ------
        D : distance between target and detector [mm]
        """
        Rd = self.R + self.d
        r = self.r
        AT = self.AT
        if isinstance(a, (int, float, np.number, uncertainties.core.AffineScalarFunc)):
            return umath.sqrt(Rd**2.0 + r**2.0 - 2.0 * Rd * r * umath.cos(a + AT))
        elif isinstance(a, np.ndarray):
            return unp.sqrt(Rd**2.0 + r**2.0 - 2.0 * Rd * r * unp.cos(a + AT))
        else:
            raise ValueError(
                f"This function not supported for the input types. argument 'a' must be number or array")
예제 #20
0
파일: lab2cm.py 프로젝트: yano404/A5tools
def theta(theta_lab, n):
    """
    function to convert θ in the lab system to θ in the center-of-mass system

    Arguments
    ---------
    theta_lab : scattering angle in the lab system [rad]
    n         : A_t / A_i; A_t, A_i means mass number of target particle or incident particle

    Return
    ------
    theta_cm  : scattering angle in the center-of-mass system [rad]

    Notice
    ------
    This function do not consider relativity
    """
    if isinstance(theta_lab, uncertainties.core.AffineScalarFunc):
        coslab2 = umath.pow(umath.cos(theta_lab), 2.0)
        coscm = (coslab2 - 1.0) / n \
            + umath.sqrt((1.0 - 1.0 / n**2.0) * coslab2 +
                         umath.pow(coslab2 / n, 2.0))
        return np.sign(theta_lab) * umath.acos(coscm)
    elif isinstance(theta_lab, np.ndarray) and isinstance(
            theta_lab[0], uncertainties.core.AffineScalarFunc):
        coslab2 = unp.pow(unp.cos(theta_lab), 2.0)
        coscm = (coslab2 - 1.0) / n \
            + unp.sqrt((1.0 - 1.0 / n**2.0) * coslab2 +
                       unp.pow(coslab2 / n, 2.0))
        return np.sign(theta_lab) * unp.arccos(coscm)
    else:
        coslab2 = np.power(np.cos(theta_lab), 2.0)
        coscm = (coslab2 - 1.0) / n \
            + np.sqrt((1.0 - 1.0 / n**2.0) * coslab2 +
                      np.power(coslab2 / n, 2.0))
        return np.sign(theta_lab) * np.arccos(coscm)
예제 #21
0
    def output(n_refl,
               gitter,
               theta,
               lam,
               pathrefl,
               pathfig,
               pathparams,
               rem=0):
        theta = theta[:n_refl]
        for x in new_m:
            print(unumpy.nominal_values(gittertest(x[:n_refl], theta)))
        abstand = gitterabstand(lam, new_m[gitter][:n_refl], theta)

        x = unumpy.cos(theta)**2

        popt, pcov = curve_fit(linear_func, unumpy.nominal_values(x[rem:]),
                               unumpy.nominal_values(abstand[rem:]))

        print('parameter:', popt, np.sqrt(np.diag(pcov)))
        with open(pathparams, "w") as text_file:
            text_file.write(
                '\\num{' + '{}'.format(round(popt[1] * 10**10, 2)) + '+-' +
                '{}'.format(np.round(np.sqrt(pcov[1, 1]) * 10**10, 2)) +
                '} & ' + '\\num{' + '{}'.format(round(popt[0] * 10**10, 2)) +
                '+-' + '{}'.format(np.round(np.sqrt(pcov[0, 0]) * 10**10, 2)) +
                '} \\\\')

        plt.errorbar(unumpy.nominal_values(x),
                     unumpy.nominal_values(abstand),
                     xerr=unumpy.std_devs(x),
                     yerr=unumpy.std_devs(abstand),
                     fmt='o')
        plt.plot(np.linspace(0, 1, 10),
                 linear_func(np.linspace(0, 1, 10), *popt), '--')
        plt.xlabel(r'$\cos^2(\theta)$')
        plt.ylabel(r'$a$ / m')
        plt.tight_layout(pad=0)
        plt.savefig(pathfig)
        plt.close()

        with open(pathrefl, "w") as text_file:
            i = 1
            for theta, m in zip(theta, new_m[gitter][:n_refl]):
                theta_deg = round(np.degrees(unumpy.nominal_values(theta)), 1)
                theta_deg_err = round(np.degrees(unumpy.std_devs(theta)), 0)
                m_sin = round(
                    np.asscalar(unumpy.nominal_values(gittertest(m, theta))))
                cosinus = round(
                    np.asscalar(np.cos(unumpy.nominal_values(theta))**2), 3)
                abstand = round(
                    np.asscalar(
                        unumpy.nominal_values(
                            10**10 * gitterabstand(lam, m, theta))), 2)
                abstand_err = round(
                    np.asscalar(
                        unumpy.std_devs(10**10 *
                                        gitterabstand(lam, m, theta))), 2)
                text_file.write('{} &'.format(i) + ' \\num{'+'{}'.format(theta_deg) +
                        ' +- ' '{}'.format(theta_deg_err) + '} ' + \
                        '& {} & {} & {} & '.format(m, m_sin, cosinus) + '\\num{'
                        + '{}'.format(abstand) + ' +- '+ '{}'.format(abstand_err) +
                        ' } \\\\ \n')
                i += 1
예제 #22
0
#!/usr/bin/env python

#example taken from https://pypi.python.org/pypi/uncertainties/3.0.1
from __future__ import print_function
from uncertainties import ufloat
x = ufloat(2, 0.25)
print(x)
square = x**2  # Transparent calculations
print(square)
print(square.nominal_value)
print(square.std_dev)  # Standard deviation
print(square - x * x)
from uncertainties.umath import *  # sin(), etc.
print(sin(1 + x**2))
print((2 * x + 1000).derivatives[x])  # Automatic calculation of derivatives
from uncertainties import unumpy  # Array manipulation
random_vars = unumpy.uarray([1, 2], [0.1, 0.2])
print(random_vars)
print(random_vars.mean())
print(unumpy.cos(random_vars))
예제 #23
0
파일: mod.py 프로젝트: dfb159/expKP
def cos_abs(x, a, f, phi):
    '''a*|cos(2*π*f*(x-phi))|'''
    return a * np.abs(unp.cos(2 * np.pi * f * (x - phi)))
예제 #24
0



########## Aufgabenteil b) ##########
# Kalibrierung des Okularmikrometers
lambda_kalibrierung = np.array(
    [438.8, 447.1, 501.6, 504.8]) * 1e-9       # in m
Eichgroesse = unp.uarray(np.zeros(np.size(lambda_kalibrierung)/2), np.zeros(np.size(lambda_kalibrierung)/2))    # in m Skt    Skt = Sektor
phi_mean = unp.uarray(np.zeros(np.size(phi_kalib)/2), np.zeros(np.size(phi_kalib)/2))                           # in rad
eichgroesse_mit_fehler = ufloat(0,0)                                                                            # in m Skt    Skt = Sektor
i = 0
for eichgroesse in Eichgroesse:
    j = 2*i         # index für die 2*size(Eichgroesse) arrays, in unserem Fall arrays mit 4 Einträgen
    phi_mean[i] = ufloat(np.mean(phi_kalib[j:j+2]), np.std(phi_kalib[j:j+2]))    # Indizierung für i= 0: von 0 bis < 2  also 0 bis 1, dh. wir bilden Mittelwert aus zwei Werten
    Eichgroesse[i] = np.abs(lambda_kalibrierung[j] - lambda_kalibrierung[j+1]) / ( np.abs(t_kalib[j] - t_kalib[j+1]) * unp.cos(phi_mean[i]) )   # Formel aus "zu b:"
    eichgroesse_mit_fehler += Eichgroesse[i]
    i += 1
eichgroesse_mit_fehler *= 1/(np.size(lambda_kalibrierung)/2)      # in m
write('build/Eichgroesse.tex', make_SI(eichgroesse_mit_fehler*1e9, r'\nano\meter', figures=1) )  # hier fehlt noch Skt^-1  das geht allerdings schlecht mit make_si..

# Tabelle für LaTeX:
phi1 = np.array([phi_kalib[0], phi_kalib[2]])       # crappy weil hart codiert aber was will man machen
phi2 = np.array([phi_kalib[1], phi_kalib[3]])       # in rad
lambda1 = [lambda_kalibrierung[0]*1e9, lambda_kalibrierung[2]*1e9]     # in nm
lambda2 = [lambda_kalibrierung[1]*1e9, lambda_kalibrierung[3]*1e9]     # in nm
t1 = [t_kalib[0], t_kalib[2]]
t2 = [t_kalib[1], t_kalib[3]]
write('build/Tabelle_b.tex', make_table([-phi1,lambda1,t1,-phi2,lambda2,t2,-phi_mean],[3, 1, 1, 3, 1, 1, 1]))     # Jeder fehlerbehaftete Wert bekommt zwei Spalten
write('build/Tabelle_b_texformat.tex', make_full_table(
    'Messdaten zur Bestimmung der Eichgröße.',
def f_unc(x, A, tau, freq, phi, offset):
    return offset + A * unp.exp(-x / tau) * unp.cos(2 * np.pi * freq * x + phi)
예제 #26
0
#!/usr/bin/env python

#example taken from https://pypi.python.org/pypi/uncertainties/3.0.1
from __future__ import print_function
from uncertainties import ufloat
x = ufloat(2, 0.25)
print(x)
square = x**2  # Transparent calculations
print(square)
print(square.nominal_value)
print(square.std_dev)  # Standard deviation
print(square - x*x)
from uncertainties.umath import *  # sin(), etc.
print(sin(1+x**2))
print((2*x+1000).derivatives[x])  # Automatic calculation of derivatives
from uncertainties import unumpy  # Array manipulation
random_vars = unumpy.uarray([1, 2], [0.1, 0.2])
print(random_vars)
print(random_vars.mean())
print(unumpy.cos(random_vars))
예제 #27
0
def cos(x, a, f, phi):
    return a * unp.cos(2*np.pi*f*(x-phi))
예제 #28
0
def cos_abs(x, a, f, phi):
    return a * np.abs(unp.cos(2*np.pi*f*(x-phi)))
예제 #29
0
plt.legend()
plt.xlabel('$\\alpha$ / $^\circ$')
plt.ylabel('relative Intensität')
plt.savefig('../../pics/rot.png')

d = unp.uarray([403.609], [9.666])*1e-9
w_B = unp.uarray([135],[1])
w_G = unp.uarray([83],[1])
alpha_1 = unp.uarray([popt[0]],[popt_error[0]])
alpha_2 = unp.uarray([popt[3]],[popt_error[3]])
delta_beta = -alpha_2+alpha_1
print('\n delta beta')
print(delta_beta)
delta_beta_value = unp.nominal_values(delta_beta)
delta_beta_error = unp.std_devs(delta_beta)
delta_lamda = d*unp.cos(unp.radians(w_B)+unp.radians(w_G)-np.radians(180))*unp.radians(delta_beta)
print('\n delta lambda')
print(delta_lamda)


####
# Rechne Linienbreite in nm um
####
delta_alpha_a = unp.uarray(-a_x_0+a_x_1, (a_x_0-a_x_1)*0.01)
delta_alpha_b = unp.uarray(-b_x_0+b_x_1, (b_x_0-b_x_1)*0.01)
delta_doppler_a = d*unp.cos(unp.radians(w_B)+unp.radians(w_G)-np.radians(180))*unp.radians(delta_alpha_a)
delta_doppler_b = d*unp.cos(unp.radians(w_B)+unp.radians(w_G)-np.radians(180))*unp.radians(delta_alpha_b)
print('\nDoppler')
print(delta_doppler_a)
print(delta_doppler_b)
예제 #30
0
def main():

    print('\n#################### Analyse für Salz ####################\n')

    Xi2_best = [
        'SC', 20, 'CuF'
    ]  # SC ist in dem Fall ein Platzhalter. Die 20 garantiert, dass ein jedes Xi zunächst kleiner ist.

    # daten1, daten2 = np.genfromtxt('SalzRadius.txt', unpack=True)
    # daten = np.array([23, 34.50, 41, 43, 51, 57, 58.5, 65, 70, 78, 83, 84.5, 90,95.5, 103, 108,110,116, 123, 133, 116 +43])
    daten = np.array([
        23, 34.50, 43, 51, 57, 65, 78, 83, 90, 95.5, 103, 108, 123, 133,
        116 + 43
    ])
    # daten = np.array([23, 34.50, 43, 51, 57, 65, 78, 83,95.5, 103, 108, 123, 133, 116 +43]) #9. raus

    # maske = [True,True,False,True,True,True,True,True,True,True,True,True,True,True,True,True,True,True,True,True,True]
    # daten = daten[maske]
    daten = daten + 4.5
    # daten = daten[daten != 0]
    daten = (daten * np.pi) / (360)

    print('Daten: ', daten)

    # theta = theta_radiant(radius())
    theta = daten

    print('Theta mit Fehler: ', theta)
    netzebenenabstand = bragg(lambda_1, noms(theta))

    reflexe_Zinkblende = []
    reflexe_Steinsalz = []
    reflexe_Caesiumchlorid = []
    reflexe_Fluorit = []

    verhaeltnisse_temp = []

    for gitter in gitter_moegl:
        if gitter == 'Zinkblende':
            ############## CuF ##################
            argg = 'CuF'
            print('Berechnung ' + gitter + ' für ' + argg + ':')
            infos = Strukturamplitude_Salz(28, 10, gitter=gitter)
            reflexe = np.array(infos[0])
            # print(gitter +': ',reflexe[np.argsort(infos[1])])
            m = infos[1]
            m = np.sort(m)

            verhaeltnisse = findStructure(m, netzebenenabstand)
            verhaeltnisse_temp = verhaeltnisse[0]
            # verhaeltnis_m = np.sort(verhaeltnisse[0])
            verhaeltnis_m = verhaeltnisse[0]
            if gitter == 'Zinkblende':
                reflexe_Zinkblende = verhaeltnis_m
            elif gitter == 'Steinsalz':
                reflexe_Steinsalz = verhaeltnis_m
            elif gitter == 'Caesiumchlorid':
                reflexe_Caesiumchlorid = verhaeltnis_m
            elif gitter == 'Fluorit':
                reflexe_Fluorit = verhaeltnis_m

            verhaeltnis_d = np.sort(verhaeltnisse[1])

            print('sqrt(m_i/m_1): ', verhaeltnis_m)
            print('d_1/d_i: ', verhaeltnis_d)

            print('Verhältnisse für die m Werte: ', verhaeltnis_m)
            print('Verhältnisse für die d Werte: ', verhaeltnis_d)
            print(
                'Abweichung Xi^2 für die ' + gitter + ' Struktur für ' + argg +
                ': ', abweichung(verhaeltnis_m, verhaeltnis_d))

            if abweichung(verhaeltnis_m, verhaeltnis_d) < Xi2_best[1]:
                Xi2_best = [
                    gitter,
                    abweichung(verhaeltnis_m, verhaeltnis_d), argg
                ]

            ############## CuCl ##################

            argg = 'CuCl'
            print('Berechnung ' + gitter + ' für ' + argg + ':')
            infos = Strukturamplitude_Salz(28, 18, gitter=gitter)
            reflexe = np.array(infos[0])
            # print(gitter +': ',reflexe[np.argsort(infos[1])])
            m = infos[1]
            m = np.sort(m)

            verhaeltnisse = findStructure(m, netzebenenabstand)
            verhaeltnisse_temp = verhaeltnisse[0]
            # verhaeltnis_m = np.sort(verhaeltnisse[0])
            verhaeltnis_m = verhaeltnisse[0]
            if gitter == 'Zinkblende':
                reflexe_Zinkblende = verhaeltnis_m
            elif gitter == 'Steinsalz':
                reflexe_Steinsalz = verhaeltnis_m
            elif gitter == 'Caesiumchlorid':
                reflexe_Caesiumchlorid = verhaeltnis_m
            elif gitter == 'Fluorit':
                reflexe_Fluorit = verhaeltnis_m

            verhaeltnis_d = np.sort(verhaeltnisse[1])

            print('sqrt(m_i/m_1): ', verhaeltnis_m)
            print('d_1/d_i: ', verhaeltnis_d)

            print('Verhältnisse für die m Werte: ', verhaeltnis_m)
            print('Verhältnisse für die d Werte: ', verhaeltnis_d)
            print(
                'Abweichung Xi^2 für die ' + gitter + ' Struktur für ' + argg +
                ': ', abweichung(verhaeltnis_m, verhaeltnis_d))

            if abweichung(verhaeltnis_m, verhaeltnis_d) < Xi2_best[1]:
                Xi2_best = [
                    gitter,
                    abweichung(verhaeltnis_m, verhaeltnis_d), argg
                ]
        elif gitter == 'Steinsalz':
            ############## KF ##################
            argg = 'KF'
            print('Berechnung ' + gitter + ' für ' + argg + ':')
            infos = Strukturamplitude_Salz(18, 10, gitter=gitter)
            reflexe = np.array(infos[0])
            # print(gitter +': ',reflexe[np.argsort(infos[1])])
            m = infos[1]
            m = np.sort(m)

            verhaeltnisse = findStructure(m, netzebenenabstand)
            verhaeltnisse_temp = verhaeltnisse[0]
            # verhaeltnis_m = np.sort(verhaeltnisse[0])
            verhaeltnis_m = verhaeltnisse[0]
            if gitter == 'Zinkblende':
                reflexe_Zinkblende = verhaeltnis_m
            elif gitter == 'Steinsalz':
                reflexe_Steinsalz = verhaeltnis_m
            elif gitter == 'Caesiumchlorid':
                reflexe_Caesiumchlorid = verhaeltnis_m
            elif gitter == 'Fluorit':
                reflexe_Fluorit = verhaeltnis_m

            verhaeltnis_d = np.sort(verhaeltnisse[1])

            print('sqrt(m_i/m_1): ', verhaeltnis_m)
            print('d_1/d_i: ', verhaeltnis_d)

            print('Verhältnisse für die m Werte: ', verhaeltnis_m)
            print('Verhältnisse für die d Werte: ', verhaeltnis_d)
            print(
                'Abweichung Xi^2 für die ' + gitter + ' Struktur für ' + argg +
                ': ', abweichung(verhaeltnis_m, verhaeltnis_d))

            if abweichung(verhaeltnis_m, verhaeltnis_d) < Xi2_best[1]:
                Xi2_best = [
                    gitter,
                    abweichung(verhaeltnis_m, verhaeltnis_d), argg
                ]

            ############## KCl ##################

            argg = 'KCl'
            print('Berechnung ' + gitter + ' für ' + argg + ':')
            infos = Strukturamplitude_Salz(18, 18, gitter=gitter)
            reflexe = np.array(infos[0])
            # print(gitter +': ',reflexe[np.argsort(infos[1])])
            m = infos[1]
            m = np.sort(m)

            verhaeltnisse = findStructure(m, netzebenenabstand)
            verhaeltnisse_temp = verhaeltnisse[0]
            # verhaeltnis_m = np.sort(verhaeltnisse[0])
            verhaeltnis_m = verhaeltnisse[0]
            if gitter == 'Zinkblende':
                reflexe_Zinkblende = verhaeltnis_m
            elif gitter == 'Steinsalz':
                reflexe_Steinsalz = verhaeltnis_m
            elif gitter == 'Caesiumchlorid':
                reflexe_Caesiumchlorid = verhaeltnis_m
            elif gitter == 'Fluorit':
                reflexe_Fluorit = verhaeltnis_m

            verhaeltnis_d = np.sort(verhaeltnisse[1])

            print('sqrt(m_i/m_1): ', verhaeltnis_m)
            print('d_1/d_i: ', verhaeltnis_d)

            print('Verhältnisse für die m Werte: ', verhaeltnis_m)
            print('Verhältnisse für die d Werte: ', verhaeltnis_d)
            print(
                'Abweichung Xi^2 für die ' + gitter + ' Struktur für ' + argg +
                ': ', abweichung(verhaeltnis_m, verhaeltnis_d))

            if abweichung(verhaeltnis_m, verhaeltnis_d) < Xi2_best[1]:
                Xi2_best = [
                    gitter,
                    abweichung(verhaeltnis_m, verhaeltnis_d), argg
                ]
        elif gitter == 'Caesiumchlorid':
            ############## CsJ ##################
            argg = 'CsJ'
            print('Berechnung ' + gitter + ' für ' + argg + ':')
            infos = Strukturamplitude_Salz(54, 54, gitter=gitter)
            reflexe = np.array(infos[0])
            # print(gitter +': ',reflexe[np.argsort(infos[1])])
            m = infos[1]
            m = np.sort(m)

            verhaeltnisse = findStructure(m, netzebenenabstand)
            verhaeltnisse_temp = verhaeltnisse[0]
            # verhaeltnis_m = np.sort(verhaeltnisse[0])
            verhaeltnis_m = verhaeltnisse[0]
            if gitter == 'Zinkblende':
                reflexe_Zinkblende = verhaeltnis_m
            elif gitter == 'Steinsalz':
                reflexe_Steinsalz = verhaeltnis_m
            elif gitter == 'Caesiumchlorid':
                reflexe_Caesiumchlorid = verhaeltnis_m
            elif gitter == 'Fluorit':
                reflexe_Fluorit = verhaeltnis_m

            verhaeltnis_d = np.sort(verhaeltnisse[1])

            print('sqrt(m_i/m_1): ', verhaeltnis_m)
            print('d_1/d_i: ', verhaeltnis_d)

            print('Verhältnisse für die m Werte: ', verhaeltnis_m)
            print('Verhältnisse für die d Werte: ', verhaeltnis_d)
            print(
                'Abweichung Xi^2 für die ' + gitter + ' Struktur für ' + argg +
                ': ', abweichung(verhaeltnis_m, verhaeltnis_d))

            if abweichung(verhaeltnis_m, verhaeltnis_d) < Xi2_best[1]:
                Xi2_best = [
                    gitter,
                    abweichung(verhaeltnis_m, verhaeltnis_d), argg
                ]

            ############## CsCl ################## -> könnte komisch sein

            argg = 'CsCl'
            print('Berechnung ' + gitter + ' für ' + argg +
                  '(könnte komisch sein):')
            infos = Strukturamplitude_Salz(54, 18, gitter=gitter)
            reflexe = np.array(infos[0])
            # print(gitter +': ',reflexe[np.argsort(infos[1])])
            m = infos[1]
            m = np.sort(m)

            verhaeltnisse = findStructure(m, netzebenenabstand)
            verhaeltnisse_temp = verhaeltnisse[0]
            # verhaeltnis_m = np.sort(verhaeltnisse[0])
            verhaeltnis_m = verhaeltnisse[0]
            if gitter == 'Zinkblende':
                reflexe_Zinkblende = verhaeltnis_m
            elif gitter == 'Steinsalz':
                reflexe_Steinsalz = verhaeltnis_m
            elif gitter == 'Caesiumchlorid':
                reflexe_Caesiumchlorid = verhaeltnis_m
            elif gitter == 'Fluorit':
                reflexe_Fluorit = verhaeltnis_m

            verhaeltnis_d = np.sort(verhaeltnisse[1])

            print('sqrt(m_i/m_1): ', verhaeltnis_m)
            print('d_1/d_i: ', verhaeltnis_d)

            print('Verhältnisse für die m Werte: ', verhaeltnis_m)
            print('Verhältnisse für die d Werte: ', verhaeltnis_d)
            print(
                'Abweichung Xi^2 für die ' + gitter + ' Struktur für ' + argg +
                ': ', abweichung(verhaeltnis_m, verhaeltnis_d))

            if abweichung(verhaeltnis_m, verhaeltnis_d) < Xi2_best[1]:
                Xi2_best = [
                    gitter,
                    abweichung(verhaeltnis_m, verhaeltnis_d), argg
                ]
        elif gitter == 'Fluorit':
            ############## CaF ##################
            argg = 'CaF'
            print('Berechnung ' + gitter + ' für ' + argg + ':')
            infos = Strukturamplitude_Salz(18, 10, gitter=gitter)
            reflexe = np.array(infos[0])
            # print(gitter +': ',reflexe[np.argsort(infos[1])])
            m = infos[1]
            m = np.sort(m)

            verhaeltnisse = findStructure(m, netzebenenabstand)
            verhaeltnisse_temp = verhaeltnisse[0]
            # verhaeltnis_m = np.sort(verhaeltnisse[0])
            verhaeltnis_m = verhaeltnisse[0]
            if gitter == 'Zinkblende':
                reflexe_Zinkblende = verhaeltnis_m
            elif gitter == 'Steinsalz':
                reflexe_Steinsalz = verhaeltnis_m
            elif gitter == 'Caesiumchlorid':
                reflexe_Caesiumchlorid = verhaeltnis_m
            elif gitter == 'Fluorit':
                reflexe_Fluorit = verhaeltnis_m

            verhaeltnis_d = np.sort(verhaeltnisse[1])

            print('sqrt(m_i/m_1): ', verhaeltnis_m)
            print('d_1/d_i: ', verhaeltnis_d)

            print('Verhältnisse für die m Werte: ', verhaeltnis_m)
            print('Verhältnisse für die d Werte: ', verhaeltnis_d)
            print(
                'Abweichung Xi^2 für die ' + gitter + ' Struktur für ' + argg +
                ': ', abweichung(verhaeltnis_m, verhaeltnis_d))

            if abweichung(verhaeltnis_m, verhaeltnis_d) < Xi2_best[1]:
                Xi2_best = [
                    gitter,
                    abweichung(verhaeltnis_m, verhaeltnis_d), argg
                ]

            ############## CaCl ################## -> könnte komisch sein

            argg = 'CaCl'
            print('Berechnung ' + gitter + ' für ' + argg +
                  '(könnte komisch sein):')
            infos = Strukturamplitude_Salz(18, 18, gitter=gitter)
            reflexe = np.array(infos[0])
            # print(gitter +': ',reflexe[np.argsort(infos[1])])
            m = infos[1]
            m = np.sort(m)

            verhaeltnisse = findStructure(m, netzebenenabstand)
            verhaeltnisse_temp = verhaeltnisse[0]
            # verhaeltnis_m = np.sort(verhaeltnisse[0])
            verhaeltnis_m = verhaeltnisse[0]
            if gitter == 'Zinkblende':
                reflexe_Zinkblende = verhaeltnis_m
            elif gitter == 'Steinsalz':
                reflexe_Steinsalz = verhaeltnis_m
            elif gitter == 'Caesiumchlorid':
                reflexe_Caesiumchlorid = verhaeltnis_m
            elif gitter == 'Fluorit':
                reflexe_Fluorit = verhaeltnis_m

            verhaeltnis_d = np.sort(verhaeltnisse[1])

            print('sqrt(m_i/m_1): ', verhaeltnis_m)
            print('d_1/d_i: ', verhaeltnis_d)

            print('Verhältnisse für die m Werte: ', verhaeltnis_m)
            print('Verhältnisse für die d Werte: ', verhaeltnis_d)
            print(
                'Abweichung Xi^2 für die ' + gitter + ' Struktur für ' + argg +
                ': ', abweichung(verhaeltnis_m, verhaeltnis_d))

            if abweichung(verhaeltnis_m, verhaeltnis_d) < Xi2_best[1]:
                Xi2_best = [
                    gitter,
                    abweichung(verhaeltnis_m, verhaeltnis_d), argg
                ]

    print('Struktur mit der kleinsten Abweichung: ', Xi2_best[0], ' für ',
          Xi2_best[2])
    print('Abweichung Xi^2: ', Xi2_best[1])

    m = Strukturamplitude_Salz(18, 18, gitter=Xi2_best[0])[1]
    a = np.array(gitterkonstanteBragg(m, netzebenenabstand))

    print('Gitterkonstanten für ' + Xi2_best[0] + ' Struktur: ', ' für ',
          Xi2_best[2], a)

    ####################################################################################################
    # Systematischer Fehler
    ####################################################################################################

    # systematischer Fehler Absorption der Röntgenstrahlung

    DeltaA = (radius_rohr /
              (2 * Radius_kamera)) * (1 - Radius_kamera / Abstand_FP) * (
                  np.cos(noms(theta))**2 / noms(theta)) * a

    a_mitFehler = unp.uarray(a, DeltaA)
    print('Gitterkonstanten mit Fehler durch die Absorption: ', a_mitFehler)

    ####################################################################################################
    # curve_fit zeugs
    ####################################################################################################

    # linearer fit für a gegen cos^2
    # params, cov = curve_fit(lin,np.cos(noms(theta))**2,noms(a_mitFehler), sigma = stds(a_mitFehler))
    params, cov = curve_fit(lin, np.cos(noms(theta))**2, noms(a_mitFehler))
    err = np.sqrt(np.diag(cov))
    a_extrp = ufloat(params[1], err[1])
    print('Extrapolierte Gitterkonstante: ', a_extrp)

    ####################################################################################################
    # Plots
    ####################################################################################################

    cos2Theta = unp.cos(theta)**2
    cos2Theta_fit = np.linspace(0, 1)

    ####### ab hier der a gegen cos^2 Plot ########
    plt.errorbar(np.cos(noms(theta))**2,
                 a,
                 xerr=stds(cos2Theta),
                 yerr=DeltaA,
                 fmt='x',
                 label='Daten')
    plt.plot(cos2Theta_fit, lin(cos2Theta_fit, *params), label='Fit')
    plt.legend(loc='best')
    plt.xlabel('cos$^2(\Theta)$')
    plt.ylabel('$a$ in Angtröm')
    # plt.xlim(0.6,1)
    # plt.ylim(4.8e-10,5.8e-10)
    plt.tight_layout()
    plt.grid()
    plt.savefig('Plots/Salz_Fit_Egor.pdf')
    plt.close()

    i = np.linspace(1, len(daten), len(daten))

    verhaeltnisse_daten = []
    for j in range(0, len(daten)):
        verhaeltnisse_daten.append(unp.sin(daten[j]) / unp.sin(daten[0]))

    plt.plot(i, reflexe_Zinkblende, 'x', label='Zinkblende')
    plt.plot(i, reflexe_Steinsalz, 'x', label='Steinsalz')
    plt.plot(i, reflexe_Caesiumchlorid, 'x', label='Caesiumchlorid')
    plt.plot(i, reflexe_Fluorit, 'o', label='Fluorit')
    plt.plot(i, noms(verhaeltnisse_daten), 'x', label='data')
    plt.xlabel('i')
    # plt.xlim(0,7)
    # plt.ylim(0,4.5)
    plt.ylabel('verhältnisse')
    plt.legend(loc='best')
    plt.tight_layout()
    plt.grid()
    plt.savefig('Plots/verhaeltnisse_Salz.pdf')
    plt.close()
예제 #31
0
 def structurfactor(self, h, k, l):
     structurfactor = 0
     for g_1, g_2, g_3 in self.base_vec:
         structurfactor += self.formfaktor * unumpy.cos(
             2 * np.pi * (g_1 * h + g_2 * k + g_3 * l))
     return structurfactor
예제 #32
0
    print(a1, b1)
    print(a2, b2)
    # print(a3, b3)

    with open('build/fitresults.tex', 'w') as f:
        lines = [
            r'\begin{align}',
            r'm_1 &= \num{{{:0.3f} +- {:0.3f}}} & b_1 &= \SI{{{:0.3f} +- {:0.3f}}}{{\nano\meter}} \\'.format(a1.n, a1.s, b1.n, b1.s),
            r'm_2 &= \num{{{:0.3f} +- {:0.3f}}} & b_2 &= \SI{{{:0.3f} +- {:0.3f}}}{{\nano\meter}}'.format(a2.n, a2.s, b2.n, b2.s),
            r'\end{align}',
        ]
        f.write('\n'.join(lines) + '\n')

    a = (a1 + a2) / 2

    delta_h = unp.cos(unp.arctan(a)) * (b1 - b2)
    print(delta_h)
    with open('build/height.tex', 'w') as f:
        f.write(r'\SI{{{:.1f} +- {:.1f}}}{{\pico\meter}}'.format(
            delta_h.n * 1000, delta_h.s * 1000)
        )
        f.write('\n')


    grid_constant_gold = 407.82
    step_factor =  np.sqrt(3)*delta_h*1000/grid_constant_gold
    print(step_factor)
    with open('build/step_factor.tex', 'w') as f:
        f.write(r'\num{{{:.1f} +- {:.1f}}}'.format(
            step_factor.n, step_factor.s)
        )
예제 #33
0
#!/usr/bin/env python

#example taken from https://pypi.python.org/pypi/uncertainties/3.0.1
from uncertainties import ufloat
x = ufloat(2, 0.25)
print x
square = x**2  # Transparent calculations
print square
print square.nominal_value
print square.std_dev  # Standard deviation
print square - x*x
from uncertainties.umath import *  # sin(), etc.
print sin(1+x**2)
print (2*x+1000).derivatives[x]  # Automatic calculation of derivatives
from uncertainties import unumpy  # Array manipulation
random_vars = unumpy.uarray([1, 2], [0.1, 0.2])
print random_vars
print random_vars.mean()
print unumpy.cos(random_vars)
예제 #34
0
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
from uncertainties import ufloat
from scipy.stats import linregress
import uncertainties.unumpy as unp

phi, lamda, t = np.genfromtxt('Daten/eichung.txt', unpack=True)
phi *= (1 / 360) * 2 * np.pi  #in rad umrechnen

phi_01 = np.array([phi[0], phi[1]])  #phi in array
#print(phi_12, np.mean(phi_12), np.std(phi_12))
phi_gem1 = ufloat(np.mean(phi_01), np.std(phi_01))  #phi mitteln
lamda_0_1 = lamda[0] - lamda[1]

eich1 = (abs(lamda[0] - lamda[1]) / (abs(t[0] - t[1])) * unp.cos(phi_gem1)
         )  #erste eichgroesse
print(eich1)

phi_23 = np.array([phi[2], phi[3]])
#print(phi_12, np.mean(phi_12), np.std(phi_12))
phi_gem2 = ufloat(np.mean(phi_23), np.std(phi_23))
lamda_2_3 = lamda[2] - lamda[3]

eich2 = (abs(lamda[2] - lamda[3]) / (abs(t[2] - t[3])) * unp.cos(phi_gem2))
print(eich2)

eichgroesse = (1 / 2) * (eich1 + eich2)
print(eichgroesse)
np.savetxt(
    'build/eichgroesse.txt',
예제 #35
0
#!/usr/bin/env python

#example taken from https://pypi.python.org/pypi/uncertainties/3.0.1
from uncertainties import ufloat
x = ufloat(2, 0.25)
print x
square = x**2  # Transparent calculations
print square
print square.nominal_value
print square.std_dev  # Standard deviation
print square - x * x
from uncertainties.umath import *  # sin(), etc.
print sin(1 + x**2)
print(2 * x + 1000).derivatives[x]  # Automatic calculation of derivatives
from uncertainties import unumpy  # Array manipulation
random_vars = unumpy.uarray([1, 2], [0.1, 0.2])
print random_vars
print random_vars.mean()
print unumpy.cos(random_vars)
def delta_lambda(phi1,phi2,s):
    return unp.cos(phimittelwert(phi1,phi2))*eichzahl*s
예제 #37
0
########## Aufgabenteil b) ##########
# Kalibrierung des Okularmikrometers
lambda_kalibrierung = np.array([438.8, 447.1, 501.6, 504.8]) * 1e-9  # in m
Eichgroesse = unp.uarray(
    np.zeros(np.size(lambda_kalibrierung) / 2), np.zeros(np.size(lambda_kalibrierung) / 2)
)  # in m Skt^(-1)     Skt = Sektor
phi_mean = unp.uarray(np.zeros(np.size(phi_kalib) / 2), np.zeros(np.size(phi_kalib) / 2))  # in rad
eichgroesse_mit_fehler = ufloat(0, 0)  # in m Skt^(-1)     Skt = Sektor
i = 0
for eichgroesse in Eichgroesse:
    j = 2 * i  # index für die 2*size(Eichgroesse) arrays, in unserem Fall arrays mit 4 Einträgen
    phi_mean[i] = ufloat(
        np.mean(phi_kalib[j : j + 2]), np.std(phi_kalib[j : j + 2])
    )  # Indizierung für i= 0: von 0 bis < 2  also 0 bis 1, dh. wir bilden Mittelwert aus zwei Werten
    Eichgroesse[i] = np.abs(lambda_kalibrierung[j] - lambda_kalibrierung[j + 1]) / (
        np.abs(t_kalib[j] - t_kalib[j + 1]) * unp.cos(phi_mean[i])
    )  # Formel aus "zu b:"
    eichgroesse_mit_fehler += Eichgroesse[i]
    i += 1
eichgroesse_mit_fehler *= 1 / (np.size(lambda_kalibrierung) / 2)  # in m
write("build/Eichgroesse.tex", make_SI(eichgroesse_mit_fehler * 1e9, r"\nano\meter", figures=1))

# Tabelle für LaTeX:
phi1 = np.array([phi_kalib[0], phi_kalib[2]])  # crappy weil hart codiert aber was will man machen
phi2 = np.array([phi_kalib[1], phi_kalib[3]])  # in rad
lambda1 = [lambda_kalibrierung[0] * 1e9, lambda_kalibrierung[2] * 1e9]  # in nm
lambda2 = [lambda_kalibrierung[1] * 1e9, lambda_kalibrierung[3] * 1e9]  # in nm
t1 = [t_kalib[0], t_kalib[2]]
t2 = [t_kalib[1], t_kalib[3]]
write(
    "build/Tabelle_b.tex", make_table([-phi1, lambda1, t1, -phi2, lambda2, t2, -phi_mean], [3, 1, 1, 3, 1, 1, 1])
예제 #38
0
w_G_error = unp.std_devs(w_G)

d = unp.uarray([403.609], [9.666]) * 1e-9
a = unp.uarray(data[1:, 3], [0.05])
a_value = unp.nominal_values(a)
a_error = unp.std_devs(a)
f = unp.uarray(300, 10)
lamda = d * (unp.sin(unp.radians(w_G)) -
             unp.sin(unp.radians(w_G) + unp.radians(w_B)))
lamda_value = unp.nominal_values(lamda)
lamda_error = unp.std_devs(lamda)
delta_beta = a / f

delta_beta_value = unp.nominal_values(delta_beta)
delta_beta_error = unp.std_devs(delta_beta)
delta_lamda = d * unp.cos(unp.radians(w_G) + unp.radians(w_B)) * delta_beta
delta_lamda_value = unp.nominal_values(delta_lamda)
delta_lamda_error = unp.std_devs(delta_lamda)
print(
    '\nFarbe & $\lambda$ / nm & Abstand a / mm &$\Delta \beta$ / 10^{-3}^{\circ}$ & $\Delta \lambda$ / nm\\\\'
)
for i in range(0, len(w_B)):
    print('%s & %.3f\pm%.3f & %.1f\pm %.1f & %.3f\pm%.3f & %.3f\pm%.3f\\\\' %
          (Farbe[i], lamda_value[i] * 1e9, lamda_error[i] * 1e9, a_value[i],
           a_error[i], delta_beta_value[i] * 1e3, delta_beta_error[i] * 1e3,
           -delta_lamda_value[i] * 1e9, delta_lamda_error[i] * 1e9))

print('\nFarbe & $w_B$ / $^\circ$ & $w_G$ / $^\circ$ & Abstand a / mm\\\\')
for i in range(0, len(w_B)):
    print('%s & %.1f\pm %.1f & %.1f\pm %.1f & %.1f\pm%.1f\\\\' %
          (Farbe[i], w_B_value[i], w_B_error[i], w_G_value[i], w_G_error[i],
def eichgr(lam1,lam2,delta_t,phi1,phi2):
 phimitt = unp.uarray([np.average([phi1,phi2])],[np.std([phi1,phi2])])
 print('phi12',phimitt)
 print('delta t',delta_t)
 return((lam1-lam2)/(delta_t*unp.cos(phimitt)))