jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def execute(block, config):
    (mu, sigma, section) = config
    nbin = len(mu)
    # Set up z array.  Make sure ZMAX is inclusive
    z = np.arange(0, ZMAX + DZ, DZ)

    # Save Z array and count info
    block[section, "Z"] = z
    block[section, "NZ"] = len(z)
    block[section, "NBIN"] = nbin

    for i in range(1, nbin + 1):
        # generate simple gaussian window
        nz_bin = gaussian(z, mu[i - 1], sigma[i - 1])
        # the bin may not quite go to zero before we get to the
        # edges so normalize it
        norm = scipy.integrate.trapz(nz_bin, z)
        nz_bin /= norm
        # Save n(z)
        block[section, "BIN_%d" % i] = nz_bin
    return 0
//  [python]
def execute(block, config):
    (mu, sigma, section) = config
    nbin = len(mu)
    # Set up z array.  Make sure ZMAX is inclusive
    z = np.arange(0, ZMAX + DZ, DZ)

    # Save Z array and count info
    block[section, "Z"] = z
    block[section, "NZ"] = len(z)
    block[section, "NBIN"] = nbin

    for i in range(1, nbin + 1):
        # generate simple gaussian window
        nz_bin = gaussian(z, mu[i - 1], sigma[i - 1])
        # the bin may not quite go to zero before we get to the
        # edges so normalize it
        norm = scipy.integrate.trapezoid(nz_bin, z)
        nz_bin /= norm
        # Save n(z)
        block[section, "BIN_%d" % i] = nz_bin
    return 0
//  [python]
def compute_integral1D(grid, x0):
    """
    Computes norm of a 1D grid

    :param grid: 1D grid to integrate
    :param x0: coordinates of all points along the integration axis

    :type grid: numpy array
    :type x0: numpy array

    :rtype: float
    :returns: grid norm

    """

    grid_norm = si.trapz(grid, x=x0, axis=0)
    return grid_norm
//  [python]
def compute_integral1D(grid, x0):
    """
    Computes norm of a 1D grid

    :param grid: 1D grid to integrate
    :param x0: coordinates of all points along the integration axis

    :type grid: numpy array
    :type x0: numpy array

    :rtype: float
    :returns: grid norm

    """

    grid_norm = si.trapezoid(grid, x=x0, axis=0)
    return grid_norm
//  [python]
def mainCalculation():
    NoOfPaths = 1
    NoOfSteps = 500
    T         = 1
    r         = 0.05
    sigma     = 0.4
    S_0       = 100
    
    Paths = GeneratePathsGBMABM(NoOfPaths,NoOfSteps,T,r,sigma,S_0)
    timeGrid = Paths["time"]
    S = Paths["S"]
        
    plt.figure(1)
    plt.plot(timeGrid, np.transpose(S))   
    plt.grid()
    plt.xlabel("time")
    plt.ylabel("S(t)")

    m          = 20
    pathNumber = 0 
    f = interp1d(timeGrid, S[pathNumber,:])
    
    for k in range(1,m*T+1):
        tGrid = np.linspace(float((k-1))/m, float(k)/m, 100)
        g_m   = m * integrate.trapz(np.squeeze(f(tGrid)),np.squeeze(tGrid))
        plt.plot(tGrid,g_m * np.ones([len(tGrid),1]),'-r',linewidth=3.0)
        plt.plot(tGrid[0],g_m,'or')
        plt.plot(tGrid[-1],g_m,'or',markerfacecolor =[1,1,1])
//  [python]
def mainCalculation():
    NoOfPaths = 1
    NoOfSteps = 500
    T         = 1
    r         = 0.05
    sigma     = 0.4
    S_0       = 100
    
    Paths = GeneratePathsGBMABM(NoOfPaths,NoOfSteps,T,r,sigma,S_0)
    timeGrid = Paths["time"]
    S = Paths["S"]
        
    plt.figure(1)
    plt.plot(timeGrid, np.transpose(S))   
    plt.grid()
    plt.xlabel("time")
    plt.ylabel("S(t)")

    m          = 20
    pathNumber = 0 
    f = interp1d(timeGrid, S[pathNumber,:])
    
    for k in range(1,m*T+1):
        tGrid = np.linspace(float((k-1))/m, float(k)/m, 100)
        g_m   = m * integrate.trapezoid(np.squeeze(f(tGrid)),np.squeeze(tGrid))
        plt.plot(tGrid,g_m * np.ones([len(tGrid),1]),'-r',linewidth=3.0)
        plt.plot(tGrid[0],g_m,'or')
        plt.plot(tGrid[-1],g_m,'or',markerfacecolor =[1,1,1])
//  [python]
def compute_range_table(stepsize=0.001, maxextent=10):
    """Compute integrals of the unit normal distribution and return these tabulated.
    Returns:
    --------
    - range: NumPy array giving integration range (x) where integration range runs -x to +x
    - integral: NumPy arrange giving integrals over specified integration range.

    Arguments (optional):
    ---------------------
    - stepsize: Step size to advance integration range by each trial. Default: 0.001
    - maxextent: Maximum extent of integration range
"""
    # Calculate integration range
    x = np.arange(0, maxextent, stepsize)  # Symmetric, so no need to do negative values.

    # Calculate distribution at specified x values
    distrib = normal(x)

    integral = np.zeros(len(x), float)
    for idx in range(1, len(x)):
        integral[idx] = 2 * scipy.integrate.trapz(distrib[0:idx + 1], x[0:idx + 1])  # Factor of 2 handles symmetry

    return x, integral
//  [python]
def compute_range_table(stepsize=0.001, maxextent=10):
    """Compute integrals of the unit normal distribution and return these tabulated.
    Returns:
    --------
    - range: NumPy array giving integration range (x) where integration range runs -x to +x
    - integral: NumPy arrange giving integrals over specified integration range.

    Arguments (optional):
    ---------------------
    - stepsize: Step size to advance integration range by each trial. Default: 0.001
    - maxextent: Maximum extent of integration range
"""
    # Calculate integration range
    x = np.arange(0, maxextent, stepsize)  # Symmetric, so no need to do negative values.

    # Calculate distribution at specified x values
    distrib = normal(x)

    integral = np.zeros(len(x), float)
    for idx in range(1, len(x)):
        integral[idx] = 2 * scipy.integrate.trapezoid(distrib[0:idx + 1], x[0:idx + 1])  # Factor of 2 handles symmetry

    return x, integral
//  [python]
def calculate_position(coeff, val, vec):
    
    N = len(val)//2
    ti = 0.
    tf = 100.
    num = 3*int(tf-ti)
    tList = np.linspace(ti, tf, num=num)
    
    def integrand(t1,t):
        
        expMat = np.exp(np.dot(np.diag((t-t1)*val),np.ones((2*N,N))), dtype=complex)
        
        gFunc = np.dot(vec[:N,:],np.multiply(expMat,coeff))
        
#        print(tstep)
#        print(gFunc)
        
        #now the force
        force = np.zeros(N)
    
        #cosine driven force
#        w = 1.5
#        force[0] = np.cos(w*t1)
        
        #impulse force
        w = 1.
        force[0] = np.exp(-w*t1)
        force[N-1] = -force[0]
        
        x = np.dot(gFunc,force)
        return np.real(x)
    
    q = np.zeros((num,N))
    
    for count, t in enumerate(tList):
        
        innerNum = 3*int(t)
        t1List = np.linspace(0,t,num=innerNum)
        yList = np.zeros((innerNum,N))
        for t1count,t1 in enumerate(t1List):
            yList[t1count] = integrand(t1,t)
            
        for atom in range(N):
            q[count,atom] = integrate.trapz(yList[:,atom],t1List)
        
    return q,tList
//  [python]
def calculate_position(coeff, val, vec):
    
    N = len(val)//2
    ti = 0.
    tf = 100.
    num = 3*int(tf-ti)
    tList = np.linspace(ti, tf, num=num)
    
    def integrand(t1,t):
        
        expMat = np.exp(np.dot(np.diag((t-t1)*val),np.ones((2*N,N))), dtype=complex)
        
        gFunc = np.dot(vec[:N,:],np.multiply(expMat,coeff))
        
#        print(tstep)
#        print(gFunc)
        
        #now the force
        force = np.zeros(N)
    
        #cosine driven force
#        w = 1.5
#        force[0] = np.cos(w*t1)
        
        #impulse force
        w = 1.
        force[0] = np.exp(-w*t1)
        force[N-1] = -force[0]
        
        x = np.dot(gFunc,force)
        return np.real(x)
    
    q = np.zeros((num,N))
    
    for count, t in enumerate(tList):
        
        innerNum = 3*int(t)
        t1List = np.linspace(0,t,num=innerNum)
        yList = np.zeros((innerNum,N))
        for t1count,t1 in enumerate(t1List):
            yList[t1count] = integrand(t1,t)
            
        for atom in range(N):
            q[count,atom] = integrate.trapezoid(yList[:,atom],t1List)
        
    return q,tList
//  [python]
def compute_expected_coordinates1D(grid, x0):
    """
    Computes expected value and variance of a 1D grid along its (only) axis.

    :param grid: 1D grid to integrate
    :param x0: coordinates of all points along the integration axis

    :type grid: numpy array
    :type x0: numpy array

    :rtype: float
    :returns:
        * exp_x0 : expected value
        * var_x0 : variance

    """

    # normalize 1D grid
    grid_integral = compute_integral1D(grid, x0)
    prob_x0 = grid / grid_integral

    # get 1D marginals, expected values and variances
    exp_x0 = si.trapz(x0*prob_x0, x=x0)
    var_x0 = si.trapz((x0-exp_x0)*(x0-exp_x0)*prob_x0, x=x0)

    return exp_x0, var_x0
//  [python]
def compute_expected_coordinates1D(grid, x0):
    """
    Computes expected value and variance of a 1D grid along its (only) axis.

    :param grid: 1D grid to integrate
    :param x0: coordinates of all points along the integration axis

    :type grid: numpy array
    :type x0: numpy array

    :rtype: float
    :returns:
        * exp_x0 : expected value
        * var_x0 : variance

    """

    # normalize 1D grid
    grid_integral = compute_integral1D(grid, x0)
    prob_x0 = grid / grid_integral

    # get 1D marginals, expected values and variances
    exp_x0 = si.trapezoid(x0*prob_x0, x=x0)
    var_x0 = si.trapezoid((x0-exp_x0)*(x0-exp_x0)*prob_x0, x=x0)

    return exp_x0, var_x0
//  [python]
def compute_integral3D(grid, x0, x1, x2):
    """
    Computes norm of a 3D grid

    :param grid: 3D grid to integrate
    :param x0: coordinates of all points along axis=0
    :param x1: coordinates of all points along axis=1
    :param x2: coordinates of all points along axis=2

    :type grid: numpy array
    :type x0: numpy array
    :type x1: numpy array
    :type x2: numpy array

    :rtype: float
    :returns: grid norm

    """

    grid_norm = si.trapz(si.trapz(si.trapz(grid, x=x0, axis=0), x=x1, axis=0),
                         x=x2, axis=0)
    return grid_norm
//  [python]
def compute_integral3D(grid, x0, x1, x2):
    """
    Computes norm of a 3D grid

    :param grid: 3D grid to integrate
    :param x0: coordinates of all points along axis=0
    :param x1: coordinates of all points along axis=1
    :param x2: coordinates of all points along axis=2

    :type grid: numpy array
    :type x0: numpy array
    :type x1: numpy array
    :type x2: numpy array

    :rtype: float
    :returns: grid norm

    """

    grid_norm = si.trapezoid(si.trapezoid(si.trapezoid(grid, x=x0, axis=0), x=x1, axis=0),
                         x=x2, axis=0)
    return grid_norm
//  [python]
def compute_integral4D(grid, x0, x1, x2, x3):
    """
    Computes norm of a 4D grid

    :param grid: 4D grid to integrate
    :param x0: coordinates of all points along axis=0
    :param x1: coordinates of all points along axis=1
    :param x2: coordinates of all points along axis=2
    :param x3: coordinates of all points along axis=3

    :type grid: numpy array
    :type x0: numpy array
    :type x1: numpy array
    :type x2: numpy array
    :type x3: numpy array

    :rtype: float
    :returns: grid norm

    """

    grid_norm = si.trapz(si.trapz(si.trapz(si.trapz(grid, x=x0, axis=0),
                                           x=x1, axis=0), x=x2, axis=0),
                         x=x3, axis=0)
    return grid_norm
//  [python]
def compute_integral4D(grid, x0, x1, x2, x3):
    """
    Computes norm of a 4D grid

    :param grid: 4D grid to integrate
    :param x0: coordinates of all points along axis=0
    :param x1: coordinates of all points along axis=1
    :param x2: coordinates of all points along axis=2
    :param x3: coordinates of all points along axis=3

    :type grid: numpy array
    :type x0: numpy array
    :type x1: numpy array
    :type x2: numpy array
    :type x3: numpy array

    :rtype: float
    :returns: grid norm

    """

    grid_norm = si.trapezoid(si.trapezoid(si.trapezoid(si.trapezoid(grid, x=x0, axis=0),
                                           x=x1, axis=0), x=x2, axis=0),
                         x=x3, axis=0)
    return grid_norm
//  [python]
def HW_A(lambd,eta,P0T,T1,T2):
    tau = T2-T1
    zGrid = np.linspace(0.0,tau,250)
    B_r = lambda tau: 1.0/lambd * (np.exp(-lambd *tau)-1.0)
    theta = HW_theta(lambd,eta,P0T)    
    temp1 = lambd * integrate.trapz(theta(T2-zGrid)*B_r(zGrid),zGrid)  
    temp2 = eta*eta/(4.0*np.power(lambd,3.0)) * (np.exp(-2.0*lambd*tau)*(4*np.exp(lambd*tau)-1.0) -3.0) + eta*eta*tau/(2.0*lambd*lambd)
    return temp1 + temp2
//  [python]
def HW_A(lambd,eta,P0T,T1,T2):
    tau = T2-T1
    zGrid = np.linspace(0.0,tau,250)
    B_r = lambda tau: 1.0/lambd * (np.exp(-lambd *tau)-1.0)
    theta = HW_theta(lambd,eta,P0T)    
    temp1 = lambd * integrate.trapezoid(theta(T2-zGrid)*B_r(zGrid),zGrid)  
    temp2 = eta*eta/(4.0*np.power(lambd,3.0)) * (np.exp(-2.0*lambd*tau)*(4*np.exp(lambd*tau)-1.0) -3.0) + eta*eta*tau/(2.0*lambd*lambd)
    return temp1 + temp2
//  [python]
def HWMean_r(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.0*dt)
    # Initial interest rate is a forward rate at time t->0
    r0 = f0T(0.00001)
    theta = HW_theta(lambd,eta,P0T)
    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_r(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.0*dt)
    # Initial interest rate is a forward rate at time t->0
    r0 = f0T(0.00001)
    theta = HW_theta(lambd,eta,P0T)
    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 '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 '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 HWMean_r(P0T,lambd,eta,T):

    # time step 
    dt = 0.0001    
    f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2.0*dt)
    # Initial interest rate is a forward rate at time t->0
    r0 = f0T(0.00001)
    theta = HW_theta(lambd,eta,P0T)
    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_r(P0T,lambd,eta,T):

    # time step 
    dt = 0.0001    
    f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2.0*dt)
    # Initial interest rate is a forward rate at time t->0
    r0 = f0T(0.00001)
    theta = HW_theta(lambd,eta,P0T)
    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 __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.magnitude
            unit = str(wavelength.units)
        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()
        self._cl        = self._lT / self.norm
//  [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.magnitude
            unit = str(wavelength.units)
        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       = trapezoid(self.transmit, self._wavelength)
        self._lT        = trapezoid(self._wavelength * self.transmit, self._wavelength)
        self._lpivot    = self._calculate_lpivot()
        self._cl        = self._lT / self.norm
//  [python]
def calc_mobility(self):
        time_series = self.evolve_times
        corr_real = self.auto_corr.real
        inte = scipy.integrate.trapz(corr_real, time_series)
        mobility_in_au = inte / self.temperature.as_au()
        mobility = mobility_in_au / mobility2au
        return mobility_in_au, mobility
//  [python]
def calc_mobility(self):
        time_series = self.evolve_times
        corr_real = self.auto_corr.real
        inte = scipy.integrate.trapezoid(corr_real, time_series)
        mobility_in_au = inte / self.temperature.as_au()
        mobility = mobility_in_au / mobility2au
        return mobility_in_au, mobility
//  [python]
def alpha_mu_BER_NEP_fixed(alpha,mu,r,Ie,NEP,BW):
    u = np.linspace(0,100,10000)
    integrand = alpha_mu_pdf(alpha,mu,r,Ie,u)*scsp.erfc(SNR0_NEP(u,NEP,BW)*u/(2*np.sqrt(2)))
    return 0.5*scin.trapz(integrand,u)
//  [python]
def alpha_mu_BER_NEP_fixed(alpha,mu,r,Ie,NEP,BW):
    u = np.linspace(0,100,10000)
    integrand = alpha_mu_pdf(alpha,mu,r,Ie,u)*scsp.erfc(SNR0_NEP(u,NEP,BW)*u/(2*np.sqrt(2)))
    return 0.5*scin.trapezoid(integrand,u)
//  [python]
def get_aoacl0_from_camber(x, y):
    """
    This section provies the angle of attack of zero lift for a thin
    airfoil which camber line is defined by 'x' and 'y' coordinates

    Check Theory of wing sections. Abbott. pg 69
    """

    # Scale
    c = x[-1] - x[0]
    xc = (x - x[0])/c
    yc = (y - y[0])/c

    # Remove the first and last points that may give rise to problems
    xc = xc[1:-1]
    yc = yc[1:-1]

    f1 = 1./(np.pi*(1-xc)*np.sqrt(xc*(1-xc)))
    int = yc*f1

    return -scipy.integrate.trapz(int, xc)
//  [python]
def get_aoacl0_from_camber(x, y):
    """
    This section provies the angle of attack of zero lift for a thin
    airfoil which camber line is defined by 'x' and 'y' coordinates

    Check Theory of wing sections. Abbott. pg 69
    """

    # Scale
    c = x[-1] - x[0]
    xc = (x - x[0])/c
    yc = (y - y[0])/c

    # Remove the first and last points that may give rise to problems
    xc = xc[1:-1]
    yc = yc[1:-1]

    f1 = 1./(np.pi*(1-xc)*np.sqrt(xc*(1-xc)))
    int = yc*f1

    return -scipy.integrate.trapezoid(int, xc)
//  [python]
def HW_Mu_FrwdMeasure(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 a forward rate at time t->0
    r0 = f0T(0.00001)
    theta = HW_theta(lambd,eta,P0T)
    zGrid = np.linspace(0.0,T,500)
    
    theta_hat =lambda t,T:  theta(t) + eta*eta / lambd *1.0/lambd * (np.exp(-lambd*(T-t))-1.0)
    
    temp =lambda z: theta_hat(z,T) * np.exp(-lambd*(T-z))
    
    r_mean = r0*np.exp(-lambd*T) + lambd * integrate.trapz(temp(zGrid),zGrid)
    
    return r_mean
//  [python]
def HW_Mu_FrwdMeasure(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 a forward rate at time t->0
    r0 = f0T(0.00001)
    theta = HW_theta(lambd,eta,P0T)
    zGrid = np.linspace(0.0,T,500)
    
    theta_hat =lambda t,T:  theta(t) + eta*eta / lambd *1.0/lambd * (np.exp(-lambd*(T-t))-1.0)
    
    temp =lambda z: theta_hat(z,T) * np.exp(-lambd*(T-z))
    
    r_mean = r0*np.exp(-lambd*T) + lambd * integrate.trapezoid(temp(zGrid),zGrid)
    
    return r_mean
//  [python]
def get_mu0_from_camber(x, y):
    """
    This funrcion provides the constant :math:`\mu_0` for a thin
    airfoil which camber line is defined by 'x' and 'y' coordinates

    Check Theory of wing sections. Abbott. pg 69
    """

    # Scale
    c = x[-1] - x[0]
    xc = (x - x[0])/c
    yc = (y - y[0])/c

    # Remove the first and last points that may give rise to problems
    xc = xc[1:-1]
    yc = yc[1:-1]

    f2 = (1. - 2*xc)/np.sqrt(xc*(1. - xc))
    int = yc*f2

    return scipy.integrate.trapz(int, xc)
//  [python]
def get_mu0_from_camber(x, y):
    """
    This funrcion provides the constant :math:`\mu_0` for a thin
    airfoil which camber line is defined by 'x' and 'y' coordinates

    Check Theory of wing sections. Abbott. pg 69
    """

    # Scale
    c = x[-1] - x[0]
    xc = (x - x[0])/c
    yc = (y - y[0])/c

    # Remove the first and last points that may give rise to problems
    xc = xc[1:-1]
    yc = yc[1:-1]

    f2 = (1. - 2*xc)/np.sqrt(xc*(1. - xc))
    int = yc*f2

    return scipy.integrate.trapezoid(int, xc)
//  [python]
def compute_L2_error(self, n, rates):
        from scipy.integrate import odeint, trapz
        bfc = self._bfc

        def fun(data, _):
            theta = np.array([f(data) for f in bfc.functions])
            return np.matmul(rates, theta)

        def fun_reference(data, _):
            theta = np.array([f(data) for f in bfc.functions])
            return np.matmul(self._desired_rates, theta)

        traj = self.get_traj(n)
        xs = traj.times
        num_solution = np.array(odeint(fun, self.initial_states[n].squeeze(), xs)).squeeze()
        reference_soln = np.array(odeint(fun_reference, np.array(self.initial_states[n]).squeeze(), xs)).squeeze()

        err = 0.
        for i in range(traj.n_species):
            err += trapz(np.abs(num_solution[:, i] - reference_soln[:, i]), x=xs)
        return err
//  [python]
def compute_L2_error(self, n, rates):
        from scipy.integrate import odeint, trapezoid
        bfc = self._bfc

        def fun(data, _):
            theta = np.array([f(data) for f in bfc.functions])
            return np.matmul(rates, theta)

        def fun_reference(data, _):
            theta = np.array([f(data) for f in bfc.functions])
            return np.matmul(self._desired_rates, theta)

        traj = self.get_traj(n)
        xs = traj.times
        num_solution = np.array(odeint(fun, self.initial_states[n].squeeze(), xs)).squeeze()
        reference_soln = np.array(odeint(fun_reference, np.array(self.initial_states[n]).squeeze(), xs)).squeeze()

        err = 0.
        for i in range(traj.n_species):
            err += trapezoid(np.abs(num_solution[:, i] - reference_soln[:, i]), x=xs)
        return err
//  [python]
def HWMean_r(P0T,lambd,eta,T):

    # Time step 

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

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

    r0 = f0T(0.00001)
    theta = HW_theta(lambd,eta,P0T)
    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_r(P0T,lambd,eta,T):

    # Time step 

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

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

    r0 = f0T(0.00001)
    theta = HW_theta(lambd,eta,P0T)
    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 stiffness_matrix(self,omega,distances,ks,dA,Nstep = 10):
        """
        Calculate stiffness matrix of TMmodel

        Parameters
        ----------
        omega : float
            angular frequency.
        distances : ndarray
            distances for discrete mesh.
        ks : fload
            maximum wavenumber integration limit
        dA : float
            element area
        Nstep : int, optional
            Number of intervals for numeric wavenumber integration. The default is 10.

        Returns
        -------
        D11 : ndarray
            1-1 coeffcient of stifness matrix.
        D12 : ndarray
            1-2 coeffcient of stifness matrix equal to D21.
        D22 : ndarray
            2-2 coeffcient of stifness matrix.

        """
        
        # \todo Calulate wavenumber sampling....
        J_1st_zero = 2.40482556
        dks = J_1st_zero/Nstep
        
        kx = np.linspace(0,ks,int(np.ceil(ks*np.max(distances)/dks))+1)
        fak = dA/2/np.pi
        
        _D = self.stiffness_matrix_wavenumber(omega,kx)
        
        
        # create besselmatrix with rows for distance and coloums for kx 
        J0 = scl.j0(distances.reshape(-1,1) @ kx.reshape(1,-1) )
        D11 = fak*integrate.trapz(_D[0,0,:].data.flatten()*J0*kx,kx)
        D12 = fak*integrate.trapz(_D[0,1,:].data.flatten()*J0*kx,kx)
        D22 = fak*integrate.trapz(_D[1,1,:].data.flatten()*J0*kx,kx) # ,axis = 1
        
        return (D11,D12,D22)
//  [python]
def stiffness_matrix(self,omega,distances,ks,dA,Nstep = 10):
        """
        Calculate stiffness matrix of TMmodel

        Parameters
        ----------
        omega : float
            angular frequency.
        distances : ndarray
            distances for discrete mesh.
        ks : fload
            maximum wavenumber integration limit
        dA : float
            element area
        Nstep : int, optional
            Number of intervals for numeric wavenumber integration. The default is 10.

        Returns
        -------
        D11 : ndarray
            1-1 coeffcient of stifness matrix.
        D12 : ndarray
            1-2 coeffcient of stifness matrix equal to D21.
        D22 : ndarray
            2-2 coeffcient of stifness matrix.

        """
        
        # \todo Calulate wavenumber sampling....
        J_1st_zero = 2.40482556
        dks = J_1st_zero/Nstep
        
        kx = np.linspace(0,ks,int(np.ceil(ks*np.max(distances)/dks))+1)
        fak = dA/2/np.pi
        
        _D = self.stiffness_matrix_wavenumber(omega,kx)
        
        
        # create besselmatrix with rows for distance and coloums for kx 
        J0 = scl.j0(distances.reshape(-1,1) @ kx.reshape(1,-1) )
        D11 = fak*integrate.trapezoid(_D[0,0,:].data.flatten()*J0*kx,kx)
        D12 = fak*integrate.trapezoid(_D[0,1,:].data.flatten()*J0*kx,kx)
        D22 = fak*integrate.trapezoid(_D[1,1,:].data.flatten()*J0*kx,kx) # ,axis = 1
        
        return (D11,D12,D22)
//  [python]
def calculate_size_distribution_opacity(self, amin, amax, p, \
            coat_volume_fraction=0.0, nang=1000, with_dhs=False, fmax=0.8, \
            nf=50):
        na = int(round(numpy.log10(amax) - numpy.log10(amin))*100+1)
        a = numpy.logspace(numpy.log10(amin),numpy.log10(amax),na)
        kabsgrid = numpy.zeros((self.lam.size,na))
        kscagrid = numpy.zeros((self.lam.size,na))
        
        normfunc = a**(3-p)

        for i in range(na):
            if with_dhs:
                self.calculate_dhs_opacity(a[i], fmax=fmax, nf=nf, nang=nang)
            else:
                self.calculate_opacity(a[i], \
                        coat_volume_fraction=coat_volume_fraction, nang=nang)
            
            kabsgrid[:,i] = self.kabs*normfunc[i]
            kscagrid[:,i] = self.ksca*normfunc[i]
        
        norm = scipy.integrate.trapz(normfunc,x=a)
        
        self.kabs = scipy.integrate.trapz(kabsgrid,x=a)/norm
        self.ksca = scipy.integrate.trapz(kscagrid,x=a)/norm
        self.kext = self.kabs + self.ksca
        self.albedo = self.ksca / self.kext
//  [python]
def calculate_size_distribution_opacity(self, amin, amax, p, \
            coat_volume_fraction=0.0, nang=1000, with_dhs=False, fmax=0.8, \
            nf=50):
        na = int(round(numpy.log10(amax) - numpy.log10(amin))*100+1)
        a = numpy.logspace(numpy.log10(amin),numpy.log10(amax),na)
        kabsgrid = numpy.zeros((self.lam.size,na))
        kscagrid = numpy.zeros((self.lam.size,na))
        
        normfunc = a**(3-p)

        for i in range(na):
            if with_dhs:
                self.calculate_dhs_opacity(a[i], fmax=fmax, nf=nf, nang=nang)
            else:
                self.calculate_opacity(a[i], \
                        coat_volume_fraction=coat_volume_fraction, nang=nang)
            
            kabsgrid[:,i] = self.kabs*normfunc[i]
            kscagrid[:,i] = self.ksca*normfunc[i]
        
        norm = scipy.integrate.trapezoid(normfunc,x=a)
        
        self.kabs = scipy.integrate.trapezoid(kabsgrid,x=a)/norm
        self.ksca = scipy.integrate.trapezoid(kscagrid,x=a)/norm
        self.kext = self.kabs + self.ksca
        self.albedo = self.ksca / self.kext
//  [python]
def compute_expected_coordinates3D(grid, x0, x1, x2, return_2Dgrids=False):
    """
    Computes expected coordinates of a 3D grid

    :param grid: 3D grid to integrate
    :param x0: coordinates of all points along axis=0
    :param x1: coordinates of all points along axis=1
    :param x2: coordinates of all points along axis=2
    :param return_2Dgrids: if ``True`` returns the 1D and 2D marginals in a
        dictionary.

    :type grid: numpy array
    :type x0: numpy array
    :type x1: numpy array
    :type x2: numpy array
    :type return_2Dgrids: boolean

    :rtype: numpy array
    :returns:
        * exp_x0 : expected value along axis=0
        * exp_x1 : expected value along axis=1
        * exp_x2 : expected value along axis=2
        * cov_matrix : covariance matrix
        * grid_dict : dictionary containing 1D and 2D marginals (optional)

    """

    # normalize grid
    grid_integral = compute_integral3D(grid, x0, x1, x2)
    grid = grid / grid_integral

    # get 1D marginals, expected values and variances
    prob_x0 = si.trapz(si.trapz(grid, x=x1, axis=1), x=x2, axis=1)
    exp_x0 = si.trapz(x0*prob_x0, x=x0)
    var_x0 = si.trapz((x0-exp_x0)*(x0-exp_x0)*prob_x0, x=x0)

    prob_x1 = si.trapz(si.trapz(grid, x=x0, axis=0), x=x2, axis=1)
    exp_x1 = si.trapz(x1*prob_x1, x=x1)
    var_x1 = si.trapz((x1-exp_x1)*(x1-exp_x1)*prob_x1, x=x1)

    prob_x2 = si.trapz(si.trapz(grid, x=x0, axis=0), x=x1, axis=0)
    exp_x2 = si.trapz(x2*prob_x2, x=x2)
    var_x2 = si.trapz((x2-exp_x2)*(x2-exp_x2)*prob_x2, x=x2)

    # get 2D marginals and covariances
    prob_x0_x1 = si.trapz(grid, x=x2, axis=2)
    cov_x0_x1 = si.trapz((x0-exp_x0)*si.trapz((x1-exp_x1)*prob_x0_x1,
                                              x=x1, axis=1), x=x0, axis=0)
    prob_x0_x2 = si.trapz(grid, x=x1, axis=1)
    cov_x0_x2 = si.trapz((x0-exp_x0)*si.trapz((x2-exp_x2)*prob_x0_x2,
                                              x=x2, axis=1), x=x0, axis=0)
    prob_x1_x2 = si.trapz(grid, x=x0, axis=0)
    cov_x1_x2 = si.trapz((x1-exp_x1)*si.trapz((x2-exp_x2)*prob_x1_x2,
                                              x=x2, axis=1), x=x1, axis=0)

    # set up covariance matrix
    cov_matrix = np.eye(3)
    cov_matrix[0, 0] = var_x0
    cov_matrix[1, 1] = var_x1
    cov_matrix[2, 2] = var_x2

    cov_matrix[0, 1] = cov_x0_x1
    cov_matrix[1, 0] = cov_x0_x1

    cov_matrix[0, 2] = cov_x0_x2
    cov_matrix[2, 0] = cov_x0_x2

    cov_matrix[1, 2] = cov_x1_x2
    cov_matrix[2, 1] = cov_x1_x2

    logging.debug('Type prob_x0 = %s' % prob_x0.dtype)

    if return_2Dgrids:
        grid_dict = {}
        grid_dict['prob_x0'] = prob_x0
        grid_dict['prob_x1'] = prob_x1
        grid_dict['prob_x2'] = prob_x2
        grid_dict['prob_x0_x1'] = prob_x0_x1
        grid_dict['prob_x0_x2'] = prob_x0_x2
        grid_dict['prob_x1_x2'] = prob_x1_x2

        return exp_x0, exp_x1, exp_x2, cov_matrix, grid_dict
    else:
        return exp_x0, exp_x1, exp_x2, cov_matrix
//  [python]
def compute_expected_coordinates3D(grid, x0, x1, x2, return_2Dgrids=False):
    """
    Computes expected coordinates of a 3D grid

    :param grid: 3D grid to integrate
    :param x0: coordinates of all points along axis=0
    :param x1: coordinates of all points along axis=1
    :param x2: coordinates of all points along axis=2
    :param return_2Dgrids: if ``True`` returns the 1D and 2D marginals in a
        dictionary.

    :type grid: numpy array
    :type x0: numpy array
    :type x1: numpy array
    :type x2: numpy array
    :type return_2Dgrids: boolean

    :rtype: numpy array
    :returns:
        * exp_x0 : expected value along axis=0
        * exp_x1 : expected value along axis=1
        * exp_x2 : expected value along axis=2
        * cov_matrix : covariance matrix
        * grid_dict : dictionary containing 1D and 2D marginals (optional)

    """

    # normalize grid
    grid_integral = compute_integral3D(grid, x0, x1, x2)
    grid = grid / grid_integral

    # get 1D marginals, expected values and variances
    prob_x0 = si.trapezoid(si.trapezoid(grid, x=x1, axis=1), x=x2, axis=1)
    exp_x0 = si.trapezoid(x0*prob_x0, x=x0)
    var_x0 = si.trapezoid((x0-exp_x0)*(x0-exp_x0)*prob_x0, x=x0)

    prob_x1 = si.trapezoid(si.trapezoid(grid, x=x0, axis=0), x=x2, axis=1)
    exp_x1 = si.trapezoid(x1*prob_x1, x=x1)
    var_x1 = si.trapezoid((x1-exp_x1)*(x1-exp_x1)*prob_x1, x=x1)

    prob_x2 = si.trapezoid(si.trapezoid(grid, x=x0, axis=0), x=x1, axis=0)
    exp_x2 = si.trapezoid(x2*prob_x2, x=x2)
    var_x2 = si.trapezoid((x2-exp_x2)*(x2-exp_x2)*prob_x2, x=x2)

    # get 2D marginals and covariances
    prob_x0_x1 = si.trapezoid(grid, x=x2, axis=2)
    cov_x0_x1 = si.trapezoid((x0-exp_x0)*si.trapezoid((x1-exp_x1)*prob_x0_x1,
                                              x=x1, axis=1), x=x0, axis=0)
    prob_x0_x2 = si.trapezoid(grid, x=x1, axis=1)
    cov_x0_x2 = si.trapezoid((x0-exp_x0)*si.trapezoid((x2-exp_x2)*prob_x0_x2,
                                              x=x2, axis=1), x=x0, axis=0)
    prob_x1_x2 = si.trapezoid(grid, x=x0, axis=0)
    cov_x1_x2 = si.trapezoid((x1-exp_x1)*si.trapezoid((x2-exp_x2)*prob_x1_x2,
                                              x=x2, axis=1), x=x1, axis=0)

    # set up covariance matrix
    cov_matrix = np.eye(3)
    cov_matrix[0, 0] = var_x0
    cov_matrix[1, 1] = var_x1
    cov_matrix[2, 2] = var_x2

    cov_matrix[0, 1] = cov_x0_x1
    cov_matrix[1, 0] = cov_x0_x1

    cov_matrix[0, 2] = cov_x0_x2
    cov_matrix[2, 0] = cov_x0_x2

    cov_matrix[1, 2] = cov_x1_x2
    cov_matrix[2, 1] = cov_x1_x2

    logging.debug('Type prob_x0 = %s' % prob_x0.dtype)

    if return_2Dgrids:
        grid_dict = {}
        grid_dict['prob_x0'] = prob_x0
        grid_dict['prob_x1'] = prob_x1
        grid_dict['prob_x2'] = prob_x2
        grid_dict['prob_x0_x1'] = prob_x0_x1
        grid_dict['prob_x0_x2'] = prob_x0_x2
        grid_dict['prob_x1_x2'] = prob_x1_x2

        return exp_x0, exp_x1, exp_x2, cov_matrix, grid_dict
    else:
        return exp_x0, exp_x1, exp_x2, cov_matrix
//  [python]
def HW_Mu_FrwdMeasure(P0T,lambd,eta,T):

    # Time step 

    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 = HW_theta(lambd,eta,P0T)
    zGrid = np.linspace(0.0,T,500)
    
    theta_hat =lambda t,T:  theta(t) + eta*eta / lambd *1.0/lambd * (np.exp(-lambd*(T-t))-1.0)
    
    temp =lambda z: theta_hat(z,T) * np.exp(-lambd*(T-z))
    
    r_mean = r0*np.exp(-lambd*T) + lambd * integrate.trapz(temp(zGrid),zGrid)
    
    return r_mean
//  [python]
def HW_Mu_FrwdMeasure(P0T,lambd,eta,T):

    # Time step 

    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 = HW_theta(lambd,eta,P0T)
    zGrid = np.linspace(0.0,T,500)
    
    theta_hat =lambda t,T:  theta(t) + eta*eta / lambd *1.0/lambd * (np.exp(-lambd*(T-t))-1.0)
    
    temp =lambda z: theta_hat(z,T) * np.exp(-lambd*(T-z))
    
    r_mean = r0*np.exp(-lambd*T) + lambd * integrate.trapezoid(temp(zGrid),zGrid)
    
    return r_mean
//  [python]
def fwd_model_1d(arr, x, z, R, varsigma=1):
    """
    Apply fwd model to arbitrary space-time array arr; predicts at same time points as input.
    (Note: want dense input within integral bounds to get good results!)
    :param arr: matrix (nz, nt)
    :param x: x vector of observations
    :param z: z vector for predictions (can differ from x)
    :param R: forward model parameter
    :param varsigma: scalar conductivity
    :return: matrix (nx, nt)
    """
    nx, nt = arr.shape
    nz = z.shape[0]
    res = np.zeros((nz, nt))
    for t in range(nt):
        arr_tmp = np.squeeze(arr[:, t])[:,None]
        for i in range(nz):
            A = b_fwd_1d(z[i]-x, R)
            res[i, t] = scipy.integrate.trapz(np.squeeze(A * arr_tmp), x=np.squeeze(x), axis=0)
    return R/(2*varsigma) * res
//  [python]
def fwd_model_1d(arr, x, z, R, varsigma=1):
    """
    Apply fwd model to arbitrary space-time array arr; predicts at same time points as input.
    (Note: want dense input within integral bounds to get good results!)
    :param arr: matrix (nz, nt)
    :param x: x vector of observations
    :param z: z vector for predictions (can differ from x)
    :param R: forward model parameter
    :param varsigma: scalar conductivity
    :return: matrix (nx, nt)
    """
    nx, nt = arr.shape
    nz = z.shape[0]
    res = np.zeros((nz, nt))
    for t in range(nt):
        arr_tmp = np.squeeze(arr[:, t])[:,None]
        for i in range(nz):
            A = b_fwd_1d(z[i]-x, R)
            res[i, t] = scipy.integrate.trapezoid(np.squeeze(A * arr_tmp), x=np.squeeze(x), axis=0)
    return R/(2*varsigma) * res
//  [python]
def _guess_area(bands, intensities, loc):
  idx = np.searchsorted(bands, loc)
  i, j = max(0, idx-4), idx+5
  area_guess = scipy.integrate.trapz(intensities[i:j], bands[i:j])
  return max(0, area_guess)
//  [python]
def _guess_area(bands, intensities, loc):
  idx = np.searchsorted(bands, loc)
  i, j = max(0, idx-4), idx+5
  area_guess = scipy.integrate.trapezoid(intensities[i:j], bands[i:j])
  return max(0, area_guess)
//  [python]
def fwd_model_2d(arr, x1, x2, z, R, eps, varsigma=1):
    """
    Apply fwd model to space-time array arr (must be on grid of spatial locs); predicts at same time points as input.
    (Note: want dense input within integral bounds to get good results!) Output can be requested on non-grid.
    :param arr: matrix (nx1, nx2, nt)
    :param x1: x1 (nx1, 1) vector of observation spatial locations
    :param x2: x2 (nx2, 1) vector of observation spatial locations
    :param z: z (nz, 2) matrix of predicted spatial locations
    :param R: forward model parameter
    :param eps: forward model singularity parameter
    :param varsigma: scalar conductivity
    :return: matrix (nz, nt)
    """
    nt = arr.shape[2]
    nz = z.shape[0]
    res = np.zeros((nz, nt))
    for t in range(nt):
        arr_tmp = np.squeeze(arr[:, :, t]) # (nx1, nx2)
        for i in range(nz):
            deltax1 = z[i,0] - x1   # (nx1, 1)
            deltax2 = z[i,1] - x2.T # (1, nx2)
            wt = b_fwd_2d(deltax1, deltax2, R, eps)
            toint = wt * arr_tmp # (nx1, nx2)
            res[i, t] = scipy.integrate.trapz(scipy.integrate.trapz(toint, x=np.squeeze(x1), axis=0), x=np.squeeze(x2), axis=0)
    return res
//  [python]
def fwd_model_2d(arr, x1, x2, z, R, eps, varsigma=1):
    """
    Apply fwd model to space-time array arr (must be on grid of spatial locs); predicts at same time points as input.
    (Note: want dense input within integral bounds to get good results!) Output can be requested on non-grid.
    :param arr: matrix (nx1, nx2, nt)
    :param x1: x1 (nx1, 1) vector of observation spatial locations
    :param x2: x2 (nx2, 1) vector of observation spatial locations
    :param z: z (nz, 2) matrix of predicted spatial locations
    :param R: forward model parameter
    :param eps: forward model singularity parameter
    :param varsigma: scalar conductivity
    :return: matrix (nz, nt)
    """
    nt = arr.shape[2]
    nz = z.shape[0]
    res = np.zeros((nz, nt))
    for t in range(nt):
        arr_tmp = np.squeeze(arr[:, :, t]) # (nx1, nx2)
        for i in range(nz):
            deltax1 = z[i,0] - x1   # (nx1, 1)
            deltax2 = z[i,1] - x2.T # (1, nx2)
            wt = b_fwd_2d(deltax1, deltax2, R, eps)
            toint = wt * arr_tmp # (nx1, nx2)
            res[i, t] = scipy.integrate.trapezoid(scipy.integrate.trapezoid(toint, x=np.squeeze(x1), axis=0), x=np.squeeze(x2), axis=0)
    return res
//  [python]
def get_sed(self):
        """Specific Energy Density (SED).
        """
        sed = trapz(self.vel ** 2, self.time)
        return sed
//  [python]
def get_sed(self):
        """Specific Energy Density (SED).
        """
        sed = trapezoid(self.vel ** 2, self.time)
        return sed
//  [python]
def L_villar(self, times, omegas, glob_vars, glob_params, NN=100):
        td                 = np.sqrt( (8 * self.opacity * np.pi * self.mass_ej * utils.Msun / omegas) / (13.4 * self.vel_rms * utils.c**2) )
        _, td_NN           = np.meshgrid(np.zeros(NN), td)
        _, td              = np.meshgrid(times, td)
        init_x             = np.logspace(-3, np.log10(times[0]), NN)
        init_int           = integrate.trapz(self.L_in(omegas, init_x, glob_vars, glob_params) * np.exp((init_x**2)/(td_NN**2)) * (init_x/td_NN), init_x)
        _, init_int        = np.meshgrid(times, init_int)
        t_cut              = (times / td)**2
        t_cut[t_cut > 500] = 500
        tmp                = self.L_in(omegas, times, glob_vars, glob_params) * np.exp(t_cut) * (times/td)
        return integrate.cumtrapz(tmp, times, initial=0) + init_int * np.exp(-(times / td)**2.) / td
//  [python]
def L_villar(self, times, omegas, glob_vars, glob_params, NN=100):
        td                 = np.sqrt( (8 * self.opacity * np.pi * self.mass_ej * utils.Msun / omegas) / (13.4 * self.vel_rms * utils.c**2) )
        _, td_NN           = np.meshgrid(np.zeros(NN), td)
        _, td              = np.meshgrid(times, td)
        init_x             = np.logspace(-3, np.log10(times[0]), NN)
        init_int           = integrate.trapezoid(self.L_in(omegas, init_x, glob_vars, glob_params) * np.exp((init_x**2)/(td_NN**2)) * (init_x/td_NN), init_x)
        _, init_int        = np.meshgrid(times, init_int)
        t_cut              = (times / td)**2
        t_cut[t_cut > 500] = 500
        tmp                = self.L_in(omegas, times, glob_vars, glob_params) * np.exp(t_cut) * (times/td)
        return integrate.cumtrapz(tmp, times, initial=0) + init_int * np.exp(-(times / td)**2.) / td
//  [python]
def rebin(x, y, binedges):
    """
    Seth Meeker 1-29-2013
    Given arrays of wavelengths and fluxes (x and y) rebins to specified bin size by taking average value of input data within each bin
    use: rebinnedData = rebin(x,y,binedges)
    binedges typically can be imported from a FlatCal after being applied in an Photontable
    returns rebinned data as 2D array:
        rebinned[:,0] = centers of wvl bins
        rebinned[:,1] = average of y-values per new bins
    """
    # must be passed binedges array since spectra will not be binned with evenly sized bins
    start = binedges[0]
    stop = binedges[-1]
    # calculate how many new bins we will have
    nbins = len(binedges) - 1
    # create output arrays
    rebinned = np.zeros((nbins, 2), dtype=float)
    for i in range(nbins):
        rebinned[i, 0] = binedges[i] + (binedges[i + 1] - binedges[i]) / 2.0
    n = 0
    binsize = binedges[n + 1] - binedges[n]
    while start + (binsize / 2.0) < stop:
        rebinned[n, 0] = (start + (binsize / 2.0))
        ind = np.where((x > start) & (x < start + binsize))
        rebinned[n, 1] = (scipy.integrate.trapz(y[ind], x=x[ind])) / binsize
        start += binsize
        n += 1
        try:
            binsize = binedges[n + 1] - binedges[n]
        except IndexError:
            break
    return rebinned
//  [python]
def rebin(x, y, binedges):
    """
    Seth Meeker 1-29-2013
    Given arrays of wavelengths and fluxes (x and y) rebins to specified bin size by taking average value of input data within each bin
    use: rebinnedData = rebin(x,y,binedges)
    binedges typically can be imported from a FlatCal after being applied in an Photontable
    returns rebinned data as 2D array:
        rebinned[:,0] = centers of wvl bins
        rebinned[:,1] = average of y-values per new bins
    """
    # must be passed binedges array since spectra will not be binned with evenly sized bins
    start = binedges[0]
    stop = binedges[-1]
    # calculate how many new bins we will have
    nbins = len(binedges) - 1
    # create output arrays
    rebinned = np.zeros((nbins, 2), dtype=float)
    for i in range(nbins):
        rebinned[i, 0] = binedges[i] + (binedges[i + 1] - binedges[i]) / 2.0
    n = 0
    binsize = binedges[n + 1] - binedges[n]
    while start + (binsize / 2.0) < stop:
        rebinned[n, 0] = (start + (binsize / 2.0))
        ind = np.where((x > start) & (x < start + binsize))
        rebinned[n, 1] = (scipy.integrate.trapezoid(y[ind], x=x[ind])) / binsize
        start += binsize
        n += 1
        try:
            binsize = binedges[n + 1] - binedges[n]
        except IndexError:
            break
    return rebinned
//  [python]
def get_rms(self):
        """Root-mean-square (RMS) of acceleration, velocity and displacement.
        """
        Arms = np.sqrt(trapz(self.acc ** 2, self.time) / self.time[-1])
        Vrms = np.sqrt(trapz(self.vel ** 2, self.time) / self.time[-1])
        Drms = np.sqrt(trapz(self.disp ** 2, self.time) / self.time[-1])
        return Arms, Vrms, Drms
//  [python]
def get_rms(self):
        """Root-mean-square (RMS) of acceleration, velocity and displacement.
        """
        Arms = np.sqrt(scipy.integrate.trapezoid(self.acc ** 2, self.time) / self.time[-1])
        Vrms = np.sqrt(scipy.integrate.trapezoid(self.vel ** 2, self.time) / self.time[-1])
        Drms = np.sqrt(scipy.integrate.trapezoid(self.disp ** 2, self.time) / self.time[-1])
        return Arms, Vrms, Drms
//  [python]
def prior_energy_balance(data, GALAXYatt_dict, GALAXYFdict, gal_obj, GA, STARBURST_LIRdict,sb_obj,SB, models):

    if gal_obj.par_types[-1] == 'grid':
        Lgal_att = GALAXYatt_dict[tuple(gal_obj.matched_parkeys_grid)] * 10**(GA)

    elif gal_obj.par_types[-1] == 'free':
        bands, gal_Fnu= GALAXYFdict[tuple(gal_obj.matched_parkeys_grid)]        #frequencies in log
        fcts=gal_obj.functions()
        f=fcts[gal_obj.functionidxs[0]]
        rest_bands = bands + np.log10((1+data.z))                               #Pass to rest frame
        bandsf, Fnuf = f(10**rest_bands, gal_Fnu*1e18, gal_obj.matched_parkeys[-1])  #bandsf not in log form, apply reddening
        gal_nu, gal_Fnu_red = bandsf/(1+data.z), Fnuf                           #Pass to observed frame
        gal_Fnu_int = scipy.integrate.trapz(gal_Fnu*3.826e33, x=gal_nu)          
        gal_Fnured_int = scipy.integrate.trapz(gal_Fnu_red*3.826e33, x=gal_nu)
        gal_att_int = gal_Fnu_int - gal_Fnured_int
        Lgal_att = abs(gal_att_int * 10**(GA))                                       #Calculate the attenuated luminosity

    Lsb_emit = STARBURST_LIRdict[sb_obj.matched_parkeys] * 10**(SB)

    if Lsb_emit < Lgal_att:
        return -9999 #-np.inf
    elif (Lsb_emit >= Lgal_att) and (models.settings['PRIOR_energy_balance'] == 'Flexible'):
        return 0
    elif (Lsb_emit >= Lgal_att) and (models.settings['PRIOR_energy_balance'] == 'Restrictive'):
        frac_SB_attGal = np.log10(Lsb_emit/Lgal_att)
        mu = 0
        sigma = 0.1
        prior_frac = Gaussian_prior(mu, sigma, frac_SB_attGal)
        return prior_frac