jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def computeIncTheta(self, x0, x1, M):
        ''' Compute increment of rotation between x0 and x1.

        :param x0: interval beginning.
        :param x1: interval end.
        :param M: bending moment function.
        '''
        x= self.samplePoints(x0= x0, x1= x1)
        y= self.computeCurvature(xi= x, M=M)
        return scipy.integrate.trapezoid(y, x)
//  [python]
def computeIncDeflection(self, x0, x1, M):
        ''' Compute increment of deflection between x0 and x1.

        :param x0: interval beginning.
        :param x1: interval end.
        :param M: bending moment function.
        '''
        xi= self.samplePoints(x0, x1)    
        first_integral= [0.0]
        xA= xi[0]
        total= 0.0
        for x in xi[1:]:
            total-= self.computeIncTheta(xA, x, M= M)
            first_integral.append(total)
            xA= x
        return scipy.integrate.trapz(first_integral, xi)
//  [python]
def computeIncDeflection(self, x0, x1, M):
        ''' Compute increment of deflection between x0 and x1.

        :param x0: interval beginning.
        :param x1: interval end.
        :param M: bending moment function.
        '''
        xi= self.samplePoints(x0, x1)    
        first_integral= [0.0]
        xA= xi[0]
        total= 0.0
        for x in xi[1:]:
            total-= self.computeIncTheta(xA, x, M= M)
            first_integral.append(total)
            xA= x
        return scipy.integrate.trapezoid(first_integral, xi)
//  [python]
def HWMean(P0T,lambd,eta,T):

    # Time step needed for differentiation

    dt = 0.0001    
    f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2*dt)

    # Initial interest rate is forward rate at time t->0

    r0 = f0T(0.00001)
    theta = Theta(P0T,eta,lambd)
    zGrid = np.linspace(0.0,T,2500)
    temp =lambda z: theta(z) * np.exp(-lambd*(T-z))
    r_mean = r0*np.exp(-lambd*T) + lambd * integrate.trapz(temp(zGrid),zGrid)
    return r_mean
//  [python]
def HWMean(P0T,lambd,eta,T):

    # Time step needed for differentiation

    dt = 0.0001    
    f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2*dt)

    # Initial interest rate is forward rate at time t->0

    r0 = f0T(0.00001)
    theta = Theta(P0T,eta,lambd)
    zGrid = np.linspace(0.0,T,2500)
    temp =lambda z: theta(z) * np.exp(-lambd*(T-z))
    r_mean = r0*np.exp(-lambd*T) + lambd * integrate.trapezoid(temp(zGrid),zGrid)
    return r_mean
//  [python]
def _calculate_lpivot(self):
        if self.transmit.max() <= 0:
            return 0.
        if 'photon' in self.dtype:
            lpivot2 = self._lT / trapz(self.transmit / self._wavelength,
                                       self._wavelength)
        else:
            lpivot2 = self.norm / trapz(self.transmit / self._wavelength ** 2,
                                        self._wavelength)
        return np.sqrt(lpivot2)
//  [python]
def _calculate_lpivot(self):
        if self.transmit.max() <= 0:
            return 0.
        if 'photon' in self.dtype:
            lpivot2 = self._lT / trapezoid(self.transmit / self._wavelength,
                                       self._wavelength)
        else:
            lpivot2 = self.norm / trapezoid(self.transmit / self._wavelength ** 2,
                                        self._wavelength)
        return np.sqrt(lpivot2)
//  [python]
def numeric_integrate(y, x, h=0.1, axis=-1) -> Union[np.ndarray, float]:
    import scipy.integrate as inte
    result = inte.trapz(y, x, h, axis)
    return result
//  [python]
def numeric_integrate(y, x, h=0.1, axis=-1) -> Union[np.ndarray, float]:
    import scipy.integrate as inte
    result = inte.trapezoid(y, x, dx=h, axis=axis)
    return result
//  [python]
def FourierCosineSeries(y,f,N,a,b):
        
    g = np.zeros(len(y))
    for k in range(0,N):
        A_k = 2.0/(b-a) * integrate.trapz(f(y)*np.cos(k*np.pi*(y-a)/(b-a)),y)
        if k == 0:
            A_k = A_k * 0.5
        g = g + A_k*np.cos(k*np.pi*(y-a)/(b-a)) 
    return g
//  [python]
def FourierCosineSeries(y,f,N,a,b):
        
    g = np.zeros(len(y))
    for k in range(0,N):
        A_k = 2.0/(b-a) * integrate.trapezoid(f(y)*np.cos(k*np.pi*(y-a)/(b-a)),y)
        if k == 0:
            A_k = A_k * 0.5
        g = g + A_k*np.cos(k*np.pi*(y-a)/(b-a)) 
    return g
//  [python]
def __init__(self, wavelength, transmit, name='', dtype="photon",
                 unit=None):
        """Constructor"""
        self.name = name
        self.set_dtype(dtype)
        try:   # get units from the inputs
            self._wavelength = wavelength.value
            unit = str(wavelength.unit)
        except AttributeError:
            self._wavelength = wavelength
        self.set_wavelength_unit(unit)

        # make sure input data are ordered and cleaned of weird values.
        idx = np.argsort(self._wavelength)
        self._wavelength = self._wavelength[idx]
        self.transmit   = np.clip(transmit[idx], 0., np.nanmax(transmit))

        self.norm = trapz(self.transmit, self._wavelength)
        self._lT = trapz(self._wavelength * self.transmit, self._wavelength)
        self._lpivot = self._calculate_lpivot()
        if self.norm > 0:
            self._cl = self._lT / self.norm
        else:
            self._cl = 0.
//  [python]
def __init__(self, wavelength, transmit, name='', dtype="photon",
                 unit=None):
        """Constructor"""
        self.name = name
        self.set_dtype(dtype)
        try:   # get units from the inputs
            self._wavelength = wavelength.value
            unit = str(wavelength.unit)
        except AttributeError:
            self._wavelength = wavelength
        self.set_wavelength_unit(unit)

        # make sure input data are ordered and cleaned of weird values.
        idx = np.argsort(self._wavelength)
        self._wavelength = self._wavelength[idx]
        self.transmit   = np.clip(transmit[idx], 0., np.nanmax(transmit))

        self.norm = np.trapz(self.transmit, self._wavelength)
        self._lT = np.trapz(self._wavelength * self.transmit, self._wavelength)
        self._lpivot = self._calculate_lpivot()
        if self.norm > 0:
            self._cl = self._lT / self.norm
        else:
            self._cl = 0.
//  [python]
def velocity(self):
        """
        Plot acceleration and velocity on x-axis.
        Velocity calculated with trapeze method.
        """
        self.speedX = self.speedX + scipy.integrate.trapz(self.accX, dx=0.02)
        print("SPEED : {}".format(self.speedX))
//  [python]
def velocity(self):
        """
        Plot acceleration and velocity on x-axis.
        Velocity calculated with trapeze method.
        """
        self.speedX = self.speedX + scipy.integrate.trapezoid(self.accX, dx=0.02)
        print("SPEED : {}".format(self.speedX))
//  [python]
def plotProfileAndMC(ax, FB_WIDTH, color1, color2, label=None, **kwargs):
    profile_dist = clsim.I3CLSimRandomValueIceCubeFlasherTimeProfile()
    
    xVals = numpy.linspace(-100.,200.,2000)
    area = scipy.integrate.trapz(profile_dist._the_pulse(xVals, FB_WIDTH), xVals) 

    hist = genMCHistogramsHost(profile_dist, hist_range=(0., 200.), distribution_params=[FB_WIDTH*0.5*I3Units.ns])
    ax.plot(hist["bins"], hist["num"]*area, color=color2, linewidth=2., label=label+" (MC)", **kwargs)

    ax.plot(xVals, profile_dist._the_pulse(xVals, FB_WIDTH), color=color1, label=label+" (func)", **kwargs)
    
    ax.plot(xVals, gauss(0., FB_WIDTH*0.5 / 2.3548, xVals)*area, linestyle='--', color='g', label=r"previous versions")
//  [python]
def plotProfileAndMC(ax, FB_WIDTH, color1, color2, label=None, **kwargs):
    profile_dist = clsim.I3CLSimRandomValueIceCubeFlasherTimeProfile()
    
    xVals = numpy.linspace(-100.,200.,2000)
    area = scipy.integrate.trapezoid(profile_dist._the_pulse(xVals, FB_WIDTH), xVals) 

    hist = genMCHistogramsHost(profile_dist, hist_range=(0., 200.), distribution_params=[FB_WIDTH*0.5*I3Units.ns])
    ax.plot(hist["bins"], hist["num"]*area, color=color2, linewidth=2., label=label+" (MC)", **kwargs)

    ax.plot(xVals, profile_dist._the_pulse(xVals, FB_WIDTH), color=color1, label=label+" (func)", **kwargs)
    
    ax.plot(xVals, gauss(0., FB_WIDTH*0.5 / 2.3548, xVals)*area, linestyle='--', color='g', label=r"previous versions")
//  [python]
def action(self, *args):
        """
        Compute the action for all the trajectories given as arguments
        """
        for t, x in args:
            xdot = edpy.CenteredFD(t).grad(x)
            p = 0.5*(xdot-self.drift(x[1:-1], t[1:-1]))
            yield integrate.trapz(p**2, t[1:-1])
//  [python]
def action(self, *args):
        """
        Compute the action for all the trajectories given as arguments
        """
        for t, x in args:
            xdot = edpy.CenteredFD(t).grad(x)
            p = 0.5*(xdot-self.drift(x[1:-1], t[1:-1]))
            yield integrate.trapezoid(p**2, t[1:-1])
//  [python]
def get_y_hat(t_list, density_hat):
    """
    Compute y_hat based on t_list and density values.

    Parameters
    ----------
    t_list : np.ndarray
        Array of t-values.
    density_hat : np.ndarray
        Array of density values.

    Returns
    -------
    np.ndarray
        y_hat for each entry in density_hat.
    """
    n_y, n_t = np.shape(density_hat)

    t_list_hat = (t_list[0:-1] + t_list[1:]) / 2

    y_hat = np.zeros(n_y)

    if len(t_list_hat) == n_t:
        for i in range(0, n_y):
            y_py = t_list_hat * density_hat[i, :]

            y_hat[i] = scipy.integrate.trapz(y_py, t_list_hat)

    else:
        for i in range(0, n_y):
            y_py = t_list * density_hat[i, :]

            y_hat[i] = scipy.integrate.trapz(y_py, t_list)

    return y_hat
//  [python]
def get_y_hat(t_list, density_hat):
    """
    Compute y_hat based on t_list and density values.

    Parameters
    ----------
    t_list : np.ndarray
        Array of t-values.
    density_hat : np.ndarray
        Array of density values.

    Returns
    -------
    np.ndarray
        y_hat for each entry in density_hat.
    """
    n_y, n_t = np.shape(density_hat)

    t_list_hat = (t_list[0:-1] + t_list[1:]) / 2

    y_hat = np.zeros(n_y)

    if len(t_list_hat) == n_t:
        for i in range(0, n_y):
            y_py = t_list_hat * density_hat[i, :]

            y_hat[i] = scipy.integrate.trapezoid(y_py, t_list_hat)

    else:
        for i in range(0, n_y):
            y_py = t_list * density_hat[i, :]

            y_hat[i] = scipy.integrate.trapezoid(y_py, t_list)

    return y_hat
//  [python]
def BSHWVolatility(T,eta,sigma,rho,lambd):
    Br= lambda t,T: 1/lambd * (np.exp(-lambd*(T-t))-1.0)
    sigmaF = lambda t: np.sqrt(sigma * sigma + eta * eta * Br(t,T) * Br(t,T)\
                               - 2.0 * rho * sigma * eta * Br(t,T)) 
    zGrid = np.linspace(0.0,T,2500)
    sigmaC = np.sqrt(1/T*integrate.trapz(sigmaF(zGrid)*sigmaF(zGrid), zGrid))
    return sigmaC
//  [python]
def BSHWVolatility(T,eta,sigma,rho,lambd):
    Br= lambda t,T: 1/lambd * (np.exp(-lambd*(T-t))-1.0)
    sigmaF = lambda t: np.sqrt(sigma * sigma + eta * eta * Br(t,T) * Br(t,T)\
                               - 2.0 * rho * sigma * eta * Br(t,T)) 
    zGrid = np.linspace(0.0,T,2500)
    sigmaC = np.sqrt(1/T*integrate.trapezoid(sigmaF(zGrid)*sigmaF(zGrid), zGrid))
    return sigmaC
//  [python]
def get_y_var(t_list, density_hat):
    """
    Compute y variance based on t_list and density values.

    Parameters
    ----------
    t_list : np.ndarray
        Array of t-values.
    density_hat : np.ndarray
        Array of density values.

    Returns
    -------
    np.ndarray
        Variance for each entry in density_hat.
    """
    n_y, n_t = np.shape(density_hat)

    t_list_hat = (t_list[0:-1] + t_list[1:]) / 2

    y_hat = get_y_hat(t_list, density_hat)
    y_var = np.zeros(n_y)

    if len(t_list_hat) == n_t:
        for i in range(0, n_y):
            y_py = ((t_list_hat - y_hat[i]) ** 2) * density_hat[i, :]

            y_var[i] = scipy.integrate.trapz(y_py, t_list_hat)

    else:
        for i in range(0, n_y):
            y_py = ((t_list - y_hat[i]) ** 2) * density_hat[i, :]

            y_var[i] = scipy.integrate.trapz(y_py, t_list)

    return y_var
//  [python]
def get_y_var(t_list, density_hat):
    """
    Compute y variance based on t_list and density values.

    Parameters
    ----------
    t_list : np.ndarray
        Array of t-values.
    density_hat : np.ndarray
        Array of density values.

    Returns
    -------
    np.ndarray
        Variance for each entry in density_hat.
    """
    n_y, n_t = np.shape(density_hat)

    t_list_hat = (t_list[0:-1] + t_list[1:]) / 2

    y_hat = get_y_hat(t_list, density_hat)
    y_var = np.zeros(n_y)

    if len(t_list_hat) == n_t:
        for i in range(0, n_y):
            y_py = ((t_list_hat - y_hat[i]) ** 2) * density_hat[i, :]

            y_var[i] = scipy.integrate.trapezoid(y_py, t_list_hat)

    else:
        for i in range(0, n_y):
            y_py = ((t_list - y_hat[i]) ** 2) * density_hat[i, :]

            y_var[i] = scipy.integrate.trapezoid(y_py, t_list)

    return y_var
//  [python]
def get_area(self, sign, m, t):
        """ Get area under model, for the postive (above median) and negative parts.

        I break the ( > median) points into segments which I integrate
        over using trapazoid method.  Otherwise, the interpolation
        over ( < median) gaps would skew the results.
        """
        if sign == 'pos':
            past_thresh = numpy.where(m > 0.0)[0]
        elif sign == 'neg':
            past_thresh = numpy.where(m < 0.0)[0]
        total_area = 0.
        t_segment = [t[past_thresh[0]]]
        m_segment = [m[past_thresh[0]]]
        j_prev = past_thresh[0]
        #import pdb; pdb.set_trace()
        #print
        for j in past_thresh[1:]:
            if j-1 == j_prev:
                j_prev = j
                t_segment.append(t[j])
                m_segment.append(m[j])
            else:
                if len(t_segment) >= 2:
                    total_area += scipy.integrate.trapz(m_segment, t_segment)
                # then we integrate the current segment if long enough
                t_segment = [t[j]]
                m_segment = [m[j]]
                j_prev = j
        if len(t_segment) >= 2:
            total_area += scipy.integrate.trapz(m_segment, t_segment)
        return total_area
//  [python]
def get_area(self, sign, m, t):
        """ Get area under model, for the postive (above median) and negative parts.

        I break the ( > median) points into segments which I integrate
        over using trapazoid method.  Otherwise, the interpolation
        over ( < median) gaps would skew the results.
        """
        if sign == 'pos':
            past_thresh = numpy.where(m > 0.0)[0]
        elif sign == 'neg':
            past_thresh = numpy.where(m < 0.0)[0]
        total_area = 0.
        t_segment = [t[past_thresh[0]]]
        m_segment = [m[past_thresh[0]]]
        j_prev = past_thresh[0]
        #import pdb; pdb.set_trace()
        #print
        for j in past_thresh[1:]:
            if j-1 == j_prev:
                j_prev = j
                t_segment.append(t[j])
                m_segment.append(m[j])
            else:
                if len(t_segment) >= 2:
                    total_area += scipy.integrate.trapezoid(m_segment, t_segment)
                # then we integrate the current segment if long enough
                t_segment = [t[j]]
                m_segment = [m[j]]
                j_prev = j
        if len(t_segment) >= 2:
            total_area += scipy.integrate.trapezoid(m_segment, t_segment)
        return total_area
//  [python]
def calc_pew(w,f,fc): return scipy.integrate.trapz(1-f/fc,w)
//  [python]
def calc_pew(w,f,fc): return scipy.integrate.trapezoid(1-f/fc,w)
//  [python]
def l2(x, funca, funcb):
    """
    Computes the L2 norm for one profile(assumed to be linear between points).

    :type x: array of float
    :param x: depths :math:`[m]`.
    :type funca: list of arrays of float
    :param funca: array calculated values
    :type funcb: list of arrays of float
    :param funcb: array of values (observed or calculated) to compare to

    :returns: L2 norm
    :rtype: array of floats
    """
    diff = np.array(funca - funcb)
    diff = diff * diff

    return integrate.trapz(diff, x)
//  [python]
def l2(x, funca, funcb):
    """
    Computes the L2 norm for one profile(assumed to be linear between points).

    :type x: array of float
    :param x: depths :math:`[m]`.
    :type funca: list of arrays of float
    :param funca: array calculated values
    :type funcb: list of arrays of float
    :param funcb: array of values (observed or calculated) to compare to

    :returns: L2 norm
    :rtype: array of floats
    """
    diff = np.array(funca - funcb)
    diff = diff * diff

    return integrate.trapezoid(diff, x)
//  [python]
def guess_res_freq(self):
        if self.useml and np.any(self.resID == self.mlResIDs):
            resInd = np.where(self.resID == self.mlResIDs)[0]
            self.select_freq(self.mlFreqs[resInd])
        else:
            use = np.abs(self.Res1.freq[:-1] - self.fsweepdata.initfreqs[self.resnum]) < .25e6
            com_guess = (scipy.integrate.trapz(self.res1_iq_vel[use] * self.Res1.freq[:-1][use]) /
                         scipy.integrate.trapz(self.res1_iq_vel[use]))

            self.select_freq(com_guess)
            getLogger(__name__).info('Guessing resonant freq at {} for self.iAtten={}'.format(com_guess, self.iAtten))
//  [python]
def guess_res_freq(self):
        if self.useml and np.any(self.resID == self.mlResIDs):
            resInd = np.where(self.resID == self.mlResIDs)[0]
            self.select_freq(self.mlFreqs[resInd])
        else:
            use = np.abs(self.Res1.freq[:-1] - self.fsweepdata.initfreqs[self.resnum]) < .25e6
            com_guess = (scipy.integrate.trapezoid(self.res1_iq_vel[use] * self.Res1.freq[:-1][use]) /
                         scipy.integrate.trapezoid(self.res1_iq_vel[use]))

            self.select_freq(com_guess)
            getLogger(__name__).info('Guessing resonant freq at {} for self.iAtten={}'.format(com_guess, self.iAtten))
//  [python]
def ChFBSHW(u, T, P0T, lambd, eta, rho, sigma):
    i = np.complex(0.0,1.0)
    f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2*dt)
    
    # Initial interest rate is a forward rate at time t->0

    r0 = f0T(0.00001)
    
    theta = lambda t: 1.0/lambd * (f0T(t+dt)-f0T(t-dt))/(2.0*dt) + f0T(t) \
        + eta*eta/(2.0*lambd*lambd)*(1.0-np.exp(-2.0*lambd*t))      
    C = lambda u,tau: 1.0/lambd*(i*u-1.0)*(1.0-np.exp(-lambd*tau))
    
    # Define a grid for the numerical integration of function theta

    zGrid = np.linspace(0.0,T,2500)
    term1 = lambda u: 0.5*sigma*sigma *i*u*(i*u-1.0)*T
    term2 = lambda u: i*u*rho*sigma*eta/lambd*(i*u-1.0)*(T+1.0/lambd \
                    *(np.exp(-lambd*T)-1.0))
    term3 = lambda u: eta*eta/(4.0*np.power(lambd,3.0))*np.power(i+u,2.0)*\
            (3.0+np.exp(-2.0*lambd*T)-4.0*np.exp(-lambd*T)-2.0*lambd*T)
    term4 = lambda u:  lambd*integrate.trapz(theta(T-zGrid)*C(u,zGrid), zGrid)
    A= lambda u: term1(u) + term2(u) + term3(u) + term4(u)
    
    # Note that we don't include B(u)*x0 term as it is included in the COS method

    cf = lambda u : np.exp(A(u) + C(u,T)*r0 )
    
    # Iterate over all u and collect the ChF, iteration is necessary due to the integration in term4

    cfV = []
    for ui in u:
        cfV.append(cf(ui))
    
    return cfV
//  [python]
def ChFBSHW(u, T, P0T, lambd, eta, rho, sigma):
    i = np.complex(0.0,1.0)
    f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2*dt)
    
    # Initial interest rate is a forward rate at time t->0

    r0 = f0T(0.00001)
    
    theta = lambda t: 1.0/lambd * (f0T(t+dt)-f0T(t-dt))/(2.0*dt) + f0T(t) \
        + eta*eta/(2.0*lambd*lambd)*(1.0-np.exp(-2.0*lambd*t))      
    C = lambda u,tau: 1.0/lambd*(i*u-1.0)*(1.0-np.exp(-lambd*tau))
    
    # Define a grid for the numerical integration of function theta

    zGrid = np.linspace(0.0,T,2500)
    term1 = lambda u: 0.5*sigma*sigma *i*u*(i*u-1.0)*T
    term2 = lambda u: i*u*rho*sigma*eta/lambd*(i*u-1.0)*(T+1.0/lambd \
                    *(np.exp(-lambd*T)-1.0))
    term3 = lambda u: eta*eta/(4.0*np.power(lambd,3.0))*np.power(i+u,2.0)*\
            (3.0+np.exp(-2.0*lambd*T)-4.0*np.exp(-lambd*T)-2.0*lambd*T)
    term4 = lambda u:  lambd*integrate.trapezoid(theta(T-zGrid)*C(u,zGrid), zGrid)
    A= lambda u: term1(u) + term2(u) + term3(u) + term4(u)
    
    # Note that we don't include B(u)*x0 term as it is included in the COS method

    cf = lambda u : np.exp(A(u) + C(u,T)*r0 )
    
    # Iterate over all u and collect the ChF, iteration is necessary due to the integration in term4

    cfV = []
    for ui in u:
        cfV.append(cf(ui))
    
    return cfV
//  [python]
def calc_momentum_def(x_loc, X, Y, U):
    """ calc_momentum_def() : Calculates the integral momentum deficit of scalar field U stored at \
        locations X,Y on a vertical line that runs nearest to x_loc. """
    
    U_line, x_line, x_idx_line = get_line_quantity(x_loc, X, Y, U)
    y_line = Y[:,x_idx_line]

    return scipy.integrate.trapz(U_line*(1-U_line), y_line)
//  [python]
def calc_momentum_def(x_loc, X, Y, U):
    """ calc_momentum_def() : Calculates the integral momentum deficit of scalar field U stored at \
        locations X,Y on a vertical line that runs nearest to x_loc. """
    
    U_line, x_line, x_idx_line = get_line_quantity(x_loc, X, Y, U)
    y_line = Y[:,x_idx_line]

    return scipy.integrate.trapezoid(U_line*(1-U_line), y_line)
//  [python]
def ChFBSHW(u, T, P0T, lambd, eta, rho, sigma):
    i = np.complex(0.0,1.0)
    f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2*dt)
    
    # Initial interest rate is a forward rate at time t->0

    r0 = f0T(0.00001)
    
    theta = lambda t: 1.0/lambd * (f0T(t+dt)-f0T(t-dt))/(2.0*dt) + f0T(t) + eta*eta/(2.0*lambd*lambd)*(1.0-np.exp(-2.0*lambd*t))   
    C = lambda u,tau: 1.0/lambd*(i*u-1.0)*(1.0-np.exp(-lambd*tau))
    
    # Define a grid for the numerical integration of function theta

    zGrid = np.linspace(0.0,T,2500)
    term1 = lambda u: 0.5*sigma*sigma *i*u*(i*u-1.0)*T
    term2 = lambda u: i*u*rho*sigma*eta/lambd*(i*u-1.0)*(T+1.0/lambd *(np.exp(-lambd*T)-1.0))
    term3 = lambda u: eta*eta/(4.0*np.power(lambd,3.0))*np.power(i+u,2.0)*(3.0+np.exp(-2.0*lambd*T)-4.0*np.exp(-lambd*T)-2.0*lambd*T)
    term4 = lambda u:  lambd*integrate.trapz(theta(T-zGrid)*C(u,zGrid), zGrid)    
    A= lambda u: term1(u) + term2(u) + term3(u) + term4(u)
    
    # Note that we don't include B(u)*x0 term as it is already included in the COS method
    cf = lambda u : np.exp(A(u) + C(u,T)*r0 )
    
    # Iterate over all u and collect the ChF, iteration is necessary due to the integration in term4

    cfV = []
    for ui in u:
        cfV.append(cf(ui))
    
    return cfV
//  [python]
def ChFBSHW(u, T, P0T, lambd, eta, rho, sigma):
    i = np.complex(0.0,1.0)
    f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2*dt)
    
    # Initial interest rate is a forward rate at time t->0

    r0 = f0T(0.00001)
    
    theta = lambda t: 1.0/lambd * (f0T(t+dt)-f0T(t-dt))/(2.0*dt) + f0T(t) + eta*eta/(2.0*lambd*lambd)*(1.0-np.exp(-2.0*lambd*t))   
    C = lambda u,tau: 1.0/lambd*(i*u-1.0)*(1.0-np.exp(-lambd*tau))
    
    # Define a grid for the numerical integration of function theta

    zGrid = np.linspace(0.0,T,2500)
    term1 = lambda u: 0.5*sigma*sigma *i*u*(i*u-1.0)*T
    term2 = lambda u: i*u*rho*sigma*eta/lambd*(i*u-1.0)*(T+1.0/lambd *(np.exp(-lambd*T)-1.0))
    term3 = lambda u: eta*eta/(4.0*np.power(lambd,3.0))*np.power(i+u,2.0)*(3.0+np.exp(-2.0*lambd*T)-4.0*np.exp(-lambd*T)-2.0*lambd*T)
    term4 = lambda u:  lambd*integrate.trapezoid(theta(T-zGrid)*C(u,zGrid), zGrid)    
    A= lambda u: term1(u) + term2(u) + term3(u) + term4(u)
    
    # Note that we don't include B(u)*x0 term as it is already included in the COS method
    cf = lambda u : np.exp(A(u) + C(u,T)*r0 )
    
    # Iterate over all u and collect the ChF, iteration is necessary due to the integration in term4

    cfV = []
    for ui in u:
        cfV.append(cf(ui))
    
    return cfV
//  [python]
def iorg(cloudmask, connectivity=1):
    """Calculate the cloud cluster index 'I_org'.

    See also: 
        :func:`scipy.integrate.trapz`:
            Used to calculate the integral along the given axis using
            the composite trapezoidal rule.

    Parameters: 
        cloudmask (ndarray): 2d binary cloud mask.
        connectivity (int):  Maximum number of orthogonal hops to consider
            a pixel/voxel as a neighbor (see :func:`skimage.measure.label`).

    Returns:
        float: cloud cluster index I_org.

    References: 
        Tompkins, A. M., and A. G. Semie (2017), Organization of tropical 
        convection in low vertical wind shears: Role of updraft entrainment, 
        J. Adv. Model. Earth Syst., 9, 1046–1068, doi: 10.1002/2016MS000802.
        
    """
    nn = neighbor_distance(cloudmask, connectivity=connectivity)
    nn_sorted = np.sort(nn)

    nncdf = np.linspace(0, 1, len(nn))

    # theoretical nearest neighbor cumulative frequency
    # distribution (nncdf) of a random point process (Poisson)
    lamb = nn.size / cloudmask.size
    nncdf_poisson = 1 - np.exp(-lamb * np.pi * nn_sorted ** 2)

    return sc.integrate.trapz(y=nncdf, x=nncdf_poisson)
//  [python]
def iorg(cloudmask, connectivity=1):
    """Calculate the cloud cluster index 'I_org'.

    See also: 
        :func:`scipy.integrate.trapezoid`:
            Used to calculate the integral along the given axis using
            the composite trapezoidal rule.

    Parameters: 
        cloudmask (ndarray): 2d binary cloud mask.
        connectivity (int):  Maximum number of orthogonal hops to consider
            a pixel/voxel as a neighbor (see :func:`skimage.measure.label`).

    Returns:
        float: cloud cluster index I_org.

    References: 
        Tompkins, A. M., and A. G. Semie (2017), Organization of tropical 
        convection in low vertical wind shears: Role of updraft entrainment, 
        J. Adv. Model. Earth Syst., 9, 1046–1068, doi: 10.1002/2016MS000802.
        
    """
    nn = neighbor_distance(cloudmask, connectivity=connectivity)
    nn_sorted = np.sort(nn)

    nncdf = np.linspace(0, 1, len(nn))

    # theoretical nearest neighbor cumulative frequency
    # distribution (nncdf) of a random point process (Poisson)
    lamb = nn.size / cloudmask.size
    nncdf_poisson = 1 - np.exp(-lamb * np.pi * nn_sorted ** 2)

    return sc.integrate.trapezoid(y=nncdf, x=nncdf_poisson)
//  [python]
def calc_stats(self, sig, i0=0, i1=None):

        stats = {}
        # calculate the statistics values:
        stats['max'] = sig[i0:i1, :].max(axis=0)
        stats['min'] = sig[i0:i1, :].min(axis=0)
        stats['mean'] = sig[i0:i1, :].mean(axis=0)
        stats['std'] = sig[i0:i1, :].std(axis=0)
        stats['range'] = stats['max'] - stats['min']
        stats['absmax'] = np.absolute(sig[i0:i1, :]).max(axis=0)
        stats['rms'] = np.sqrt(np.mean(sig[i0:i1, :]*sig[i0:i1, :], axis=0))
        stats['int'] = integrate.trapz(sig[i0:i1, :], x=sig[i0:i1, 0], axis=0)
        return stats
//  [python]
def calc_stats(self, sig, i0=0, i1=None):

        stats = {}
        # calculate the statistics values:
        stats['max'] = sig[i0:i1, :].max(axis=0)
        stats['min'] = sig[i0:i1, :].min(axis=0)
        stats['mean'] = sig[i0:i1, :].mean(axis=0)
        stats['std'] = sig[i0:i1, :].std(axis=0)
        stats['range'] = stats['max'] - stats['min']
        stats['absmax'] = np.absolute(sig[i0:i1, :]).max(axis=0)
        stats['rms'] = np.sqrt(np.mean(sig[i0:i1, :]*sig[i0:i1, :], axis=0))
        stats['int'] = integrate.trapezoid(sig[i0:i1, :], x=sig[i0:i1, 0], axis=0)
        return stats
//  [python]
def get_kpis(self) -> dict:
        '''Returns KPI data.

        Requires standard sensor signals.

        Parameters
        ----------
        None

        Returns
        kpis : dict
            Dictionary containing KPI names and values.
            {<kpi_name>:<kpi_value>}

        '''

        kpis = dict()
        # Calculate each KPI using json for signals and save in dictionary
        for kpi in self.kpi_json.keys():
            print(kpi, type(kpi))
            if 'Power' in kpi:
                # Calculate total energy [KWh - assumes measured in J]
                E = 0
                for signal in self.kpi_json[kpi]:
                    time = self.y_store['time']
                    power = self.y_store[signal]
                    E = E + np.trapz(power, time)
                # Store result in dictionary
                kpis['energy'] = E * 2.77778e-7  # Convert to kWh
            elif kpi == 'AirZoneTemperature':
                # Calculate total discomfort [K-h = assumes measured in K]
                tot_dis = 0
                heat_setpoint = 273.15 + 20
                for signal in self.kpi_json[kpi]:
                    data = np.array(self.y_store[signal])
                    dT_heating = heat_setpoint - data
                    dT_heating[dT_heating < 0] = 0
                    tot_dis = tot_dis + trapz(dT_heating, self.y_store['time']) / 3600
                # Store result in dictionary
                kpis['comfort'] = tot_dis
            else:
                print('No calculation for KPI named "{0}".'.format(kpi))

        return kpis
//  [python]
def get_kpis(self) -> dict:
        '''Returns KPI data.

        Requires standard sensor signals.

        Parameters
        ----------
        None

        Returns
        kpis : dict
            Dictionary containing KPI names and values.
            {<kpi_name>:<kpi_value>}

        '''

        kpis = dict()
        # Calculate each KPI using json for signals and save in dictionary
        for kpi in self.kpi_json.keys():
            print(kpi, type(kpi))
            if 'Power' in kpi:
                # Calculate total energy [KWh - assumes measured in J]
                E = 0
                for signal in self.kpi_json[kpi]:
                    time = self.y_store['time']
                    power = self.y_store[signal]
                    E = E + np.trapz(power, time)
                # Store result in dictionary
                kpis['energy'] = E * 2.77778e-7  # Convert to kWh
            elif kpi == 'AirZoneTemperature':
                # Calculate total discomfort [K-h = assumes measured in K]
                tot_dis = 0
                heat_setpoint = 273.15 + 20
                for signal in self.kpi_json[kpi]:
                    data = np.array(self.y_store[signal])
                    dT_heating = heat_setpoint - data
                    dT_heating[dT_heating < 0] = 0
                    tot_dis = tot_dis + np.trapz(dT_heating, self.y_store['time']) / 3600
                # Store result in dictionary
                kpis['comfort'] = tot_dis
            else:
                print('No calculation for KPI named "{0}".'.format(kpi))

        return kpis
//  [python]
def intergrate_curve(x, y, normalize=True):
    y_int = []
    for i in range(len(x) - 1):
        x_i = x[i:i + 2]
        y_i = y[i:i + 2]
        integral = spint.trapz(y_i, x=x_i)
        y_int.append(integral)

    if normalize:
        y_int = y_int - np.min(y_int)
        y_int = y_int / np.max(y_int)

    return x[0:-1], y_int
//  [python]
def intergrate_curve(x, y, normalize=True):
    y_int = []
    for i in range(len(x) - 1):
        x_i = x[i:i + 2]
        y_i = y[i:i + 2]
        integral = spint.trapezoid(y_i, x=x_i)
        y_int.append(integral)

    if normalize:
        y_int = y_int - np.min(y_int)
        y_int = y_int / np.max(y_int)

    return x[0:-1], y_int
//  [python]
def flux_surface_avg(Rho,Z,B,flpoints,Q=None):
    """Compute flux surface average of quantity Q or return dVdpsi (dl_B)
    """
    ## Interpolate B and quantity Q onto flux line
    B_interp = interp(Rho,Z,B,flpoints)
    s = get_fieldline_distance(flpoints)
    dl_B = scipy.integrate.trapz(y=1.0/B_interp,x=s)
    if Q != None:
        Q_interp = interp(Rho,Z,Q,flpoints)
        fsa = 1/dl_B*scipy.integrate.trapz(y=Q_interp/B_interp,x=s)
        return fsa
    else:
        return dl_B
//  [python]
def flux_surface_avg(Rho,Z,B,flpoints,Q=None):
    """Compute flux surface average of quantity Q or return dVdpsi (dl_B)
    """
    ## Interpolate B and quantity Q onto flux line
    B_interp = interp(Rho,Z,B,flpoints)
    s = get_fieldline_distance(flpoints)
    dl_B = scipy.integrate.trapezoid(y=1.0/B_interp,x=s)
    if Q != None:
        Q_interp = interp(Rho,Z,Q,flpoints)
        fsa = 1/dl_B*scipy.integrate.trapezoid(y=Q_interp/B_interp,x=s)
        return fsa
    else:
        return dl_B
//  [python]
def burst_range(f, S, rho=8, E=1e-2, fmin=64, fmax=500):
  """
    Calculate GRB-like or supernova-like burst range for a given spectrum
    and background trigger SNR.
  """

  # restrict spectrum to given frequency range
  condition = (f>=fmin) & (f<fmax)
  S2 = S[condition]
  f2 = f[condition]

  # calculate integral
  FOM1 = scipy.integrate.trapz(f_dependent_burst_range(f2, S2, rho, E)**3, f2)
  FOM2 = FOM1/(fmax-fmin)

  return FOM2**(1/3)
//  [python]
def burst_range(f, S, rho=8, E=1e-2, fmin=64, fmax=500):
  """
    Calculate GRB-like or supernova-like burst range for a given spectrum
    and background trigger SNR.
  """

  # restrict spectrum to given frequency range
  condition = (f>=fmin) & (f<fmax)
  S2 = S[condition]
  f2 = f[condition]

  # calculate integral
  FOM1 = scipy.integrate.trapezoid(f_dependent_burst_range(f2, S2, rho, E)**3, f2)
  FOM2 = FOM1/(fmax-fmin)

  return FOM2**(1/3)
//  [python]
def inspiral_range(f, S, rho=8, m1=1.4, m2=1.4, fmin=30, fmax=4096,\
                   horizon=False):

  """
    Calculate inspiral range for a given spectrum.
  """

  Mpc = 10**6 * XLALConstants.PC_SI

  # compute chirp mass and total mass (in units of solar masses)
  mtot = m1 + m2;
  reducedmass = m1*m2/mtot;
  mchirp = reducedmass**(3/5)*mtot**(2/5);

  # calculate prefactor in m^2
  mchirp *= XLALConstants.MSUN_SI * XLALConstants.G_SI /\
            XLALConstants.C_SI**2
  pre = (5 * XLALConstants.C_SI**(1/3) * mchirp**(5/3) * 1.77**2) /\
        (96 * numpy.pi ** (4/3) * rho**2)

  # include fisco
  fisco = XLALConstants.C_SI**3/XLALConstants.G_SI/XLALConstants.MSUN_SI/\
      6**1.5/numpy.pi/mtot

  # restrict to range, include fisco
  condition = (f >= fmin) & (f < min(fmax,fisco))
  S         = S[condition]
  f         = f[condition]

  # calculate integrand
  integrand = (f**(-7/3))/S

  # integrate
  result = scipy.integrate.trapz(integrand, f)

  R = (pre*result) ** 0.5 / Mpc

  if horizon: R *= 2.26

  return R
//  [python]
def inspiral_range(f, S, rho=8, m1=1.4, m2=1.4, fmin=30, fmax=4096,\
                   horizon=False):

  """
    Calculate inspiral range for a given spectrum.
  """

  Mpc = 10**6 * XLALConstants.PC_SI

  # compute chirp mass and total mass (in units of solar masses)
  mtot = m1 + m2;
  reducedmass = m1*m2/mtot;
  mchirp = reducedmass**(3/5)*mtot**(2/5);

  # calculate prefactor in m^2
  mchirp *= XLALConstants.MSUN_SI * XLALConstants.G_SI /\
            XLALConstants.C_SI**2
  pre = (5 * XLALConstants.C_SI**(1/3) * mchirp**(5/3) * 1.77**2) /\
        (96 * numpy.pi ** (4/3) * rho**2)

  # include fisco
  fisco = XLALConstants.C_SI**3/XLALConstants.G_SI/XLALConstants.MSUN_SI/\
      6**1.5/numpy.pi/mtot

  # restrict to range, include fisco
  condition = (f >= fmin) & (f < min(fmax,fisco))
  S         = S[condition]
  f         = f[condition]

  # calculate integrand
  integrand = (f**(-7/3))/S

  # integrate
  result = scipy.integrate.trapezoid(integrand, f)

  R = (pre*result) ** 0.5 / Mpc

  if horizon: R *= 2.26

  return R
//  [python]
def burst_sg_range(f, S, centralFreq, Q, rho=8, E=1e-2, fmin=64, fmax=500):
  """
    Calculate range for sine-Gaussians for a given spectrum
    and background trigger SNR, assuming isotropic GW emission (unphysical but simple)
  """

  # restrict spectrum to given frequency range
  condition = (f>=fmin) & (f<fmax)
  S2 = S[condition]
  f2 = f[condition]

  # generate frequency dependent range
  Mpc = 10**6 * XLALConstants.PC_SI
  1/centralFreq
  A = (((XLALConstants.G_SI * (E*XLALConstants.MSUN_SI) )/(XLALConstants.PI**2 * XLALConstants.C_SI))**(1/2))/Mpc/centralFreq
  sigmaSq = Q**2 / (4 * XLALConstants.PI**2 * centralFreq**2)
  sg = numpy.exp( - (f2 - centralFreq)**2 * sigmaSq / 2) 
  normSG = scipy.integrate.trapz(sg**2, f2)**(1/2)
  sg = sg/normSG
  R = A * sg / (rho * S2**(1/2) )

  # calculate integral
  FOM1 = scipy.integrate.trapz(R**2, f2)

  # factor 0.36, median antenna pattern factor for a single detector
  # and linearly polarized GWs
  return FOM1**(1/2)*0.36
//  [python]
def burst_sg_range(f, S, centralFreq, Q, rho=8, E=1e-2, fmin=64, fmax=500):
  """
    Calculate range for sine-Gaussians for a given spectrum
    and background trigger SNR, assuming isotropic GW emission (unphysical but simple)
  """

  # restrict spectrum to given frequency range
  condition = (f>=fmin) & (f<fmax)
  S2 = S[condition]
  f2 = f[condition]

  # generate frequency dependent range
  Mpc = 10**6 * XLALConstants.PC_SI
  1/centralFreq
  A = (((XLALConstants.G_SI * (E*XLALConstants.MSUN_SI) )/(XLALConstants.PI**2 * XLALConstants.C_SI))**(1/2))/Mpc/centralFreq
  sigmaSq = Q**2 / (4 * XLALConstants.PI**2 * centralFreq**2)
  sg = numpy.exp( - (f2 - centralFreq)**2 * sigmaSq / 2) 
  normSG = scipy.integrate.trapezoid(sg**2, f2)**(1/2)
  sg = sg/normSG
  R = A * sg / (rho * S2**(1/2) )

  # calculate integral
  FOM1 = scipy.integrate.trapezoid(R**2, f2)

  # factor 0.36, median antenna pattern factor for a single detector
  # and linearly polarized GWs
  return FOM1**(1/2)*0.36
//  [python]
def bubble_area(
    InFolder, OutFolder, timezone, loc=-0.015625, step=3.0, skip=1, cutoff=None
):
    dirs = sorted(os.listdir(InFolder))
    area = np.zeros(np.size(timezone))
    j = 0
    if cutoff is None:
        cutoff = -0.015625
    else:
        assert isinstance(cutoff, float), "cutoff:{} is not a float".format(
            cutoff.__class__.__name__
        )
    plt.close()
    fig1, ax1 = plt.subplots(figsize=(10, 4))  # plot only bubble
    for i in range(np.size(dirs)):
        if i % skip == 0:
            with timer("Bubble area at " + dirs[i]):
                dataframe = pd.read_hdf(InFolder + dirs[i])
                grouped = dataframe.groupby(["x", "y"])
                dataframe = grouped.mean().reset_index()
                xy_org = dividing_line(dataframe, loc=loc)
                if np.max(xy_org[:, 1]) < cutoff:
                    ind = np.argmax(xy_org[:, 1])
                    xy = xy_org[ind:, :]
                    area[j] = trapz(xy[:, 1] + step, xy[:, 0])
                    area[j] = area[j] + 0.5 * xy[0, 0] * (0 - xy[0, 1])
                else:
                    xy = xy_org
                    area[j] = trapz(xy[:, 1] + step, xy[:, 0])
                ax1.plot(xy[:, 0], xy[:, 1])
                # ind = np.argmax(xy_new[:, 1])
                # if xy[ind, 1] < cutoff:
                #    area[j] = area[j] + 0.5 * xy[ind, 0] * (0 - xy[ind, 1])
            j = j + 1
    plt.show()
    area_arr = np.vstack((timezone, area)).T
    np.savetxt(
        OutFolder + "BubbleArea.dat",
        area_arr,
        fmt="%.8e",
        delimiter=", ",
        comments="",
        header="area",
    )
    return area
//  [python]
def bubble_area(
    InFolder, OutFolder, timezone, loc=-0.015625, step=3.0, skip=1, cutoff=None
):
    dirs = sorted(os.listdir(InFolder))
    area = np.zeros(np.size(timezone))
    j = 0
    if cutoff is None:
        cutoff = -0.015625
    else:
        assert isinstance(cutoff, float), "cutoff:{} is not a float".format(
            cutoff.__class__.__name__
        )
    plt.close()
    fig1, ax1 = plt.subplots(figsize=(10, 4))  # plot only bubble
    for i in range(np.size(dirs)):
        if i % skip == 0:
            with timer("Bubble area at " + dirs[i]):
                dataframe = pd.read_hdf(InFolder + dirs[i])
                grouped = dataframe.groupby(["x", "y"])
                dataframe = grouped.mean().reset_index()
                xy_org = dividing_line(dataframe, loc=loc)
                if np.max(xy_org[:, 1]) < cutoff:
                    ind = np.argmax(xy_org[:, 1])
                    xy = xy_org[ind:, :]
                    area[j] = trapezoid(xy[:, 1] + step, xy[:, 0])
                    area[j] = area[j] + 0.5 * xy[0, 0] * (0 - xy[0, 1])
                else:
                    xy = xy_org
                    area[j] = trapezoid(xy[:, 1] + step, xy[:, 0])
                ax1.plot(xy[:, 0], xy[:, 1])
                # ind = np.argmax(xy_new[:, 1])
                # if xy[ind, 1] < cutoff:
                #    area[j] = area[j] + 0.5 * xy[ind, 0] * (0 - xy[ind, 1])
            j = j + 1
    plt.show()
    area_arr = np.vstack((timezone, area)).T
    np.savetxt(
        OutFolder + "BubbleArea.dat",
        area_arr,
        fmt="%.8e",
        delimiter=", ",
        comments="",
        header="area",
    )
    return area
//  [python]
def radiation_efficiency(self,omega,fluid = mc.Fluid(),Nstep = 90,simple_muGT1=True):
        """
        Radiation efficieny of rectangular plates using leppingtons theory
        
        This method applies half circle integration over all avaiable mode shapes
        at one frequency.

        Parameters
        ----------
        omega : ndarray
            angular freuquency
        fluid : fluid
            fluid material for half space. The default is mc.Fluid().
        Nstep : int, optional
            Number of integration steps for half circle integration. The default is 90.
        simple_muGT1 : bool, optional
            Switch for simplified Leppington apporach. The default is True.

        Returns
        -------
        sigma : float
            Radiation efficiency of plate.

        """

        ar = aR.HalfSpace(fluid)
            
        phi   = np.linspace(0,np.pi/2,Nstep)  
        phi   = phi[1:-1]
        sigma = np.zeros(np.shape(omega)) 
        k_B = self.plate_wavenumber(omega,3)

        sigs = np.zeros(np.shape(phi))
        
        for ifreq,om in enumerate(omega):
            k_y  = k_B[ifreq]*np.cos(phi)
            k_x  = k_B[ifreq]*np.sin(phi)
            sigs = ar.radiation_efficiency_leppington(om, k_x, k_y, self.Lx, self.Ly,simple_muGT1=simple_muGT1) 
                
            sigma[ifreq] = 2/np.pi*integrate.trapz(sigs,phi)
            
        return sigma
//  [python]
def radiation_efficiency(self,omega,fluid = mc.Fluid(),Nstep = 90,simple_muGT1=True):
        """
        Radiation efficieny of rectangular plates using leppingtons theory
        
        This method applies half circle integration over all avaiable mode shapes
        at one frequency.

        Parameters
        ----------
        omega : ndarray
            angular freuquency
        fluid : fluid
            fluid material for half space. The default is mc.Fluid().
        Nstep : int, optional
            Number of integration steps for half circle integration. The default is 90.
        simple_muGT1 : bool, optional
            Switch for simplified Leppington apporach. The default is True.

        Returns
        -------
        sigma : float
            Radiation efficiency of plate.

        """

        ar = aR.HalfSpace(fluid)
            
        phi   = np.linspace(0,np.pi/2,Nstep)  
        phi   = phi[1:-1]
        sigma = np.zeros(np.shape(omega)) 
        k_B = self.plate_wavenumber(omega,3)

        sigs = np.zeros(np.shape(phi))
        
        for ifreq,om in enumerate(omega):
            k_y  = k_B[ifreq]*np.cos(phi)
            k_x  = k_B[ifreq]*np.sin(phi)
            sigs = ar.radiation_efficiency_leppington(om, k_x, k_y, self.Lx, self.Ly,simple_muGT1=simple_muGT1) 
                
            sigma[ifreq] = 2/np.pi*integrate.trapezoid(sigs,phi)
            
        return sigma
//  [python]
def A(u,tau,eta,lambd,Rxsigma,Rrsigma,Rxr,gamma,kappa,sigmabar):
    i=np.complex(0.0,1.0)
    a_0=-1.0/2.0*u*(i+u)
    a_1=2.0*(gamma*Rxsigma*i*u-kappa)
    a_2=2.0*gamma*gamma
    d  =np.sqrt(a_1*a_1-4.0*a_0*a_2)
    g =(-a_1-d)/(-a_1+d) 
    f_6=eta*eta/(4.0*np.power(lambd,3.0))*np.power(i+u,2.0)*(3.0+np.exp(-2.0*lambd*tau)-4.0*np.exp(-lambd*tau)-2.0*lambd*tau)
    A_1=1.0/4.0*((-a_1-d)*tau-2.0*np.log((1-g*np.exp(-d*tau))/(1.0-g)))+f_6
  
    # Integration within the function A(u,tau)

    value=np.zeros([len(u),1],dtype=np.complex_)   
    N = 500
    arg=np.linspace(0,tau,N)

    for k in range(0,len(u)):
       E_val=E(u[k],arg,lambd,gamma,Rxsigma,Rrsigma,Rxr,eta,kappa,sigmabar)
       C_val=C(u[k],arg,lambd)
       f=(kappa*sigmabar+1.0/2.0*gamma*gamma*E_val+gamma*eta*Rrsigma*C_val)*E_val
       value1 =integrate.trapz(np.real(f),arg)
       value2 =integrate.trapz(np.imag(f),arg)
       value[k]=(value1 + value2*i)
    
    return value + A_1
//  [python]
def A(u,tau,eta,lambd,Rxsigma,Rrsigma,Rxr,gamma,kappa,sigmabar):
    i=np.complex(0.0,1.0)
    a_0=-1.0/2.0*u*(i+u)
    a_1=2.0*(gamma*Rxsigma*i*u-kappa)
    a_2=2.0*gamma*gamma
    d  =np.sqrt(a_1*a_1-4.0*a_0*a_2)
    g =(-a_1-d)/(-a_1+d) 
    f_6=eta*eta/(4.0*np.power(lambd,3.0))*np.power(i+u,2.0)*(3.0+np.exp(-2.0*lambd*tau)-4.0*np.exp(-lambd*tau)-2.0*lambd*tau)
    A_1=1.0/4.0*((-a_1-d)*tau-2.0*np.log((1-g*np.exp(-d*tau))/(1.0-g)))+f_6
  
    # Integration within the function A(u,tau)

    value=np.zeros([len(u),1],dtype=np.complex_)   
    N = 500
    arg=np.linspace(0,tau,N)

    for k in range(0,len(u)):
       E_val=E(u[k],arg,lambd,gamma,Rxsigma,Rrsigma,Rxr,eta,kappa,sigmabar)
       C_val=C(u[k],arg,lambd)
       f=(kappa*sigmabar+1.0/2.0*gamma*gamma*E_val+gamma*eta*Rrsigma*C_val)*E_val
       value1 =integrate.trapezoid(np.real(f),arg)
       value2 =integrate.trapezoid(np.imag(f),arg)
       value[k]=(value1 + value2*i)
    
    return value + A_1
//  [python]
def __init__(self, beta, w, dos):
        try:
            nw, norbitals, nspins = dos.shape
        except ValueError:
            raise ValueError("dos must be a nw, norbital, nspins array")
        if w.shape != (nw,):
            raise ValueError("w and dos are not consistent in shape")

        Lattice.__init__(self, beta, norbitals, nspins)

        integrate = lambda fw: scipy.integrate.trapz(fw, w)
        cum_int = lambda fw: scipy.integrate.cumtrapz(fw, w, initial=0)

        if (dos < 0).any() or dos.imag.any():
            warn("dos is not a positive real function.", UserWarning, 2)

        dos_w_last = dos.transpose(1,2,0)
        norm = integrate(dos_w_last)
        if not np.allclose(norm, 1):
            warn("dos seems not to be properly normalised.\n Norms: %s" % norm,
                 UserWarning, 2)

        self.w = w
        self.dos = dos
        self.int_dos = cum_int(dos_w_last).transpose(2,0,1)

        self.hloc = integrate(dos_w_last * w)
        self.hmom2 = integrate(dos_w_last * w**2)

        self.hloc = orbspin.promote_diagonal(self.hloc)
        self.hmom2 = orbspin.promote_diagonal(self.hmom2)
//  [python]
def __init__(self, beta, w, dos):
        try:
            nw, norbitals, nspins = dos.shape
        except ValueError:
            raise ValueError("dos must be a nw, norbital, nspins array")
        if w.shape != (nw,):
            raise ValueError("w and dos are not consistent in shape")

        Lattice.__init__(self, beta, norbitals, nspins)

        integrate = lambda fw: scipy.integrate.trapezoid(fw, w)
        cum_int = lambda fw: scipy.integrate.cumtrapz(fw, w, initial=0)

        if (dos < 0).any() or dos.imag.any():
            warn("dos is not a positive real function.", UserWarning, 2)

        dos_w_last = dos.transpose(1,2,0)
        norm = integrate(dos_w_last)
        if not np.allclose(norm, 1):
            warn("dos seems not to be properly normalised.\n Norms: %s" % norm,
                 UserWarning, 2)

        self.w = w
        self.dos = dos
        self.int_dos = cum_int(dos_w_last).transpose(2,0,1)

        self.hloc = integrate(dos_w_last * w)
        self.hmom2 = integrate(dos_w_last * w**2)

        self.hloc = orbspin.promote_diagonal(self.hloc)
        self.hmom2 = orbspin.promote_diagonal(self.hmom2)