Beispiel #1
0
    def diag_likelihood(self, N, p00, p01, p10):
        """
        returns the value of the likelihood function, which is given by
        a multinomial PDF (results being now parameters and the probabilities
        the variables) multiplied by the readout error. 
        p11 is given by 1-p00-p01-p10.
        """
        N = N.astype(int)
        perr00, perr01, perr10, perr11 = self._apply_readout_error(
            p00, p01, p10, 1. - p00 - p01 - p10)

        lk = fac(N.sum(), exact=self.fac_exact) / \
                (fac(N[0],exact=self.fac_exact) * \
                fac(N[1],exact=self.fac_exact) * \
                fac(N[2],exact=self.fac_exact) * \
                fac(N[3],exact=self.fac_exact)) * \
                perr00**N[0] * perr01**N[1] * perr10**N[2] * \
                (1.-perr00-perr01-perr10)**N[3]

        if type(p00) == np.ndarray:
            lk[p00 + p01 + p10 > 1] = 0.
            lk[p00 < 0] = 0
            lk[p01 < 0] = 0
            lk[p10 < 0] = 0
        elif p00 + p01 + p10 > 1. or p00 < 0 or p01 < 0 or p10 < 0:
            return 0
        return lk
Beispiel #2
0
    def offdiag_likelihood(self, N, a, b):
        """
        the probabilities for the XX measurement have some constraints, and are
        in the end described by the parameters a and b (see lab book)
        """
        N = N.astype(int)
        perr00,perr01,perr10,perr11 = self._apply_readout_error(
                .25+a-b,
                .25-a-b,
                .25-a+b,
                .25+a+b)

        lk = fac(N.sum(), exact=self.fac_exact) / \
                (fac(N[0],exact=self.fac_exact) * \
                fac(N[1],exact=self.fac_exact) * \
                fac(N[2],exact=self.fac_exact) * \
                fac(N[3],exact=self.fac_exact)) * \
                perr00**N[0] * perr01**N[1] * perr10**N[2] * \
                (1.-perr00-perr01-perr10)**N[3]
        
        if type(a) == np.ndarray:
            lk[abs(b) > .25-abs(a)] = 0.
        elif abs(b) > .25-abs(a):
            return 0
        return lk
Beispiel #3
0
def P0(l):  #Find the integral of P0l
    if l % 2 == 0: return 0
    Sum = 0
    for q in range(ceil(l / 2), l + 1):
        Sum += fac(2 * q) * fac2(2 * q - l - 1) / fac(
            (l - q) * fac(q) * fac(2 * q - l) * fac2(2 * q - l))
    return 1 / (2**l) * Sum
Beispiel #4
0
def zer_coeff(n, m):
    coeffs, pows = [], []

    for s in range((n - m) / 2 + 1):
        coeffs.append((-1.0)**s * fac(n-s) / \
                          (fac(s) * fac((n+m)/2.0 - s) * fac((n-m)/2.0 - s)))
        pows.append(n - 2.0 * s)
    return coeffs, pows
def radialPoly(rho, n,m):
    rp = 0
    m=np.abs(m)
    if is_odd(n-m):
        rp = 0
    else:
        for k in range(0,(n-m)/2):
            rp += (-1.0)**k * fac(n-k) * rho**(n-2.0*k) / (np.math.factorial(k) * fac((n+m)/2.0 - k) * fac((n-m)/2.0 - k)) 
    return rp
Beispiel #6
0
def zernike_rad(l, n, r):
    res = np.zeros(r.shape)
    if (n - l) % 2:
        return res
    for i in xrange((n - l) / 2 + 1):
        res += (
            r ** (n - 2.0 * i) * (-1.0) ** i * fac(n - i) / (fac(i) * fac((n + l) / 2.0 - i) * fac((n - l) / 2.0 - i))
        )
    return res
Beispiel #7
0
def R(m, n, rad, orig, Nx):
    ''' n>=m, n-m even '''
    rho = getrho(rad, orig, Nx)
    bigr = N.zeros((Nx, Nx), dtype=N.float32)
    for s in range(1 + int((n - m) / 2)):
        coeff = (-1)**s * fac(n - s) / (fac(s) * fac((n + m) / 2 - s) *
                                        fac((n - m) / 2 - s))
        bigr = bigr + coeff * rho**(n - 2 * s)
    bigr = bigr * (rho <= 1.0)
    return bigr
Beispiel #8
0
def zernike_rad(m, n, rho):
    """radial component of zernike (m,n), given radial coordinates rho"""
    wf = np.zeros(rho.shape)  # grid of radial coords
    if (np.mod(n - m, 2) == 1):
        return rho * 0.0
    for k in range((n - m) / 2 + 1):
        wf += rho**(n-(2.0*k)) * ((-1.0)**k) * fac(n-k) / \
        ( fac(k) * fac( (n+m)/2.0 - k ) * \
        fac( (n-m)/2.0 - k ) )
        return wf
Beispiel #9
0
def zernike_rad(m, n, rho):
    """
    Calculate the radial component of Zernike polynomial (m, n) 
    given a grid of radial coordinates rho.
    """
    if (n < 0 or m < 0 or abs(m) > n):
        raise ValueError
    if ((n-m) % 2):
        return rho*0.0
    pre_fac = lambda k: (-1.0)**k * fac(n-k) / ( fac(k) * fac( (n+m)/2.0 - k ) * fac( (n-m)/2.0 - k ) )
    return sum(pre_fac(k) * rho**(n-2.0*k) for k in xrange((n-m)/2+1))
Beispiel #10
0
 def zernike_rad(self, rho):
     n=abs(self.n)
     m=abs(self.m)
     if (numpy.mod(n-m, 2) == 1):
         return rho*0.0
     
     wf = rho*0.0
     for k in range((n-m)/2+1):
         wf += rho**(n-2.0*k) * (-1.0)**k * fac(n-k) / ( fac(k) * fac( (n+m)/2.0 - k ) * fac( (n-m)/2.0 - k ) )
     
     return wf
def zernike_rad(m, n, rho):
    """
    Calculate the radial component of Zernike polynomial (m, n)
    given a grid of radial coordinates rho.
    """
    wf = N.zeros(rho.shape)
    if (n-m) % 2:
        return wf
    for k in xrange((n-m)/2+1):
        wf += rho**(n-2.0*k) * (-1.0)**k * fac(n-k) / ( fac(k) * fac( (n+m)/2.0 - k ) * fac( (n-m)/2.0 - k ) )
        return wf
Beispiel #12
0
 def _radzernike(self, m, n, r):
     """
     Calculate the radial part of the Zernike polynomials
     """
     if (np.mod(n - m, 2) == 1):
         return np.zeros_like(r)
     wf = np.zeros_like(r)
     for k in range((n - m) // 2 + 1):
         wf += r**(n - 2.0 * k) * (-1.0)**k * fac(n - k) / (fac(k) * fac(
             (n + m) / 2.0 - k) * fac((n - m) / 2.0 - k))
     return wf
Beispiel #13
0
 def zernike_rad(self, m, n, rho):
     """
     Calculate the radial component of Zernike polynomial (m, n) 
     given a grid of radial coordinates rho.
     """
     if (n < 0 or m < 0 or abs(m) > n):
         raise ValueError
     if ((n-m) % 2):
         return rho*0.0
     pre_fac = lambda k: (-1.0)**k * fac(n-k) / ( fac(k) * fac( (n+m)/2.0 - k ) * fac( (n-m)/2.0 - k ) )
     return sum(pre_fac(k) * rho**(n-2.0*k) for k in xrange((n-m)/2+1))
def zernike_rad(m, n, rho):
    """
    Calculate the radial component of Zernike polynomial (m, n)
    given a grid of radial coordinates rho.
    """
    wf = N.zeros(rho.shape)
    if (n - m) % 2:
        return wf
    for k in xrange((n - m) / 2 + 1):
        wf += rho**(n - 2.0 * k) * (-1.0)**k * fac(n - k) / (fac(k) * fac(
            (n + m) / 2.0 - k) * fac((n - m) / 2.0 - k))
        return wf
Beispiel #15
0
def differential(poly, diffvar):
    """
    Polynomial differential operator.

    Args:
        poly (Poly) : Polynomial to be differentiated.
        diffvar (Poly) : Polynomial to differentiate by. Must be decomposed. If
                polynomial array, the output is the Jacobian matrix.

    Examples:
        >>> q0, q1 = chaospy.variable(2)
        >>> poly = chaospy.Poly([1, q0, q0*q1**2+1])
        >>> print(poly)
        [1, q0, q0q1^2+1]
        >>> print(differential(poly, q0))
        [0, 1, q1^2]
        >>> print(differential(poly, q1))
        [0, 0, 2q0q1]
    """
    poly = Poly(poly)
    diffvar = Poly(diffvar)

    if not chaospy.poly.caller.is_decomposed(diffvar):
        sum(differential(poly, chaospy.poly.caller.decompose(diffvar)))

    if diffvar.shape:
        return Poly([differential(poly, pol) for pol in diffvar])

    if diffvar.dim > poly.dim:
        poly = chaospy.poly.dimension.setdim(poly, diffvar.dim)
    else:
        diffvar = chaospy.poly.dimension.setdim(diffvar, poly.dim)

    qkey = diffvar.keys[0]

    core = {}
    for key in poly.keys:

        newkey = np.array(key) - np.array(qkey)

        if np.any(newkey < 0):
            continue
        newkey = tuple(newkey)
        core[newkey] = poly.A[key] * np.prod([
            fac(key[idx], exact=True) / fac(newkey[idx], exact=True)
            for idx in range(poly.dim)
        ])

    return Poly(core, poly.dim, poly.shape, poly.dtype)
Beispiel #16
0
def differential(poly, diffvar):
    """
    Polynomial differential operator.

    Args:
        poly (Poly) : Polynomial to be differentiated.
        diffvar (Poly) : Polynomial to differentiate by. Must be decomposed. If
                polynomial array, the output is the Jacobian matrix.

    Examples:
        >>> q0, q1 = cp.variable(2)
        >>> poly = cp.Poly([1, q0, q0*q1**2+1])
        >>> print(poly)
        [1, q0, q0q1^2+1]
        >>> print(differential(poly, q0))
        [0, 1, q1^2]
        >>> print(differential(poly, q1))
        [0, 0, 2q0q1]
    """
    poly = Poly(poly)
    diffvar = Poly(diffvar)

    if not chaospy.poly.caller.is_decomposed(diffvar):
        sum(differential(poly, chaospy.poly.caller.decompose(diffvar)))

    if diffvar.shape:
        return Poly([differential(poly, pol) for pol in diffvar])

    if diffvar.dim > poly.dim:
        poly = chaospy.poly.dimension.setdim(poly, diffvar.dim)
    else:
        diffvar = chaospy.poly.dimension.setdim(diffvar, poly.dim)

    qkey = diffvar.keys[0]

    core = {}
    for key in poly.keys:

        newkey = np.array(key) - np.array(qkey)

        if np.any(newkey < 0):
            continue
        newkey = tuple(newkey)
        core[newkey] = poly.A[key] * np.prod(
            [fac(key[idx], exact=True) / fac(newkey[idx], exact=True)
             for idx in range(poly.dim)])

    return Poly(core, poly.dim, poly.shape, poly.dtype)
Beispiel #17
0
 def get_mu(mu_t, L_t):
     """ Computes mu_{t+1}
     """
     coeffs = (1.0 / L_t) * np.array(
         [pow(mu_t, i) / (fac(i)) for i in np.arange(d + 1)])
     polys = np.array([get_moment(mu_t, i) for i in np.arange(d + 1)])
     return kappa * sum(np.multiply(coeffs, polys))
def goodfunform(x, s, c0, c1, c2, c3, c4, c5, n, L, Alow, Aupp, lam):
    numpeaks = 10
    dx = x[1] - x[0]
    cent = [c0, c1, c2, c3, c4, c5] + list(np.arange(1, 2 * numpeaks) + c5)
    A1 = 1 - Alow - Aupp
    norm = [
        hnorm(m=value, A=np.array([A1, Alow, Aupp]), c=cent)
        for value in range(1, numpeaks)
    ]
    amp = np.array([
        np.exp(-lam) * lam**(value) / fac(value) for value in range(numpeaks)
    ])
    yvalues = [
        hfit(x, value, np.array([A1, Alow, Aupp]), cent)
        for value in range(1, numpeaks)
    ]
    peakform = np.sum(
        [yvalues[value - 1] * amp[value] for value in range(1, numpeaks)],
        axis=0)
    peakform = np.convolve(gaussian(np.arange(-2, 2, dx), 0, s), peakform,
                           'same')
    peakform = peakform + np.sum([
        gaussian(x, cent[value - 1], s) * amp[value] * A1**value /
        norm[value - 1] for value in range(1, numpeaks)
    ],
                                 axis=0)
    return L * (peakform + amp[0] * gzero(x, c0, s, n))
Beispiel #19
0
def zernike_rad(m, n, rho):
    """
    Make radial Zernike polynomial on coordinate grid **rho**.
    @param [in] m Radial Zernike index
    @param [in] n Azimuthal Zernike index
    @param [in] rho Radial coordinate grid
    @return Radial polynomial with identical shape as **rho**
    """
    if (np.mod(n - m, 2) == 1):
        return rho * 0.0

    wf = rho * 0.0
    for k in range((n - m) / 2 + 1):
        wf += rho**(n-2.0*k) * (-1.0)**k * fac(n-k) / \
          ( fac(k) * fac( (n+m)/2.0 - k ) * fac( (n-m)/2.0 - k ) )

    return wf
Beispiel #20
0
def zernike_rad(m, n, rho):
	"""
	Make radial Zernike polynomial on coordinate grid **rho**.

	@param [in] m Radial Zernike index
	@param [in] n Azimuthal Zernike index
	@param [in] rho Radial coordinate grid
	@return Radial polynomial with identical shape as **rho**
	"""
	if (np.mod(n-m, 2) == 1):
		return rho*0.0

	wf = rho*0.0
	for k in range((n-m)/2+1):
		wf += rho**(n-2.0*k) * (-1.0)**k * fac(n-k) / ( fac(k) * fac( (n+m)/2.0 - k ) * fac( (n-m)/2.0 - k ) )

	return wf
Beispiel #21
0
def zernike_rad(m, n, rho):
    """
    Calculate the radial component of Zernike polynomial (m, n) 
    given a grid of radial coordinates rho.
    """

    #Todo: This could be sped up A LOT by caching all this factorial stuff

    if (n < 0 or m < 0 or abs(m) > n):
        raise ValueError

    if ((n - m) % 2):
        return rho * 0.0

    pre_fac = lambda k: (-1.0)**k * fac(n - k) / (fac(k) * fac(
        (n + m) / 2.0 - k) * fac((n - m) / 2.0 - k))

    return np.sum(
        pre_fac(k) * rho**(n - 2.0 * k) for k in xrange((n - m) / 2 + 1))
def zernike_rad(rho, n,m):
    """
    Calculate the radial component of Zernike polynomial (m, n) 
    given a grid of radial coordinates rho.
    
    >>> zernike_rad(3, 3, 0.333)
    0.036926037000000009
    >>> zernike_rad(1, 3, 0.333)
    -0.55522188900000002
    >>> zernike_rad(3, 5, 0.12345)
    -0.007382104685237683
    """
    
    if (n < 0 or m < 0 or abs(m) > n):
        raise ValueError
    
    if ((n-m) % 2):
        return rho*0.0
    else:
        pre_fac = lambda k: (-1.0)**k * fac(n-k) / ( fac(k) * fac( (n+m)/2.0 - k ) * fac( (n-m)/2.0 - k ) )
        return sum(pre_fac(k) * rho**(n-2.0*k) for k in xrange((n-m)/2+1))
Beispiel #23
0
def differential(P, Q):
    """Polynomial differential operator

Parameters
----------
P : Poly
    Polynomial to be differentiated.
Q : Poly
    Polynomial to differentiate by. Must be decomposed. If
    polynomial array, the output is the Jacobian matrix.
    """
    P, Q = Poly(P), Poly(Q)

    if not is_decomposed(Q):
        differential(decompose(Q)).sum(0)

    if Q.shape:
        return Poly([differential(P, q) for q in Q])

    if Q.dim > P.dim:
        P = setdim(P, Q.dim)
    else:
        Q = setdim(Q, P.dim)

    qkey = Q.keys[0]

    A = {}
    for key in P.keys:

        newkey = np.array(key) - np.array(qkey)

        if np.any(newkey < 0):
            continue

        A[tuple(newkey)] = P.A[key]*np.prod([fac(key[i], \
            exact=True)/fac(newkey[i], exact=True) \
            for i in xrange(P.dim)])

    return Poly(A, P.dim, None)
Beispiel #24
0
def differential(P, Q):
    """Polynomial differential operator

Parameters
----------
P : Poly
    Polynomial to be differentiated.
Q : Poly
    Polynomial to differentiate by. Must be decomposed. If
    polynomial array, the output is the Jacobian matrix.
    """
    P, Q = Poly(P), Poly(Q)

    if not is_decomposed(Q):
        differential(decompose(Q)).sum(0)

    if Q.shape:
        return Poly([differential(P, q) for q in Q])

    if Q.dim > P.dim:
        P = setdim(P, Q.dim)
    else:
        Q = setdim(Q, P.dim)

    qkey = Q.keys[0]

    A = {}
    for key in P.keys:

        newkey = np.array(key) - np.array(qkey)

        if np.any(newkey < 0):
            continue

        A[tuple(newkey)] = P.A[key] * np.prod(
            [fac(key[i], exact=True) / fac(newkey[i], exact=True) for i in xrange(P.dim)]
        )

    return Poly(A, P.dim, None)
Beispiel #25
0
    def offdiag_likelihood(self, N, a, b):
        """
        the probabilities for the XX measurement have some constraints, and are
        in the end described by the parameters a and b (see lab book)
        """
        N = N.astype(int)
        perr00, perr01, perr10, perr11 = self._apply_readout_error(
            .25 + a - b, .25 - a - b, .25 - a + b, .25 + a + b)

        lk = fac(N.sum(), exact=self.fac_exact) / \
                (fac(N[0],exact=self.fac_exact) * \
                fac(N[1],exact=self.fac_exact) * \
                fac(N[2],exact=self.fac_exact) * \
                fac(N[3],exact=self.fac_exact)) * \
                perr00**N[0] * perr01**N[1] * perr10**N[2] * \
                (1.-perr00-perr01-perr10)**N[3]

        if type(a) == np.ndarray:
            lk[abs(b) > .25 - abs(a)] = 0.
        elif abs(b) > .25 - abs(a):
            return 0
        return lk
def zernike_rad(m, n, rho):
	"""
	Calculate the radial component of Zernike polynomial (m, n) 
	given a grid of radial coordinates rho.
	
	>>> zernike_rad(3, 3, 0.333)
	0.036926037000000009
	>>> zernike_rad(1, 3, 0.333)
	-0.55522188900000002
	>>> zernike_rad(3, 5, 0.12345)
	-0.007382104685237683
	"""
	
	if (n < 0 or m < 0 or abs(m) > n):
		raise ValueError
	
	if ((n-m) % 2):
		return rho*0.0
	
	pre_fac = lambda k: (-1.0)**k * fac(n-k) / ( fac(k) * fac( (n+m)/2.0 - k ) * fac( (n-m)/2.0 - k ) )
	
	return sum(pre_fac(k) * rho**(n-2.0*k) for k in xrange((n-m)/2+1))
Beispiel #27
0
def differential(P, Q):
    """
    Polynomial differential operator.

    Args:
        P (Poly) : Polynomial to be differentiated.
        Q (Poly) : Polynomial to differentiate by. Must be decomposed. If
                polynomial array, the output is the Jacobian matrix.
    """
    P, Q = Poly(P), Poly(Q)

    if not chaospy.poly.is_decomposed(Q):
        differential(chaospy.poly.decompose(Q)).sum(0)

    if Q.shape:
        return Poly([differential(P, q) for q in Q])

    if Q.dim > P.dim:
        P = chaospy.poly.setdim(P, Q.dim)
    else:
        Q = chaospy.poly.setdim(Q, P.dim)

    qkey = Q.keys[0]

    A = {}
    for key in P.keys:

        newkey = numpy.array(key) - numpy.array(qkey)

        if numpy.any(newkey < 0):
            continue

        A[tuple(newkey)] = P.A[key]*numpy.prod([fac(key[i], \
            exact=True)/fac(newkey[i], exact=True) \
            for i in range(P.dim)])

    return Poly(B, P.dim, P.shape, P.dtype)
Beispiel #28
0
    def diag_likelihood(self, N, p00,p01,p10):
        """
        returns the value of the likelihood function, which is given by
        a multinomial PDF (results being now parameters and the probabilities
        the variables) multiplied by the readout error. 
        p11 is given by 1-p00-p01-p10.
        """
        N = N.astype(int)
        perr00,perr01,perr10,perr11 = self._apply_readout_error(
                p00,p01,p10,1.-p00-p01-p10)
      
        lk = fac(N.sum(), exact=self.fac_exact) / \
                (fac(N[0],exact=self.fac_exact) * \
                fac(N[1],exact=self.fac_exact) * \
                fac(N[2],exact=self.fac_exact) * \
                fac(N[3],exact=self.fac_exact)) * \
                perr00**N[0] * perr01**N[1] * perr10**N[2] * \
                (1.-perr00-perr01-perr10)**N[3]

        if type(p00) == np.ndarray:
            lk[p00+p01+p10>1]=0.; lk[p00<0]=0; lk[p01<0]=0; lk[p10<0]=0
        elif p00+p01+p10 > 1. or p00<0 or p01<0 or p10<0:
            return 0
        return lk
Beispiel #29
0
    def poly(z, l):
        """ Computes the sequence of polynomials from the algorithm.

        Args:
            z: np.array to be evaluated
            l: Step Index
        Returns:
            The l-th Polynomial evaluated pointise on z
        """
        if not l:
            return np.ones(z.shape)
        coeffs = (1.0 / L_list[l]) * np.array(
            [pow(mu_list[l], k) / (fac(k)) for k in np.arange(d + 1)])
        pows = np.arange(d + 1) * np.ones(z.shape + (d + 1, ))
        polys = np.power(np.expand_dims(z, 2), pows)
        return np.sum((coeffs * polys).T, 0).T
Beispiel #30
0
    def get_L(mu_t, d):
        """ Returns L_t.
        """
        # ai = u_l^k / k!
        # sum_{i+j is even}} ai aj (i+j-1)!!
        a = np.array([pow(mu_t, k) / fac(k) for k in np.arange(d + 1)])

        # compute all the moments up to 2*d
        E = np.zeros(2 * d + 1)
        for i in np.arange(d + 1):
            E[2 * i] = fac2(2 * i - 1)

        H = np.zeros((d + 1, d + 1))
        for i in np.arange(d + 1):
            for j in np.arange(d + 1):
                H[i, j] = E[i + j]

        L2 = np.dot(a, np.dot(H, a))
        return math.sqrt(L2)
def Taylor(x, x0, n):
    p = y0[0]
    for i in range(1, n+1):
        p += ((y0[i]) / (fac(i))) * (x-x0)**i
    return p
def factorial(number):
    return fac(number,True)
def Amijn(A, m, i, j, n):
    A1, Alow, Aupp = A
    numerator = (A1**i) * (Alow**j) * Aupp**(m - i - j) * (-1)**(m - i - n) * (
        m - i) * fac(m)
    denominator = fac(i) * fac(j) * fac(m - i - j) * fac(n) * fac(m - i - n)
    return numerator / denominator
def Jb_spline(X,n=0):
    """Jb interpolated from a saved spline. Input is (m/T)^2."""
    X = numpy.array(X, copy=False)
    x = X.ravel()
    y = interpolate.splev(x,_tckb, der=n).ravel()
    y[x < _xbmin] = interpolate.splev(_xbmin,_tckb, der=n)
    y[x > _xbmax] = 0
    return y.reshape(X.shape)


# Now for the low x expansion (require that n <= 50)
a,b,c,d = -pi**4/45, pi*pi/12, -pi/6, -1/32.
logab = 1.5 - 2*euler_gamma + 2*log(4*pi)
l = numpy.arange(50)+1
g = (-2*pi**3.5 * (-1)**l*(1+special.zetac(2*l+1)) *
     special.gamma(l+.5)/(fac(l+2)*(2*pi)**(2*l+4)))
lowCoef_b = (a,b,c,d,logab,l,g)
del (a,b,c,d,logab,l,g)  # clean up name space

a,b,d = -7*pi**4/360, pi*pi/24, 1/32.
logaf = 1.5 - 2*euler_gamma + 2*log(pi)
l = numpy.arange(50)+1
g = (.25*pi**3.5 * (-1)**l*(1+special.zetac(2*l+1)) *
     special.gamma(l+.5)*(1-.5**(2*l+1))/(fac(l+2)*pi**(2*l+4)))
lowCoef_f = (a,b,d,logaf,l,g)
del (a,b,d,logaf,l,g)  # clean up name space


def Jb_low(x,n=20):
    """Jb calculated using the low-x (high-T) expansion."""
    (a,b,c,d,logab,l,g) = lowCoef_b
def funform(x, s, c0, c1, c2, c3, c4, c5, n, L, Lbulk, Lsurf, Alow, Aupp, lam):
    numpeaks = 5
    cent = [c0, c1, c2, c3, c4, c5] + list(np.arange(1, 2 * numpeaks) + c5)
    dx = x[1] - x[0]
    A1 = 1 - Alow - Aupp
    L0 = 1 - Lbulk - Lsurf
    theta = np.heaviside
    adx = np.sum((cent[0] <= x) & (x < cent[1]))

    # Amplitudes of the Gaussian
    amp = [
        np.exp(-lam) * lam**(value) / fac(value) for value in range(numpeaks)
    ]
    L = L / sum(
        amp
    )  # removes artifact of missing counts by redistributing evenly over all other energies

    # Events that 'pile-up' with a 0 event:
    yvalues = [
        hfit(x, value, np.array([A1, Alow, Aupp]), cent)
        for value in range(1, numpeaks)
    ]
    peakform = L0 * np.sum(
        [yvalues[value - 1] * amp[value] for value in range(1, numpeaks)],
        axis=0)

    #one = np.sum(peakform, axis = 0)/L0
    #print('One', np.sum(peakform, axis = 0), one*L0)

    # Events that 'Pile-up' with a surface event:
    yvalues = [
        hfit(x - cent[0], value, np.array([A1, Alow, Aupp]), cent)
        for value in range(1, numpeaks)
    ]
    peakform = peakform + Lsurf * np.sum(
        [yvalues[value - 1] * amp[value] for value in range(1, numpeaks)],
        axis=0)

    #print('Two', np.sum(peakform, axis = 0), one*(L0 + Lsurf))

    # Events that 'Pile-up' with a bulk event:
    yvalues = np.zeros(x.size)
    for value in range(1, numpeaks):
        temp = np.zeros(x.size)
        temp[(cent[value - 1] <= x) & (x < cent[value])] = 1
        yvalues = yvalues + amp[value] * temp / sum(temp)

    peakform = peakform + Lbulk * yvalues

    #print('Three', np.sum(peakform, axis = 0), one*(L0 + Lsurf + Lbulk))
    norm = [
        hnorm(m=value, A=np.array([A1, Alow, Aupp]), c=cent)
        for value in range(1, numpeaks)
    ]
    peakform = np.convolve(gaussian(np.arange(-2, 2, dx), 0, s), peakform,
                           'same')
    peakform = (peakform + np.sum([
        gaussian(x, cent[value - 1], s) * amp[value] * A1**value /
        norm[value - 1] * L0 for value in range(1, numpeaks)
    ],
                                  axis=0) +
                np.sum([
                    gaussian(x - cent[0], cent[value - 1], s) * amp[value] *
                    A1**value / norm[value - 1] * Lsurf
                    for value in range(1, numpeaks)
                ],
                       axis=0))

    #print('Four', np.sum(peakform, axis = 0), (L0 + Lbulk + Lsurf)*sum(amp[1:]))
    return L * (peakform + fitfun(x, s, c0, c1, n, amp[0], Lbulk, Lsurf))
Beispiel #36
0
def Jb_spline(X, n=0):
    """Jb interpolated from a saved spline. Input is (m/T)^2."""
    X = numpy.array(X, copy=False)
    x = X.ravel()
    y = interpolate.splev(x, _tckb, der=n).ravel()
    y[x < _xbmin] = interpolate.splev(_xbmin, _tckb, der=n)
    y[x > _xbmax] = 0
    return y.reshape(X.shape)


# Now for the low x expansion (require that n <= 50)
a, b, c, d = -pi**4 / 45, pi * pi / 12, -pi / 6, -1 / 32.
logab = 1.5 - 2 * euler_gamma + 2 * log(4 * pi)
l = numpy.arange(50) + 1
g = (-2 * pi**3.5 * (-1)**l * (1 + special.zetac(2 * l + 1)) *
     special.gamma(l + .5) / (fac(l + 2) * (2 * pi)**(2 * l + 4)))
lowCoef_b = (a, b, c, d, logab, l, g)
del (a, b, c, d, logab, l, g)  # clean up name space

a, b, d = -7 * pi**4 / 360, pi * pi / 24, 1 / 32.
logaf = 1.5 - 2 * euler_gamma + 2 * log(pi)
l = numpy.arange(50) + 1
g = (.25 * pi**3.5 * (-1)**l * (1 + special.zetac(2 * l + 1)) *
     special.gamma(l + .5) * (1 - .5**(2 * l + 1)) /
     (fac(l + 2) * pi**(2 * l + 4)))
lowCoef_f = (a, b, d, logaf, l, g)
del (a, b, d, logaf, l, g)  # clean up name space


def Jb_low(x, n=20):
    """Jb calculated using the low-x (high-T) expansion."""
Beispiel #37
0
def redo_traceplots(config,prior,Xt,Yt,TH,LLH):
    ''' plots a new chisq and a new prior + likelihood plot '''
    chisq = []
    llh   = LLH[:][config.burn+1::config.thin]
    prior_list_1 = []
    prior_list_2 = []
    prior_rlw = []
    for th in TH:
        J = len(th)
        #llh_temp,exp_counts,chisq_temp = code3.llh(th,config,prior,Xt,Yt, 10000., p_thin =1.)
        
      #  llh.append(llh_temp)
        #chisq.append( chisq_temp)       

        prior_list_1.append( J*np.log(prior.alpha) - prior.beta*np.sum(th[:,1]) - np.log(fac(J)) - np.log(np.product(th[:,1])) )       
        prior_temp = 0
        prior_rlw_temp = 0
        for th_j in th:
            mb = code3.eval_prior(th_j, config,prior)
            prior_temp +=  mb
            
            prior_rlw_temp += ( -np.log(2*3.14*prior.sigma_gamma*prior.s_Epeak/prior.scale_alpha) 
                                + th_j[2]**2/(2*prior.sigma_gamma**2) + th_j[3] + prior.scale_alpha*th_j[4] + (th_j[6] - prior.mu_Epeak)**2/(2*prior.s_Epeak**2)
                                + J * np.log(prior.alpha) )
            
        prior_list_2.append(prior_temp)
        prior_rlw.append(prior_rlw_temp)
        
        
        
        
    llh = np.array(llh)
    prior_list_1 = np.array(prior_list_1)
    prior_list_2 = np.array(prior_list_2)
    prior_mb = prior_list_1 + prior_list_2 - 50
    
    
    
  #  prior_list =np.array(prior_list)
    llh = llh - np.max(llh)
   # prior_list = prior_list - np.max(prior_list)
 #   posterior = llh[:,0] + prior_list
        
    mb = np.arange(config.burn,config.M,config.thin)
    #plt.figure()
    #plt.plot(mb,chisq)
    #plt.xlabel('MCMC iterations (thinned)')
    #plt.ylabel(r'$\chi^2$')
    #plt.title(r'$\chi^2$ for All Chains')
    #plt.tight_layout()
    #plt.show()
    #plt.savefig('chisq_new.png')
   # print np.shape(mb), np.shape(prior_list), np.shape(llh), np.shape(posterior)
    plt.figure()
    plt.plot(mb,llh)
    plt.plot(mb,prior_mb)
    plt.plot(mb,prior_rlw)
    plt.legend(['LLH',r'Log-prior MB',r'Log-prior RLW'], loc = 3)
   # plt.legend(['LLH',r'Log-prior $\nu_x \times \nu_u$',r'Log-prior $\nu_a$'], loc = 3)
    plt.xlabel('MCMC iterations (thinned)')
    plt.title('Log-densities')
    plt.tight_layout()
    plt.ylim([-200,0])
    plt.show()
    plt.savefig('densities.png')