jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def _cumul_simpson(theta, cl, nmax, thetamax, cl_mask=None):
    '''
    Notes
    -----
    This calculates the two integrals in Eq. 90
    '''

    npoints = 2.0**(nmax-1)
    step = thetamax / npoints

    beta = np.linspace(0.0, thetamax, num=npoints+1)

    c_plus = _cplus(np.cos(beta), cl, cl_mask=cl_mask)
    ftemp1 = np.sin(beta)/np.cos(beta/2.0)**4 * c_plus
    ftemp2 = np.tan(beta/2.0)**3 * c_plus

    nell = len(cl[0])

    sum1 = np.zeros(nell)
    sum2 = np.zeros(nell)
    lastn = 2*np.array(np.round(theta/(2.0*step)), dtype=int)

    for j in range(nell):
        if lastn[j] != 0:
            sum1[j] = scipy.integrate.simpson(ftemp1[:lastn[j]+1], dx=step)
            sum2[j] = scipy.integrate.simpson(ftemp2[:lastn[j]+1], dx=step)

    #Since beta[lastn[j]] is not exactly theta[j], we apply the basic Simpson's rule on
    #the small interval between those two values
    step2 = (theta - step*lastn) / 2.0
    theta0 = theta-step2
    theta1 = theta

    c_plus0 = _cplus(np.cos(theta0), cl, cl_mask=cl_mask)
    c_plus1 = _cplus(np.cos(theta1), cl, cl_mask=cl_mask)

    int1_0 = np.sin(theta0)/np.cos(theta0/2.0)**4 * c_plus0
    int1_1 = np.sin(theta1)/np.cos(theta1/2.0)**4 * c_plus1
    int2_0 = np.tan(theta0/2.0)**3 * c_plus0
    int2_1 = np.tan(theta1/2.0)**3 * c_plus1

    endpoint = step2*(ftemp1[lastn] + 4.0 * int1_0 + int1_1) / 3.0
    sum1 += endpoint

    endpoint = step2*(ftemp2[lastn] + 4.0 * int2_0 + int2_1) / 3.0
    sum2 += endpoint

    return sum1, sum2
//  [python]
def true_sec_energy_PDF(self, delta_ts, nn, E_0, energy):
        """The PDF for true secondary electrons."""
        if nn == 0:
            raise ValueError('nn = 0, you cannot emit zero electrons.')
        p_n = self.p_n
        eps_n = self.eps_n

        nn_all = np.arange(0, self.M_cut + 1, 1)

        if self.choice == 'poisson':
            P_n_ts = np.squeeze(delta_ts**nn_all / factorial(nn_all) * np.exp(-delta_ts))
        elif self.choice == 'binomial':
            p = delta_ts / self.M_cut
            P_n_ts = np.squeeze(binom(self.M_cut, nn) * (p)**nn_all * (1 - p)**(self.M_cut - nn_all))
        else:
            raise ValueError('choice must be either \'poisson\' or \'binomial\'')

        P_n_ts = P_n_ts / np.sum(P_n_ts)
        P_n_ts_return = P_n_ts[int(nn)]
        eps_curr = eps_n[int(nn - 1)]
        p_n_curr = p_n[int(nn - 1)]

        if E_0 == 0:
            F_n = 0
        else:
            F_n = 1
        f_n_ts = F_n * energy**(p_n_curr - 1) * np.exp(-energy / eps_curr)
        area = scipy.integrate.simps(f_n_ts, energy)
        f_n_ts = f_n_ts / area  # normalisation

        return f_n_ts, P_n_ts_return
//  [python]
def true_sec_energy_PDF(self, delta_ts, nn, E_0, energy):
        """The PDF for true secondary electrons."""
        if nn == 0:
            raise ValueError('nn = 0, you cannot emit zero electrons.')
        p_n = self.p_n
        eps_n = self.eps_n

        nn_all = np.arange(0, self.M_cut + 1, 1)

        if self.choice == 'poisson':
            P_n_ts = np.squeeze(delta_ts**nn_all / factorial(nn_all) * np.exp(-delta_ts))
        elif self.choice == 'binomial':
            p = delta_ts / self.M_cut
            P_n_ts = np.squeeze(binom(self.M_cut, nn) * (p)**nn_all * (1 - p)**(self.M_cut - nn_all))
        else:
            raise ValueError('choice must be either \'poisson\' or \'binomial\'')

        P_n_ts = P_n_ts / np.sum(P_n_ts)
        P_n_ts_return = P_n_ts[int(nn)]
        eps_curr = eps_n[int(nn - 1)]
        p_n_curr = p_n[int(nn - 1)]

        if E_0 == 0:
            F_n = 0
        else:
            F_n = 1
        f_n_ts = F_n * energy**(p_n_curr - 1) * np.exp(-energy / eps_curr)
        area = scipy.integrate.simpson(f_n_ts, energy)
        f_n_ts = f_n_ts / area  # normalisation

        return f_n_ts, P_n_ts_return
//  [python]
def integrate_line(self):
        """
        Integrate the line using Simpson's method.
        """
        return simps(self.f,self.wv)
//  [python]
def integrate_line(self):
        """
        Integrate the line using Simpson's method.
        """
        return simpson(self.f,self.wv)
//  [python]
def average_true_sec_energy_PDF(self, delta_ts, E_0, energy):
        nns = np.arange(1, self.M_cut + 1, 1)
        average_f_n_ts = np.zeros_like(energy)
        for ii in nns:
            f_n_ts, P_n_ts = self.true_sec_energy_PDF(delta_ts=delta_ts, nn=ii, E_0=E_0, energy=energy)
            if False:#self.conserve_energy:
                p_n_curr = self.p_n[ii - 1]
                eps_n_curr = self.eps_n[ii - 1]
                factor = eps_n_curr**p_n_curr * gamma(p_n_curr) * gammainc(ii * p_n_curr, E_0 / eps_n_curr)
                factor = 1.
                if ii - 1 == 0:
                    average_f_n_ts = average_f_n_ts + f_n_ts * P_n_ts * ii * 1. / factor
                else:
                    average_f_n_ts = average_f_n_ts + f_n_ts * P_n_ts * ii * gammainc((ii - 1) * p_n_curr, (E_0 - energy) / eps_n_curr) / factor
            else:
                average_f_n_ts = average_f_n_ts + f_n_ts * P_n_ts * ii
        area = scipy.integrate.simps(average_f_n_ts, energy)
        return average_f_n_ts / area
//  [python]
def average_true_sec_energy_PDF(self, delta_ts, E_0, energy):
        nns = np.arange(1, self.M_cut + 1, 1)
        average_f_n_ts = np.zeros_like(energy)
        for ii in nns:
            f_n_ts, P_n_ts = self.true_sec_energy_PDF(delta_ts=delta_ts, nn=ii, E_0=E_0, energy=energy)
            if False:#self.conserve_energy:
                p_n_curr = self.p_n[ii - 1]
                eps_n_curr = self.eps_n[ii - 1]
                factor = eps_n_curr**p_n_curr * gamma(p_n_curr) * gammainc(ii * p_n_curr, E_0 / eps_n_curr)
                factor = 1.
                if ii - 1 == 0:
                    average_f_n_ts = average_f_n_ts + f_n_ts * P_n_ts * ii * 1. / factor
                else:
                    average_f_n_ts = average_f_n_ts + f_n_ts * P_n_ts * ii * gammainc((ii - 1) * p_n_curr, (E_0 - energy) / eps_n_curr) / factor
            else:
                average_f_n_ts = average_f_n_ts + f_n_ts * P_n_ts * ii
        area = scipy.integrate.simpson(average_f_n_ts, energy)
        return average_f_n_ts / area
//  [python]
def wv_mean(self):
        """
        First moment of the line, i.e., mean wavelength
        """
        moment = simps(self.wv*self.f,self.wv)
        norm = self.integrate_line()
        return moment/norm
//  [python]
def wv_mean(self):
        """
        First moment of the line, i.e., mean wavelength
        """
        moment = simpson(self.wv*self.f,self.wv)
        norm = self.integrate_line()
        return moment/norm
//  [python]
def equivalent_width(self):
        """
        Calculate the equivalent width, using the linear continuum fit
        under the line
        """
        ltot = simps(self.f,self.wv)
        cmean  = sp.sum(self.cf/self.ecf**2)/sp.sum(1./self.ecf**2)
        ecmean = sp.sqrt(1./sp.sum(1./self.ecf**2))
        return ltot/cmean
//  [python]
def equivalent_width(self):
        """
        Calculate the equivalent width, using the linear continuum fit
        under the line
        """
        ltot = sp.integrate.simpson(self.f,self.wv)
        cmean  = sp.sum(self.cf/self.ecf**2)/sp.sum(1./self.ecf**2)
        ecmean = sp.sqrt(1./sp.sum(1./self.ecf**2))
        return ltot/cmean
//  [python]
def dispersion(self):
        """
        Second moment of the line, i.e., dispersion
        """
        l0 = self.wv_mean()
        moment = simps(self.wv**2*self.f,self.wv)
        norm   = self.integrate_line()

        return sp.sqrt(moment/norm - l0**2)
//  [python]
def dispersion(self):
        """
        Second moment of the line, i.e., dispersion
        """
        l0 = self.wv_mean()
        moment = sp.integrate.simpson(self.wv**2*self.f,self.wv)
        norm   = self.integrate_line()

        return sp.sqrt(moment/norm - l0**2)
//  [python]
def mad(self):
        """
        MAD = mean absolute deviation.  Defined same as dispersion,
        but uses absolute value instead of square.
        """
        wv_abs = sp.absolute(self.wv - self.wv_median())
        moment = simps(wv_abs*self.f,self.wv)
        norm = self.integrate_line()
        return moment/ norm
//  [python]
def mad(self):
        """
        MAD = mean absolute deviation.  Defined same as dispersion,
        but uses absolute value instead of square.
        """
        wv_abs = sp.absolute(self.wv - self.wv_median())
        moment = sp.integrate.simpson(wv_abs*self.f,self.wv)
        norm = self.integrate_line()
        return moment/ norm
//  [python]
def make_depth_average(self, time_basis):
        """ Make depth averaged values from numpy array of outputs

            Parameters
            ----------
            time_basis: datetime.datetime
                time base of the outputs

            Returns
            -------
            lists of a set vtools.data.timeseries of depth and depth-averaged values
                For scalars, the list has only one set of time series.
                For vectors, the list has two sets of time series.
                Each time series has multiple columns of data, and each column
                is for stations.
        """
        nvrt = self._nvrt
        n_casts = self._n_casts
        # collect time stamp first
        times = list()
        output = self._outputs[0]
        for cast_i in range(n_casts):
            i_begin = cast_i * nvrt
            time = time_basis + time_interval(days=output[i_begin, 0])
            times.append(time)
        # collect data
        values = list()
        for output in self._outputs:
            values_at_point = list()
            depths_at_point = list()
            for xy_i in range(self._nxy):
                depths_at_cast = list()
                values_at_cast = list()
                for cast_i in range(n_casts):
                    i_begin = cast_i * nvrt + xy_i * (n_casts * nvrt)
                    depth = -output[i_begin + nvrt - 1, 2]
                    x = -output[i_begin:i_begin + nvrt, 2]
                    y = output[i_begin:i_begin + nvrt, 1]
                    avg = scipy.integrate.simps(y, x) / depth
                    depths_at_cast.append(depth)
                    values_at_cast.append(avg)
                depths_at_point.append(depths_at_cast)
                values_at_point.append(values_at_cast)
            ts_depths = its(times, numpy.array(depths_at_point).transpose())
            ts_values = its(times, numpy.array(values_at_point).transpose())
            values.append((ts_depths, ts_values))
        return values
//  [python]
def make_depth_average(self, time_basis):
        """ Make depth averaged values from numpy array of outputs

            Parameters
            ----------
            time_basis: datetime.datetime
                time base of the outputs

            Returns
            -------
            lists of a set vtools.data.timeseries of depth and depth-averaged values
                For scalars, the list has only one set of time series.
                For vectors, the list has two sets of time series.
                Each time series has multiple columns of data, and each column
                is for stations.
        """
        nvrt = self._nvrt
        n_casts = self._n_casts
        # collect time stamp first
        times = list()
        output = self._outputs[0]
        for cast_i in range(n_casts):
            i_begin = cast_i * nvrt
            time = time_basis + time_interval(days=output[i_begin, 0])
            times.append(time)
        # collect data
        values = list()
        for output in self._outputs:
            values_at_point = list()
            depths_at_point = list()
            for xy_i in range(self._nxy):
                depths_at_cast = list()
                values_at_cast = list()
                for cast_i in range(n_casts):
                    i_begin = cast_i * nvrt + xy_i * (n_casts * nvrt)
                    depth = -output[i_begin + nvrt - 1, 2]
                    x = -output[i_begin:i_begin + nvrt, 2]
                    y = output[i_begin:i_begin + nvrt, 1]
                    avg = scipy.integrate.simpson(y, x) / depth
                    depths_at_cast.append(depth)
                    values_at_cast.append(avg)
                depths_at_point.append(depths_at_cast)
                values_at_point.append(values_at_cast)
            ts_depths = its(times, numpy.array(depths_at_point).transpose())
            ts_values = its(times, numpy.array(values_at_point).transpose())
            values.append((ts_depths, ts_values))
        return values
//  [python]
def test_simps(odd):
    nx = 98 + odd
    x = np.linspace(-3, 3, nx)
    sigma = 0.5
    y = np.exp(-0.5*(x/sigma)**2) / np.sqrt(2*np.pi*sigma**2)

    h = np.ediff1d(x)
    hsum, hrat, hfac = s.geth(h)
    integ = s.simps(y, h, hsum, hrat, hfac)

    np_integ = si.simps(y, x, even='first')
    np.testing.assert_approx_equal(integ, np_integ)
//  [python]
def test_simps(odd):
    nx = 98 + odd
    x = np.linspace(-3, 3, nx)
    sigma = 0.5
    y = np.exp(-0.5*(x/sigma)**2) / np.sqrt(2*np.pi*sigma**2)

    h = np.ediff1d(x)
    hsum, hrat, hfac = s.geth(h)
    integ = s.simpson(y, h, hsum, hrat, hfac)

    np_integ = si.simpson(y, x, even='first')
    np.testing.assert_approx_equal(integ, np_integ)
//  [python]
def test_simps_float32(self):
        x = np.asarray(np.random.rand(10), np.float32)
        x_gpu = gpuarray.to_gpu(x)
        np.testing.assert_allclose(scipy.integrate.simps(x),
                        integrate.simps(x_gpu))
        np.testing.assert_allclose(scipy.integrate.simps(x, even='first'),
                        integrate.simps(x_gpu, even='first'))
        np.testing.assert_allclose(scipy.integrate.simps(x, even='last'),
                        integrate.simps(x_gpu, even='last'))
//  [python]
def test_simps_float32(self):
        x = np.asarray(np.random.rand(10), np.float32)
        x_gpu = gpuarray.to_gpu(x)
        np.testing.assert_allclose(scipy.integrate.simpson(x),
                        integrate.simps(x_gpu))
        np.testing.assert_allclose(scipy.integrate.simpson(x, even='first'),
                        integrate.simps(x_gpu, even='first'))
        np.testing.assert_allclose(scipy.integrate.simpson(x, even='last'),
                        integrate.simps(x_gpu, even='last'))
//  [python]
def run_beta_grid(self, plot=True):
		# If we set alpha=0, it is easiest to just grid beta instead of sampling it since it is just one parameter
		num = 400
		beta_x = np.linspace(0.0*pi/180, 0.6*pi/180, num)
		p = np.zeros(num)
		for x in tqdm.tqdm(range(num)):
			alpha = np.zeros(22)
			omega = np.concatenate(([beta_x[x]], alpha))
			
			prob = self.log_prob(omega)
			p[x] = prob

		p = np.exp(p-max(p))
		beta_x = beta_x*180/pi
		norm = scipy.integrate.simps(p, x=beta_x)
		mean = beta_x[np.argmax(p)]
		sigma = norm/(np.max(p)*sqrt(2*pi))

		print('Assume no miscalibration: Beta is mean:', mean, 'std:', sigma)

		if plot:
			plt.plot(beta_x, p, label='actual run')
			plt.legend()
			plt.savefig('tmp/__beta_grid.pdf')
	
		return mean, sigma
//  [python]
def run_beta_grid(self, plot=True):
		# If we set alpha=0, it is easiest to just grid beta instead of sampling it since it is just one parameter
		num = 400
		beta_x = np.linspace(0.0*pi/180, 0.6*pi/180, num)
		p = np.zeros(num)
		for x in tqdm.tqdm(range(num)):
			alpha = np.zeros(22)
			omega = np.concatenate(([beta_x[x]], alpha))
			
			prob = self.log_prob(omega)
			p[x] = prob

		p = np.exp(p-max(p))
		beta_x = beta_x*180/pi
		norm = scipy.integrate.simpson(p, x=beta_x)
		mean = beta_x[np.argmax(p)]
		sigma = norm/(np.max(p)*sqrt(2*pi))

		print('Assume no miscalibration: Beta is mean:', mean, 'std:', sigma)

		if plot:
			plt.plot(beta_x, p, label='actual run')
			plt.legend()
			plt.savefig('tmp/__beta_grid.pdf')
	
		return mean, sigma
//  [python]
def calc_lam0_cog( si, wave, lam0_nom ):
    #
    # Return an estimate of the central line-core wavelength of an input
    # Stokes I absorption line spectrum
    #
    #   @param   :  si    :  [float nparray(*)]  :  Observed Stokes I absorption spectrum
    #   @param   :  wave  :  [float nparray(*)]  :  Observed wavelengths array
    #
    #   @return  :  lam0  :  [float]             :  central line-core wavelength
    #

    wcore    = np.where( abs(wave - lam0_nom) <= 0.4 )
    si_resid = np.max( si ) - si
    numer    = scipy.integrate.simps( si_resid[wcore]*wave[wcore], wave[wcore] )
    denom    = scipy.integrate.simps( si_resid[wcore], wave[wcore] )
    if numer != 0.:
        try:
            lam0 = numer / denom
        except ZeroDivisionError:
            lam0 = 8542.0910    # default to lab wavelength
    else:
        lam0 = 8542.0910

    return lam0
//  [python]
def calc_lam0_cog( si, wave, lam0_nom ):
    #
    # Return an estimate of the central line-core wavelength of an input
    # Stokes I absorption line spectrum
    #
    #   @param   :  si    :  [float nparray(*)]  :  Observed Stokes I absorption spectrum
    #   @param   :  wave  :  [float nparray(*)]  :  Observed wavelengths array
    #
    #   @return  :  lam0  :  [float]             :  central line-core wavelength
    #

    wcore    = np.where( abs(wave - lam0_nom) <= 0.4 )
    si_resid = np.max( si ) - si
    numer    = scipy.integrate.simpson( si_resid[wcore]*wave[wcore], wave[wcore] )
    denom    = scipy.integrate.simpson( si_resid[wcore], wave[wcore] )
    if numer != 0.:
        try:
            lam0 = numer / denom
        except ZeroDivisionError:
            lam0 = 8542.0910    # default to lab wavelength
    else:
        lam0 = 8542.0910

    return lam0
//  [python]
def test_simps_float64(self):
        x = np.asarray(np.random.rand(10), np.float64)
        x_gpu = gpuarray.to_gpu(x)
        np.testing.assert_allclose(scipy.integrate.simps(x),
                        integrate.simps(x_gpu))
        np.testing.assert_allclose(scipy.integrate.simps(x, even='first'),
                        integrate.simps(x_gpu, even='first'))
        np.testing.assert_allclose(scipy.integrate.simps(x, even='last'),
                        integrate.simps(x_gpu, even='last'))
//  [python]
def test_simps_float64(self):
        x = np.asarray(np.random.rand(10), np.float64)
        x_gpu = gpuarray.to_gpu(x)
        np.testing.assert_allclose(scipy.integrate.simpson(x),
                        integrate.simps(x_gpu))
        np.testing.assert_allclose(scipy.integrate.simpson(x, even='first'),
                        integrate.simps(x_gpu, even='first'))
        np.testing.assert_allclose(scipy.integrate.simpson(x, even='last'),
                        integrate.simps(x_gpu, even='last'))
//  [python]
def test_simps_complex128(self):
        x = np.asarray(np.random.rand(10)+1j*np.random.rand(10), np.complex128)
        x_gpu = gpuarray.to_gpu(x)
        np.testing.assert_allclose(scipy.integrate.simps(x),
                        integrate.simps(x_gpu))
        np.testing.assert_allclose(scipy.integrate.simps(x, even='first'),
                        integrate.simps(x_gpu, even='first'))
        np.testing.assert_allclose(scipy.integrate.simps(x, even='last'),
                        integrate.simps(x_gpu, even='last'))
//  [python]
def test_simps_complex128(self):
        x = np.asarray(np.random.rand(10)+1j*np.random.rand(10), np.complex128)
        x_gpu = gpuarray.to_gpu(x)
        np.testing.assert_allclose(scipy.integrate.simpson(x),
                        integrate.simps(x_gpu))
        np.testing.assert_allclose(scipy.integrate.simpson(x, even='first'),
                        integrate.simps(x_gpu, even='first'))
        np.testing.assert_allclose(scipy.integrate.simpson(x, even='last'),
                        integrate.simps(x_gpu, even='last'))
//  [python]
def test_simps_complex64(self):
        x = np.asarray(np.random.rand(10)+1j*np.random.rand(10), np.complex64)
        x_gpu = gpuarray.to_gpu(x)
        np.testing.assert_allclose(scipy.integrate.simps(x),
                        integrate.simps(x_gpu))
        np.testing.assert_allclose(scipy.integrate.simps(x, even='first'),
                        integrate.simps(x_gpu, even='first'))
        np.testing.assert_allclose(scipy.integrate.simps(x, even='last'),
                        integrate.simps(x_gpu, even='last'))
//  [python]
def test_simps_complex64(self):
        x = np.asarray(np.random.rand(10)+1j*np.random.rand(10), np.complex64)
        x_gpu = gpuarray.to_gpu(x)
        np.testing.assert_allclose(scipy.integrate.simpson(x),
                        integrate.simps(x_gpu))
        np.testing.assert_allclose(scipy.integrate.simpson(x, even='first'),
                        integrate.simps(x_gpu, even='first'))
        np.testing.assert_allclose(scipy.integrate.simpson(x, even='last'),
                        integrate.simps(x_gpu, even='last'))
//  [python]
def price(self, strike, spot, texp, cp=1):
        # implement the formula (14) and (15)
        fwd, df, _ = self._fwd_factor(spot, texp)

        kk = strike / fwd
        log_k = np.log(kk)
        J, h = 100001, 0.001   # need to take these as parameters
        phi = (np.arange(J)[:, None] + 1) * h  # shape=(J,1)

        ff = self.f_1(phi, texp) - kk * self.f_2(phi, texp)

        ## Need to convert using iFFT later
        price = scint.simps(
            (ff * np.exp(-1j * phi * log_k) / (1j * phi)).real,
            dx=h, axis=0,
        ) / np.pi

        price += (1 - kk) / 2 * np.where(cp > 0, 1, -1)

        if len(price) == 1:
            price = price[0]

        return df * fwd * price
//  [python]
def price(self, strike, spot, texp, cp=1):
        # implement the formula (14) and (15)
        fwd, df, _ = self._fwd_factor(spot, texp)

        kk = strike / fwd
        log_k = np.log(kk)
        J, h = 100001, 0.001   # need to take these as parameters
        phi = (np.arange(J)[:, None] + 1) * h  # shape=(J,1)

        ff = self.f_1(phi, texp) - kk * self.f_2(phi, texp)

        ## Need to convert using iFFT later
        price = scint.simpson(
            (ff * np.exp(-1j * phi * log_k) / (1j * phi)).real,
            dx=h, axis=0,
        ) / np.pi

        price += (1 - kk) / 2 * np.where(cp > 0, 1, -1)

        if len(price) == 1:
            price = price[0]

        return df * fwd * price
//  [python]
def cond_states_full(self, texp, sig_0):
        tobs = self.tobs(texp)
        n_dt = len(tobs)
        sigma_paths = self.vol_paths(tobs)
        s_t = sigma_paths[-1, :]
        u_t_std = scint.simps(sigma_paths, dx=1, axis=0) / n_dt
        v_t_std = scint.simps(sigma_paths**2, dx=1, axis=0) / n_dt

        return s_t, v_t_std, u_t_std
//  [python]
def cond_states_full(self, texp, sig_0):
        tobs = self.tobs(texp)
        n_dt = len(tobs)
        sigma_paths = self.vol_paths(tobs)
        s_t = sigma_paths[-1, :]
        u_t_std = scint.simpson(sigma_paths, dx=1, axis=0) / n_dt
        v_t_std = scint.simpson(sigma_paths**2, dx=1, axis=0) / n_dt

        return s_t, v_t_std, u_t_std
//  [python]
def compute_normalization(self):
        zs = np.arange(0, self.population_parameter_dict["redshift_max"], step=1e-3)
        out = scipy.integrate.simps(self._prob({'redshift': zs}), zs)
        return out
//  [python]
def compute_normalization(self):
        zs = np.arange(0, self.population_parameter_dict["redshift_max"], step=1e-3)
        out = scipy.integrate.simpson(self._prob({'redshift': zs}), zs)
        return out
//  [python]
def make_sn(ii, jj, m, C_DFFT, PSI_DFFT, PHI_DFFT, SWO):
   
   sn                = {}
   
   erg_psi           = abs(DFT.appInvCFWithDFT_2D(C_DFFT*PSI_DFFT, SWO))
   sn['erg_psi']     = erg_psi
   
   sn['m']           = m
   sn['log2']        = ii
   sn['alpha']       = jj
   sn['J']           = SWO.J
   
   erg_phi           = DFT.appInvCFWithDFT_2D(DFT.appCFWithDFT_2D(erg_psi, SWO)*PHI_DFFT, SWO)
   
   sn['I(erg_phi)']  = round(simps(simps(real(abs(erg_phi)), SWO.X), SWO.Y),2)
   
   if not(SWO.onlyCoef):   
      sn['Y_DFFT_psi']  = PSI_DFFT
      sn['erg_phi']     = erg_phi
   
   return(sn)
//  [python]
def make_sn(ii, jj, m, C_DFFT, PSI_DFFT, PHI_DFFT, SWO):
   
   sn                = {}
   
   erg_psi           = abs(DFT.appInvCFWithDFT_2D(C_DFFT*PSI_DFFT, SWO))
   sn['erg_psi']     = erg_psi
   
   sn['m']           = m
   sn['log2']        = ii
   sn['alpha']       = jj
   sn['J']           = SWO.J
   
   erg_phi           = DFT.appInvCFWithDFT_2D(DFT.appCFWithDFT_2D(erg_psi, SWO)*PHI_DFFT, SWO)
   
   sn['I(erg_phi)']  = round(simpson(simpson(real(abs(erg_phi)), SWO.X), SWO.Y),2)
   
   if not(SWO.onlyCoef):   
      sn['Y_DFFT_psi']  = PSI_DFFT
      sn['erg_phi']     = erg_phi
   
   return(sn)
//  [python]
def scatteringAroundCenter(C, SWO, m, FB):
 
   C_DFFT                 = DFT.appCFWithDFT_2D(C, SWO)
   S                      = {}
   
   for ii in range(1, SWO.ll+1):
      for jj in range(round(SWO.nang/2)):
         sn     = make_sn(SWO.jmax -ii, jj, m, C_DFFT, FB[str(SWO.jmax-ii)][str(jj)], FB['inf'], SWO)  
         ss     = str(SWO.jmax-ii) + ':' + str(jj) + '*2pi/' + str(SWO.nang) + ':' + str(SWO.J)
         S[ss]  = sn
          
   sn                = {} 
   sn['m']           = m   
   sn['log2']        = SWO.J   
   erg_phi           = DFT.appInvCFWithDFT_2D( C_DFFT*FB['inf'], SWO)
   sn['erg_psi']     = erg_phi # hier wird das Zentrum zerlegt, daher erg_psi=erg_phi
            
   if not(SWO.onlyCoef):   
      sn['Y_DFFT_phi']  = FB['inf']
      sn['erg_phi']     = erg_phi
   ss                = 'INF' + ':' + '0' + ':' + str(SWO.J)
   sn['I(erg_phi)']  = round(simps(simps(real(erg_phi), SWO.X), SWO.Y),2)
   S[ss]             = sn
                  
   return(S)
//  [python]
def scatteringAroundCenter(C, SWO, m, FB):
 
   C_DFFT                 = DFT.appCFWithDFT_2D(C, SWO)
   S                      = {}
   
   for ii in range(1, SWO.ll+1):
      for jj in range(round(SWO.nang/2)):
         sn     = make_sn(SWO.jmax -ii, jj, m, C_DFFT, FB[str(SWO.jmax-ii)][str(jj)], FB['inf'], SWO)  
         ss     = str(SWO.jmax-ii) + ':' + str(jj) + '*2pi/' + str(SWO.nang) + ':' + str(SWO.J)
         S[ss]  = sn
          
   sn                = {} 
   sn['m']           = m   
   sn['log2']        = SWO.J   
   erg_phi           = DFT.appInvCFWithDFT_2D( C_DFFT*FB['inf'], SWO)
   sn['erg_psi']     = erg_phi # hier wird das Zentrum zerlegt, daher erg_psi=erg_phi
            
   if not(SWO.onlyCoef):   
      sn['Y_DFFT_phi']  = FB['inf']
      sn['erg_phi']     = erg_phi
   ss                = 'INF' + ':' + '0' + ':' + str(SWO.J)
   sn['I(erg_phi)']  = round(simpson(simpson(real(erg_phi), SWO.X), SWO.Y),2)
   S[ss]             = sn
                  
   return(S)
//  [python]
def cond_spot_sigma_volpath(self, texp, sigma_0, mu=0):
        """
        Kept for backward compatibility and rn_deriv

        Args:
            texp:
            sigma_0:
            mu:

        Returns:

        """
        rhoc = np.sqrt(1.0 - self.rho**2)
        rho_sigma = self.rho * sigma_0

        tobs = self.tobs(texp)
        n_dt = len(tobs)
        sigma_paths, log_rn_deriv = self.vol_paths(tobs, mu=mu)
        sigma_final = sigma_paths[-1, :]
        int_var = scint.simps(sigma_paths**2, dx=1, axis=0) / n_dt
        vol_cond = rhoc * np.sqrt(int_var)

        if np.isclose(self.beta, 0):
            spot_cond = rho_sigma / self.vov * (sigma_final - 1)
        else:
            spot_cond = 1.0 / self.vov * (sigma_final - 1) - 0.5 * rho_sigma * int_var * texp
            np.exp(rho_sigma * spot_cond, out=spot_cond)

        return spot_cond, vol_cond, log_rn_deriv
//  [python]
def cond_spot_sigma_volpath(self, texp, sigma_0, mu=0):
        """
        Kept for backward compatibility and rn_deriv

        Args:
            texp:
            sigma_0:
            mu:

        Returns:

        """
        rhoc = np.sqrt(1.0 - self.rho**2)
        rho_sigma = self.rho * sigma_0

        tobs = self.tobs(texp)
        n_dt = len(tobs)
        sigma_paths, log_rn_deriv = self.vol_paths(tobs, mu=mu)
        sigma_final = sigma_paths[-1, :]
        int_var = scint.simpson(sigma_paths**2, dx=1, axis=0) / n_dt
        vol_cond = rhoc * np.sqrt(int_var)

        if np.isclose(self.beta, 0):
            spot_cond = rho_sigma / self.vov * (sigma_final - 1)
        else:
            spot_cond = 1.0 / self.vov * (sigma_final - 1) - 0.5 * rho_sigma * int_var * texp
            np.exp(rho_sigma * spot_cond, out=spot_cond)

        return spot_cond, vol_cond, log_rn_deriv
//  [python]
def _kernel(self, iteration=None, trace=True):
        self.initialise_recurrence()

        if iteration is None:
            iteration = self.max_cycle

        filter_type = lambda arr: arr.imag if not self.include_real else arr

        # Get the moments - allow input to already be traced
        if self.trace:
            moments = as_trace(self.moments[: iteration + 1]).astype(complex)
        else:
            moments = self.moments[: iteration + 1].astype(complex)

        # Initialise scaled grids
        a, b = self.scale
        scaled_grid = (self.grid - b) / a
        scaled_eta = self.eta / a
        z = scaled_grid + 1.0j * scaled_eta

        # Initialise the Green's function
        fac = lambda n: -1.0j * (2.0 - int(n == 0))
        num = z - 1.0j * np.sqrt(1.0 - z**2)
        den = np.sqrt(1.0 - z**2)
        gn = lambda n: fac(n) * num**n / den
        gf = np.zeros((len(z), *moments[0].shape), dtype=complex)

        integral = scipy.integrate.simps(as_trace(gf.imag), self.grid)

        for niter in range(iteration + 1):
            part = np.einsum("z,...->z...", gn(niter), moments[niter])
            part /= a * np.pi
            gf -= part

            if niter in (0, 1, 2, 3, 4, 5, 10, iteration) or niter % 100 == 0:
                integral = scipy.integrate.simps(as_trace(gf.imag), self.grid)
                self.log.info("%4d %16.8g", niter, integral)

        # Not sure why we need to do this...
        gf = -gf.conj()

        self.log.info("-" * 21)

        return filter_type(gf)
//  [python]
def _kernel(self, iteration=None, trace=True):
        self.initialise_recurrence()

        if iteration is None:
            iteration = self.max_cycle

        filter_type = lambda arr: arr.imag if not self.include_real else arr

        # Get the moments - allow input to already be traced
        if self.trace:
            moments = as_trace(self.moments[: iteration + 1]).astype(complex)
        else:
            moments = self.moments[: iteration + 1].astype(complex)

        # Initialise scaled grids
        a, b = self.scale
        scaled_grid = (self.grid - b) / a
        scaled_eta = self.eta / a
        z = scaled_grid + 1.0j * scaled_eta

        # Initialise the Green's function
        fac = lambda n: -1.0j * (2.0 - int(n == 0))
        num = z - 1.0j * np.sqrt(1.0 - z**2)
        den = np.sqrt(1.0 - z**2)
        gn = lambda n: fac(n) * num**n / den
        gf = np.zeros((len(z), *moments[0].shape), dtype=complex)

        integral = scipy.integrate.simpson(as_trace(gf.imag), self.grid)

        for niter in range(iteration + 1):
            part = np.einsum("z,...->z...", gn(niter), moments[niter])
            part /= a * np.pi
            gf -= part

            if niter in (0, 1, 2, 3, 4, 5, 10, iteration) or niter % 100 == 0:
                integral = scipy.integrate.simpson(as_trace(gf.imag), self.grid)
                self.log.info("%4d %16.8g", niter, integral)

        # Not sure why we need to do this...
        gf = -gf.conj()

        self.log.info("-" * 21)

        return filter_type(gf)
//  [python]
def find_width(self):
        """
        Using peak information, finds FWHM.

        """
        screened_peaks = Peaks()
        for p in self.peaks:
            d = np.sign(p.height / 2. - (self.u[0:-1] - self.baseline)) - np.sign(p.height / 2. - (self.u[1:] - self.baseline))
            rightIdx = np.where(d < 0)[0]  # right
            leftIdx = np.where(d > 0)[0]  # left

            x_right = self.w[rightIdx[np.argmin(np.abs(self.w[rightIdx] - p.loc))]]
            x_left = self.w[leftIdx[np.argmin(np.abs(self.w[leftIdx] - p.loc))]]

            if x_left < x_right:
                # width equals FWHM
                p.width = x_right - x_left

                # bounds are +/- 2 widths
                p.bounds = [p.loc - 2 * p.width, p.loc + 2 * p.width]

                # peak indices
                p.idx = np.where((self.w >= p.bounds[0]) & (self.w <= p.bounds[1]))

                # local baseline
                p.baseline = peakutils.baseline(self.u[p.idx], 0)[0]
                p.height = self.u[p.i] - p.baseline

                # area over peak indices
                p.area = sp.integrate.simps(self.u[p.idx] - p.baseline, self.w[p.idx])

                screened_peaks.append(p)

        self.peaks = screened_peaks
//  [python]
def find_width(self):
        """
        Using peak information, finds FWHM.

        """
        screened_peaks = Peaks()
        for p in self.peaks:
            d = np.sign(p.height / 2. - (self.u[0:-1] - self.baseline)) - np.sign(p.height / 2. - (self.u[1:] - self.baseline))
            rightIdx = np.where(d < 0)[0]  # right
            leftIdx = np.where(d > 0)[0]  # left

            x_right = self.w[rightIdx[np.argmin(np.abs(self.w[rightIdx] - p.loc))]]
            x_left = self.w[leftIdx[np.argmin(np.abs(self.w[leftIdx] - p.loc))]]

            if x_left < x_right:
                # width equals FWHM
                p.width = x_right - x_left

                # bounds are +/- 2 widths
                p.bounds = [p.loc - 2 * p.width, p.loc + 2 * p.width]

                # peak indices
                p.idx = np.where((self.w >= p.bounds[0]) & (self.w <= p.bounds[1]))

                # local baseline
                p.baseline = peakutils.baseline(self.u[p.idx], 0)[0]
                p.height = self.u[p.i] - p.baseline

                # area over peak indices
                p.area = sp.integrate.simpson(self.u[p.idx] - p.baseline, self.w[p.idx])

                screened_peaks.append(p)

        self.peaks = screened_peaks
//  [python]
def parse_points(self):
        """
        Called after 2 clicks on the plot.  Sorts the stored points in terms of frequency (w) to define
        low, middle, and high.  Subsequently determines approximate peak height, width, and area.

        """
        p = Peak()

        # sort points in frequency
        self.points.sort()

        # determine minimum and maximum
        wMin = self.points[0][0]
        wMax = self.points[1][0]

        # determine width from min and max
        # user captures +/- 3 FWHMs with clicks
        p.width = (wMax - wMin) / 4

        # determine peak height and location of peak by searching over an interval
        p.height, p.loc, p.i = find_peak(self.w, self.u, wMin, wMax)

        # bounds are +/- 3 widths
        p.bounds = [p.loc - 2 * p.width, p.loc + 2 * p.width]

        p.height = p.height - self.baseline

        # determine indices within the peak width
        p.idx = np.where((self.w > p.bounds[0]) & (self.w < p.bounds[1]))

        # local baseline
        p.baseline = peakutils.baseline(self.u[p.idx], 0)[0]
        p.height = self.u[p.i] - p.baseline

        # area over peak indices
        p.area = sp.integrate.simps(self.u[p.idx] - p.baseline, self.w[p.idx])

        self.peaks.append(p)
//  [python]
def parse_points(self):
        """
        Called after 2 clicks on the plot.  Sorts the stored points in terms of frequency (w) to define
        low, middle, and high.  Subsequently determines approximate peak height, width, and area.

        """
        p = Peak()

        # sort points in frequency
        self.points.sort()

        # determine minimum and maximum
        wMin = self.points[0][0]
        wMax = self.points[1][0]

        # determine width from min and max
        # user captures +/- 3 FWHMs with clicks
        p.width = (wMax - wMin) / 4

        # determine peak height and location of peak by searching over an interval
        p.height, p.loc, p.i = find_peak(self.w, self.u, wMin, wMax)

        # bounds are +/- 3 widths
        p.bounds = [p.loc - 2 * p.width, p.loc + 2 * p.width]

        p.height = p.height - self.baseline

        # determine indices within the peak width
        p.idx = np.where((self.w > p.bounds[0]) & (self.w < p.bounds[1]))

        # local baseline
        p.baseline = peakutils.baseline(self.u[p.idx], 0)[0]
        p.height = self.u[p.i] - p.baseline

        # area over peak indices
        p.area = sp.integrate.simpson(self.u[p.idx] - p.baseline, self.w[p.idx])

        self.peaks.append(p)
//  [python]
def _integrate_pointbased(tr, ):
    import scipy.integrate
    return scipy.integrate.simps(y=tr.data_pts_np, x=tr.time_pts_np) * tr.data_unit * tr.time_unit
//  [python]
def _integrate_pointbased(tr, ):
    import scipy.integrate
    return scipy.integrate.simpson(y=tr.data_pts_np, x=tr.time_pts_np) * tr.data_unit * tr.time_unit
//  [python]
def Nbargal(self,lnms,z,nfn,Ngal):
        nbargal=np.zeros([z.shape[0]])
        for j in range(0,z.shape[0]):
            nbargal[j]=integrate.simps(np.exp(lnms)*nfn[:,j]*Ngal[:,j],lnms)
        return nbargal
//  [python]
def Nbargal(self,lnms,z,nfn,Ngal):
        nbargal=np.zeros([z.shape[0]])
        for j in range(0,z.shape[0]):
            nbargal[j]=integrate.simpson(np.exp(lnms)*nfn[:,j]*Ngal[:,j],lnms)
        return nbargal
//  [python]
def dlnss_dlnr(self, r):
        r"""
        The derivative of the mass variance with radius.

        Parameters
        ----------
        r : array_like
            Radii

        Returns
        -------
        dlnss_dlnr : array_like
            The derivative of the the mass variance with radius.

        Notes
        -----
        Given a prescription for how radius grows with mass (typically with
        a log-slope of 1/3, and set in :meth:`dlnr_dlnm`), this specifies
        the quantity :math:`\frac{d \ln \sigma^2}{d\ln m}`.

        The general formula is

        .. math:: \frac{d\ln \sigma^2}{d\ln R} = \frac{1}{\pi^2\sigma^2} \int_0^\infty
                  W(kR) \frac{dW(kR)}{d\ln(kR)} P(k)k^2 dk
        """
        dlnk = np.log(self.k[1] / self.k[0])
        s = self.sigma(r)
        rk = np.outer(r, self.k)

        rest = self.power * self.k**3
        w = self.k_space(rk)
        dw = self.dw_dlnkr(rk)
        integ = w * dw * rest
        return intg.simps(integ, dx=dlnk, axis=-1) / (np.pi**2 * s**2)
//  [python]
def dlnss_dlnr(self, r):
        r"""
        The derivative of the mass variance with radius.

        Parameters
        ----------
        r : array_like
            Radii

        Returns
        -------
        dlnss_dlnr : array_like
            The derivative of the the mass variance with radius.

        Notes
        -----
        Given a prescription for how radius grows with mass (typically with
        a log-slope of 1/3, and set in :meth:`dlnr_dlnm`), this specifies
        the quantity :math:`\frac{d \ln \sigma^2}{d\ln m}`.

        The general formula is

        .. math:: \frac{d\ln \sigma^2}{d\ln R} = \frac{1}{\pi^2\sigma^2} \int_0^\infty
                  W(kR) \frac{dW(kR)}{d\ln(kR)} P(k)k^2 dk
        """
        dlnk = np.log(self.k[1] / self.k[0])
        s = self.sigma(r)
        rk = np.outer(r, self.k)

        rest = self.power * self.k**3
        w = self.k_space(rk)
        dw = self.dw_dlnkr(rk)
        integ = w * dw * rest
        return scipy.integrate.simpson(integ, dx=dlnk, axis=-1) / (np.pi**2 * s**2)
//  [python]
def sigma(self, r, order=0):
        if not isinstance(r, collections.abc.Iterable):
            r = np.atleast_1d(r)

        if self.k.max() < 1 / r.min():
            warnings.warn("Warning: Maximum r*k less than 1!")

        # # Need to re-define this because the integral needs to go exactly kr=1
        # # or else the function 'jitters'
        sigma = np.zeros(len(r))
        power = _spline(self.k, self.power)
        for i, rr in enumerate(r):
            k = np.logspace(
                np.log10(self.k[0]),
                min(np.log10(self.k.max()), np.log10(1.0 / rr)),
                max(100, len(self.k) - i),
            )

            p = power(k)
            dlnk = np.log(k[1] / k[0])
            integ = p * k ** (3 + 2 * order)
            sigma[i] = (0.5 / (np.pi**2)) * intg.simps(integ, dx=dlnk)

        return np.sqrt(sigma)
//  [python]
def sigma(self, r, order=0):
        if not isinstance(r, collections.abc.Iterable):
            r = np.atleast_1d(r)

        if self.k.max() < 1 / r.min():
            warnings.warn("Warning: Maximum r*k less than 1!")

        # # Need to re-define this because the integral needs to go exactly kr=1
        # # or else the function 'jitters'
        sigma = np.zeros(len(r))
        power = _spline(self.k, self.power)
        for i, rr in enumerate(r):
            k = np.logspace(
                np.log10(self.k[0]),
                min(np.log10(self.k.max()), np.log10(1.0 / rr)),
                max(100, len(self.k) - i),
            )

            p = power(k)
            dlnk = np.log(k[1] / k[0])
            integ = p * k ** (3 + 2 * order)
            sigma[i] = (0.5 / (np.pi**2)) * integrate.simpson(integ, dx=dlnk)

        return np.sqrt(sigma)
//  [python]
def sigma(self, r, order=0, rk=None):
        r"""
        Calculate the nth-moment of the smoothed density field, :math:`\sigma_n(r)`.

        .. note :: This is not :math:`\sigma_n^2(r)`!

        Parameters
        ----------
        r : float or array_like
            The radii of the spheres at which to calculate the nth moment.

        order : int, optional
            The order of the moment. Default 0 corresponds to common
            mass variance.

        Returns
        -------
        sigma : array_like
            The square root of the moment at `r`.

        Notes
        -----
        The general definition for the nth-moment of the smoothed density field is (see
        Bardeen et al. 1986, Eq 4.6c)

        .. math:: \sigma^2_n(R) = \frac{1}{2\pi^2} \int_0^\infty dk\ k^{2(1+n)}
                  P(k) W^2(kR)
        """
        if rk is None:
            rk = np.outer(r, self.k)

        dlnk = np.log(self.k[1] / self.k[0])

        # we multiply by k because our steps are in logk.
        rest = self.power * self.k ** (3 + order * 2)
        integ = rest * self.k_space(rk) ** 2
        sigma = (0.5 / np.pi**2) * intg.simps(integ, dx=dlnk, axis=-1)
        return np.sqrt(sigma)
//  [python]
def sigma(self, r, order=0, rk=None):
        r"""
        Calculate the nth-moment of the smoothed density field, :math:`\sigma_n(r)`.

        .. note :: This is not :math:`\sigma_n^2(r)`!

        Parameters
        ----------
        r : float or array_like
            The radii of the spheres at which to calculate the nth moment.

        order : int, optional
            The order of the moment. Default 0 corresponds to common
            mass variance.

        Returns
        -------
        sigma : array_like
            The square root of the moment at `r`.

        Notes
        -----
        The general definition for the nth-moment of the smoothed density field is (see
        Bardeen et al. 1986, Eq 4.6c)

        .. math:: \sigma^2_n(R) = \frac{1}{2\pi^2} \int_0^\infty dk\ k^{2(1+n)}
                  P(k) W^2(kR)
        """
        if rk is None:
            rk = np.outer(r, self.k)

        dlnk = np.log(self.k[1] / self.k[0])

        # we multiply by k because our steps are in logk.
        rest = self.power * self.k ** (3 + order * 2)
        integ = rest * self.k_space(rk) ** 2
        sigma = (0.5 / np.pi**2) * integrate.simpson(integ, dx=dlnk, axis=-1)
        return np.sqrt(sigma)
//  [python]
def Nbargal_binned(self,lnms,z,nfn,Ngal,log10mlow,log10mhigh):
        lnmlow=np.log(10.**log10mlow)
        lnmhigh=np.log(10.**log10mhigh)
        lnmsin=lnms[(lnms>=lnmlow)&(lnms<=lnmhigh)]
        nfnin=nfn[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        Ngalin=Ngal[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        #print (lnmsin.shape[0])
        nbargalbinned=np.zeros(z.shape[0])
        for j in range(0,z.shape[0]):
            nbargalbinned[j]=integrate.simps(np.exp(lnmsin)*nfnin[:,j]*Ngalin[:,j],lnmsin)
        return nbargalbinned
//  [python]
def Nbargal_binned(self,lnms,z,nfn,Ngal,log10mlow,log10mhigh):
        lnmlow=np.log(10.**log10mlow)
        lnmhigh=np.log(10.**log10mhigh)
        lnmsin=lnms[(lnms>=lnmlow)&(lnms<=lnmhigh)]
        nfnin=nfn[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        Ngalin=Ngal[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        #print (lnmsin.shape[0])
        nbargalbinned=np.zeros(z.shape[0])
        for j in range(0,z.shape[0]):
            nbargalbinned[j]=integrate.simpson(np.exp(lnmsin)*nfnin[:,j]*Ngalin[:,j],lnmsin)
        return nbargalbinned
//  [python]
def _galaxybias(self,lnms,z,nfn,Ngalc,Ngals,halobias,log10mlow,log10mhigh):
        lnmlow=np.log(10.**log10mlow)
        lnmhigh=np.log(10.**log10mhigh)
        lnmsin=lnms[(lnms>=lnmlow)&(lnms<=lnmhigh)]
        nfnin=nfn[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        Ngalcin=Ngalc[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        Ngalsin=Ngals[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        halobiasin=halobias[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        nbargaltot=self.Nbargal(lnmsin,z,nfnin,Ngalcin+Ngalsin)
        bgal = np.zeros([z.shape[0]])
        for j in range(0,z.shape[0]):
            bgal[j]=integrate.simps((np.exp(lnmsin))*nfnin[:,j]*(Ngalcin[:,j]+Ngalsin[:,j])*halobiasin[:,j]/nbargaltot[j],lnmsin)
        return bgal
//  [python]
def _galaxybias(self,lnms,z,nfn,Ngalc,Ngals,halobias,log10mlow,log10mhigh):
        lnmlow=np.log(10.**log10mlow)
        lnmhigh=np.log(10.**log10mhigh)
        lnmsin=lnms[(lnms>=lnmlow)&(lnms<=lnmhigh)]
        nfnin=nfn[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        Ngalcin=Ngalc[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        Ngalsin=Ngals[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        halobiasin=halobias[(lnms>=lnmlow)&(lnms<=lnmhigh),:]
        nbargaltot=self.Nbargal(lnmsin,z,nfnin,Ngalcin+Ngalsin)
        bgal = np.zeros([z.shape[0]])
        for j in range(0,z.shape[0]):
            bgal[j]=integrate.simpson((np.exp(lnmsin))*nfnin[:,j]*(Ngalcin[:,j]+Ngalsin[:,j])*halobiasin[:,j]/nbargaltot[j],lnmsin)
        return bgal
//  [python]
def integrate_u(u):
    """This function integrates over some input squared to calculate energy using Simpson's integration.

    If your control set (B) is the identity this will likely give energies that are nearly identical to those calculated
    using a Reimann sum. However, when control sets are sparse inputs can be super curvy, so this method will be a bit
    more accurate.

    Args:
        u (txN, numpy array): Control signals input to the system.
            These can be obtained using get_control_inputs.
      
    Returns:
        energy ((N,) numpy array): Energy input into each node.

    """

    if sp.__version__ < '1.6.0':
        energy = sp.integrate.simps(u.T**2)
    else:
        energy = sp.integrate.simpson(u.T**2)
    return energy
//  [python]
def integrate_u(u):
    """This function integrates over some input squared to calculate energy using Simpson's integration.

    If your control set (B) is the identity this will likely give energies that are nearly identical to those calculated
    using a Reimann sum. However, when control sets are sparse inputs can be super curvy, so this method will be a bit
    more accurate.

    Args:
        u (txN, numpy array): Control signals input to the system.
            These can be obtained using get_control_inputs.
      
    Returns:
        energy ((N,) numpy array): Energy input into each node.

    """

    energy = sp.integrate.simpson(u.T**2)
    return energy
//  [python]
def nbar_halo(self,zs,logmlow,logmhigh):
        zs = np.atleast_1d(zs)
        zs[zs<0.001] = 0.001
        self._setup_k_z_m_grid_functions(zs)        
        lnmlow=np.log(10.**logmlow)
        lnmhigh=np.log(10.**logmhigh)
        lnmsin=self.lnms[(self.lnms>=lnmlow)&(self.lnms<=lnmhigh)]
        nfnin=self.nfn[(self.lnms>=lnmlow)&(self.lnms<=lnmhigh),:]
        nhalobinned=np.zeros(self.z.shape[0])
        for j in range(0,self.z.shape[0]):
            nhalobinned[j]=integrate.simps(np.exp(lnmsin)*nfnin[:,j],lnmsin)
        return nhalobinned