numpy.trapz

Here are the examples of the python api numpy.trapz taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

86 Examples 7

3 Source : ECD_pulse_construction.py
with MIT License
from alec-eickbusch

def rotate(theta, phi=0, sigma=8, chop=6, dt=1):
    wave = gaussian_wave(sigma=sigma, chop=chop)
    energy = np.trapz(wave, dx=dt)
    amp = 1 / energy
    wave = (1 + 0j) * wave
    return (theta / (2.0)) * amp * np.exp(1j * phi) * wave


def rotate_echoed(theta, phi=0, sigma=8, chop=6, dt=1):

3 Source : ECD_pulse_construction.py
with MIT License
from alec-eickbusch

def disp_gaussian(alpha, sigma=8, chop=6, dt=1):
    wave = gaussian_wave(sigma=sigma, chop=chop)
    energy = np.trapz(wave, dx=dt)
    wave = (1 + 0j) * wave
    return (
        (np.abs(alpha) / energy) * np.exp(1j * (np.pi / 2.0 + np.angle(alpha))) * wave
    )


class FakePulse:

3 Source : jet_emitters.py
with BSD 3-Clause "New" or "Revised" License
from andreatramacere

    def eval_N(self):
        self.update()
        if self.emitters_type=='electrons':
            return np.trapz(self.n_gamma_e,self.gamma_e)
        elif self.emitters_type=='protons':
            return np.trapz(self.n_gamma_p, self.gamma_p)
        else:
            raise  RuntimeError('emitters type',self.emitters_type, 'not valid')

    def eval_U(self, gmin=None, gmax=None):

3 Source : arts.py
with MIT License
from atmtools

    def calc_optical_thickness(self, atmosphere, t_surface):
        """Calculate the spectral irradiance field."""
        self.set_atmospheric_state(atmosphere, t_surface)

        self.ws.propmat_clearsky_fieldCalc()

        tau = np.trapz(
            y=self.ws.propmat_clearsky_field.value[:, :, 0, 0, :, 0, 0],
            x=self.ws.z_field.value[:, 0, 0],
            axis=-1,
        )

        return self.ws.f_grid.value.copy(), tau

    @staticmethod

3 Source : arts.py
with MIT License
from atmtools

    def integrate_spectral_irradiance(frequency, irradiance):
        """Integrate the spectral irradiance field over the frequency.

        Parameters:
            frequency (ndarray): Frequency [Hz].
            irradiance (ndarray): Spectral irradiance [W m^-2 / Hz].

        Returns:
            ndarray, ndarray: Downward flux, upward, flux [W m^-2]
        """
        F = np.trapz(irradiance, frequency, axis=0)[:, 0, 0, :]

        # Fluxes
        lw_down = -F[:, 0]
        lw_up = F[:, 1]

        return lw_down, lw_up

    def calc_spectral_olr(self, atmosphere, surface):

3 Source : calculate.py
with GNU General Public License v3.0
from bch0w

def vrl(d, s1, s2):
    """
    Logarithmic variance reduction. Approximately Gaussian distributed
    reduction in variance based on full waveform difference. Based on
    Equation 8 in Tape et al. 2010.

    :type d: np.array
    :param d: data array to compare against synthetic arrays
    :type s1: np.array
    :param s1: synthetic array for model 1
    :type s2: np.array
    :param s2: synthetic array for model 2
    :rtype: float
    :return: logarithmic variance reduction
    """
    return np.log(np.trapz((d - s1) ** 2) / (np.trapz(d - s2) ** 2))


def time_offset(st, origintime):

3 Source : evaluation.py
with GNU General Public License v3.0
from bio-ontology-research-group

def compute_rank_roc(ranks, n_var):
    auc_x = list(ranks.keys())
    auc_x.sort()
    auc_y = []
    tpr = 0
    sum_rank = sum(ranks.values()) 
    for x in auc_x:
        tpr += ranks[x]
        auc_y.append(tpr / sum_rank)
    
    auc_x.append(n_var)
    auc_y.append(1)
    aucs = np.trapz(auc_y, auc_x) / n_var
    return aucs
        
def top_k(evaluation,k,total): 

3 Source : evaluate_interactions.py
with BSD 2-Clause "Simplified" License
from bio-ontology-research-group

def compute_rank_roc(ranks, n_prots):
    auc_x = list(ranks.keys())
    auc_x.sort()
    auc_y = []
    tpr = 0
    sum_rank = sum(ranks.values())
    for x in auc_x:
        tpr += ranks[x]
        auc_y.append(tpr / sum_rank)
    auc_x.append(n_prots)
    auc_y.append(1)
    auc = np.trapz(auc_y, auc_x) / n_prots
    return auc

def compute_fmax(labels, preds):

3 Source : save_registered_images.py
with MIT License
from cleary-lab

def get_kernel(sigma):
	x = np.linspace(-sigma*3,sigma*3,sigma*6+1)
	x = np.exp(-x**2/sigma**2)
	x /= np.trapz(x)
	return x[:,np.newaxis]*x[np.newaxis,:]

def normalize_dapi_intensity(Images,dapi_index,sigma1=600,sigma2=100):

3 Source : temporal.py
with GNU General Public License v2.0
from cydal

def area_under_curve(data):
    """Calculates AUC

    Parameters
    ----------

    data : Matrix or DataFrame
        Data to perform operation on

    Returns
    -------
    Array
        1-dim array
    """
    return np.trapz(data, axis=axis)

def mean_abs_diff(data):

3 Source : test_gradients.py
with MIT License
from DTUWindEnergy

def test_trapz(y, x, axis):
    if callable(y):
        y = y(x)

    npt.assert_array_equal(np.trapz(y, x, axis), gradients.trapz(y, x, axis))
    dtrapz_dy_lst = [method(gradients.trapz, True)(y, x, axis) for method in [fd, cs, autograd]]
    npt.assert_array_almost_equal(dtrapz_dy_lst[0], dtrapz_dy_lst[1])
    npt.assert_array_equal(dtrapz_dy_lst[1], dtrapz_dy_lst[2])

    if x is not None:
        dtrapz_dx_lst = [method(gradients.trapz, True, argnum=1)(y, x, axis) for method in [fd, cs, autograd]]
        npt.assert_array_almost_equal(dtrapz_dx_lst[0], dtrapz_dx_lst[1])
        npt.assert_array_almost_equal(dtrapz_dx_lst[1], dtrapz_dx_lst[2], 14)


@pytest.mark.parametrize('test', [

3 Source : plotdata.py
with MIT License
from ebranlard

    def inty(PD):
        if PD.yIsString or PD.yIsDate or PD.xIsString or PD.xIsDate:
            return None,'NA'
        else:
            v=np.trapz(y=PD.y,x=PD.x)
            s=pretty_num(v)
        return v,s

    def intyintdx(PD):

3 Source : plotdata.py
with MIT License
from ebranlard

    def intyintdx(PD):
        if PD.yIsString or PD.yIsDate or PD.xIsString or PD.xIsDate:
            return None,'NA'
        else:
            v=np.trapz(y=PD.y,x=PD.x)/np.trapz(y=PD.x*0+1,x=PD.x)
            s=pretty_num(v)
        return v,s

    def intyx1(PD):

3 Source : plotdata.py
with MIT License
from ebranlard

    def intyx1_scaled(PD):
        if PD.yIsString or PD.yIsDate or PD.xIsString or PD.xIsDate:
            return None,'NA'
        else:
            v=np.trapz(y=PD.y*PD.x,x=PD.x)
            v=v/np.trapz(y=PD.y,x=PD.x)
            s=pretty_num(v)
        return v,s

    def intyx2(PD):

3 Source : _air_scattering_coefficient.py
with GNU Lesser General Public License v3.0
from eradiate

def _eval_impl_ckd(w: pint.Quantity) -> pint.Quantity:
    values = _eval_impl(w)
    return np.trapz(values, w) / (w.max() - w.min())


@spectrum_factory.register(type_id="air_scattering_coefficient")

3 Source : functional.py
with Apache License 2.0
from Erotemic

def _average_precision(tpr, ppv):
    """
    Compute average precision of a binary PR curve. This is simply the area
    under the curve.

    Args:
        tpr (ndarray): true positive rate - aka recall
        ppv (ndarray): positive predictive value - aka precision
    """
    # The average precision is simply the area under the PR curve.
    xdata = tpr
    ydata = ppv
    if xdata[0] > xdata[-1]:
        xdata = xdata[::-1]
        ydata = ydata[::-1]
    # Note: we could simply use sklearn.metrics.auc, which has more robust
    # checks.
    ap = np.trapz(y=ydata, x=xdata)
    return ap

3 Source : animate_wave_function copie.py
with MIT License
from FelixDesrochers

def compute_err(z1,z2,x,y):
    return np.trapz(np.trapz(abs(z1-z2), x).real, y).real

#####################################
#       2) Create the system        #
#####################################
# specify time steps and duration
dt = 0.005

3 Source : metrics.py
with MIT License
from fpthink

    def average(self):
        if len(self.overlaps) == 0:
            return 0
        return np.trapz(self.value, x=self.Xaxis) * 100 / self.max_overlap


class Precision(object):

3 Source : metrics.py
with MIT License
from Ghostish

    def compute(self):
        overlaps = torchmetrics.utilities.data.dim_zero_cat(self.overlaps)

        if overlaps.numel() == 0:
            return 0
        return torch.tensor(np.trapz(self.value(overlaps), x=self.Xaxis) * 100 / self.max_overlap)

    def update(self, val):

3 Source : contactloss.py
with GNU General Public License v3.0
from hassony2

def meshiou(gt_dists, pred_dists, threshs=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]):
    """
    For each thresholds, computes thresh_ious and averages accross batch dim
    """
    all_ious = []
    for thresh in threshs:
        ious = thresh_ious(gt_dists, pred_dists, thresh)
        all_ious.append(ious)
    iou_auc = np.mean(
        np.trapz(torch.stack(all_ious).cpu().numpy(), axis=0, x=threshs)
    )
    batch_ious = torch.stack(all_ious).mean(1)
    return batch_ious, iou_auc


def masked_mean_loss(dists, mask):

3 Source : sensitivity.py
with MIT License
from Hazboun6

    def SNR(self, Sh):
        """
        Calculate the signal-to-noise ratio of a given signal strain power
        spectral density, `Sh`. Must match frequency range and `df` of
        `self`.
        """
        integrand = Sh**2 / self.S_eff**2
        return np.sqrt(2.0 * self.Tspan * np.trapz(y=integrand,
                                                   x=self.freqs,
                                                   axis=0))

    @property

3 Source : metrics.py
with MIT License
from hydrogo

def AUC(x, y):
    '''
    AUC - area under curve

    Note: area under curve wich had been computed by standard trapezial
          method (np.trapz)

    Args:

        x (numpy.ndarray): array of one metric rate (1D)
        y (numpy.ndarray): array of another metric rate (1D)

    Returns:

        float - area under curve

    '''

    return np.trapz(y, x)

3 Source : performance.py
with MIT License
from iN1k1

def nAUC(curve):
    """
    Computes the normalized Area Under Curve
    :param curve: list of curve values
    :return: area under curve in [0,1]
    """
    return np.trapz(curve) / np.prod(curve.shape)


def precision_recall(actual, ranked_predictions, k=None, average=False):

3 Source : deconvolution.py
with MIT License
from ixdat

    def sig_area(self):
        """Integrates a measured impulse response and returns the area."""
        delta_sig = self.MS_data[1] - self.MS_data[1][-1]
        sig_area = np.trapz(delta_sig, self.MS_data[0])

        return sig_area

    @property

3 Source : dd_models.py
with MIT License
from JeschkeLab

def _normalize(r,P):
    if not all(P==0):
        P = P/np.trapz(P,r)
    return P
# =================================================================

# =================================================================
def _multigaussfun(r,r0,sig):

3 Source : ex_global_twostates_parametric.py
with MIT License
from JeschkeLab

def Ptwostates(meanA,meanB,stdA,stdB,fracA):
    PA = fracA*dl.dd_gauss(r,meanA,stdA)
    PB = (1-fracA)*dl.dd_gauss(r,meanB,stdB)
    P = PA + PB
    P /= np.trapz(P)
    return P
# Construct the model object
Pmodel = dl.Model(Ptwostates)

3 Source : test_model_penalty.py
with MIT License
from JeschkeLab

def penalty_fcn(mean,std): 
    P = dd_gauss(x,mean,std)
    P = P/np.trapz(P,x)
    return np.sqrt(P*(x - np.trapz(P*x,x))**2*np.mean(np.diff(x)))

# ======================================================================
def test_type(): 

3 Source : sampler.py
with MIT License
from lscsoft

    def _compute_evidence_from_mean_lnlikes(betas, mean_lnlikes):
        lnZ = np.trapz(mean_lnlikes, betas)
        z2 = np.trapz(mean_lnlikes[::-1][::2][::-1], betas[::-1][::2][::-1])
        lnZerr = np.abs(lnZ - z2)
        return lnZ, lnZerr

    def _create_lnZ_plots(self, betas, mean_lnlikes, outdir, label, sem_lnlikes=None):

3 Source : interpolated.py
with MIT License
from lscsoft

    def _initialize_attributes(self):
        from scipy.integrate import cumtrapz
        if np.trapz(self._yy, self.xx) != 1:
            logger.debug('Supplied PDF for {} is not normalised, normalising.'.format(self.name))
        self._yy /= np.trapz(self._yy, self.xx)
        self.YY = cumtrapz(self._yy, self.xx, initial=0)
        # Need last element of cumulative distribution to be exactly one.
        self.YY[-1] = 1
        self.probability_density = interp1d(x=self.xx, y=self._yy, bounds_error=False, fill_value=0)
        self.cumulative_distribution = interp1d(x=self.xx, y=self.YY, bounds_error=False, fill_value=(0, 1))
        self.inverse_cumulative_distribution = interp1d(x=self.YY, y=self.xx, bounds_error=True)


class FromFile(Interped):

3 Source : prior.py
with MIT License
from lscsoft

    def _build_attributes(self):
        """
        Method that builds the inverse cdf of the P(pixel) distribution for rescaling
        """
        from scipy.integrate import cumtrapz
        yy = self._all_interped(self.pix_xx)
        yy /= np.trapz(yy, self.pix_xx)
        YY = cumtrapz(yy, self.pix_xx, initial=0)
        YY[-1] = 1
        self.inverse_cdf = interp1d(x=YY, y=self.pix_xx, bounds_error=True)

    @staticmethod

3 Source : statistics.py
with BSD 3-Clause "New" or "Revised" License
from LSSTDESC

    def getTotal(self):
        if len(self.axes[-1].axis) > 1:
            self.total = np.trapz(y=self.grid, x=self.axes[-1].axis, axis=self.rangedim[-1])
        else:
            self.total = np.sum(self.grid)
        if self.dim > 1:
            for i in reversed(self.rangedim[:-1]):
                if len(self.axes[i].axis) > 1:
                    self.total = np.trapz(y=self.total, x=self.axes[i].axis, axis=i)
                else:
                    self.total = np.sum(self.total, axis=i)
        return self.total

    def normalize(self):

3 Source : statistics.py
with BSD 3-Clause "New" or "Revised" License
from LSSTDESC

    def marginalizeAlongAxis(self, axis_index):
        # return(np.sum(self.grid,axis=axis_index))
        return np.trapz(self.grid, self.axes[axis_index].axis, axis=axis_index)


class PDF(Grid):

3 Source : evaluate.py
with MIT License
from mateuszbuda

def froc_auc(fps, tpr, high=4.0):
    x = [0.0]
    y = [0.0]
    for i in range(len(fps)):
        if fps[i]   <   high:
            x.append(fps[i])
            y.append(tpr[i])
    x.append(high)
    y.append(y[-1])
    return np.trapz(y, x)


def sensitivity(fps, tpr, at=2.0):

3 Source : utils.py
with GNU General Public License v2.0
from mikecokina

def calculate_volume_ellipse_approx(equator_points=None, meridian_points=None):
    """
    Function calculates volume of the object where only equator and meridian points where provided usin elipsoidal
    approximation for the points with the same x-cordinates.

    :param equator_points: numpy array; (yzx) column-wise
    :param meridian_points: numpy array; (yzx) column-wise
    :return: float;
    """
    areas = up.abs(const.PI * equator_points[:, 1] * meridian_points[:, 0])
    return up.abs(np.trapz(areas, equator_points[:, 2]))


def plane_projection(points, plane, keep_3d=False):

3 Source : _quadrature.py
with BSD 3-Clause "New" or "Revised" License
from mspass-team

def trapz(y, x=None, dx=1.0, axis=-1):
    """`An alias of `trapezoid`.

    `trapz` is kept for backwards compatibility. For new code, prefer
    `trapezoid` instead.
    """
    return trapezoid(y, x=x, dx=dx, axis=axis)


class AccuracyWarning(Warning):

3 Source : princeton_WINSPEC.py
with GNU General Public License v3.0
from qcha41

    def get_integrated_power(self):
        if self.data['spectrum'] is None :
            self.acquire_spectrum()
        return np.trapz(self.data['spectrum']['power'],self.data['spectrum']['wavelength'])
    
    
    
    
    def get_main_peak_fwhm(self):

3 Source : test_util.py
with GNU General Public License v3.0
from qutech

    def test_integrate(self):
        f = rng.standard_normal(32)
        x = rng.random(32)
        self.assertEqual(util.integrate(f, x), np.trapz(f, x))

        f = rng.standard_normal((2, 32)).astype(complex)
        x = rng.random(32)
        self.assertArrayEqual(util.integrate(f, x), np.trapz(f, x))

        f = rng.standard_normal(32)
        x = np.linspace(0, 1, 32)
        dx = 1/31
        self.assertAlmostEqual(util.integrate(f, x), util.integrate(f, dx=dx))

    def test_remove_float_errors(self):

3 Source : metrics.py
with MIT License
from Sacry

def roc_auc_score(y_true, y_score):
    fpr, tpr, _ = roc_curve(y_true, y_score)
    return np.trapz(tpr, x=fpr)

# ------------------------------ Regression metrics ------------------------------

def mean_absolute_error(y_true, y_pred):

3 Source : general.py
with GNU General Public License v3.0
from spurra

def calc_auc(x, y):
    """ Given x and y values it calculates the approx. integral and normalizes it: area under curve"""
    integral = np.trapz(y, x)
    norm = np.trapz(np.ones_like(y), x)

    return integral / norm


def get_stb_ref_curves():

3 Source : kl.py
with Apache License 2.0
from sungsulim

def approx_kl(gmm_1, gmm_2, xs):
    ys = gmm_1.pdf(xs) * (gmm_1.logpdf(xs) - gmm_2.logpdf(xs))
    return np.trapz(ys, xs)


def minimize_pq(p, xs, q_means, q_stds):

3 Source : read_filter.py
with MIT License
from tomasstolker

    def mean_wavelength(self) -> Union[np.float32, np.float64]:
        """
        Calculate the weighted mean wavelength of the filter profile.

        Returns
        -------
        float
            Mean wavelength (um).
        """

        data = self.get_filter()

        return np.trapz(data[:, 0] * data[:, 1], data[:, 0]) / np.trapz(
            data[:, 1], data[:, 0]
        )

    @typechecked

3 Source : read_filter.py
with MIT License
from tomasstolker

    def effective_width(self) -> np.float32:
        """
        Calculate the effective width of the filter profile. The
        effective width is equivalent to the horizontal size of a
        rectangle with height equal to the maximum transmission and
        with the same area as the one covered by the filter profile.

        Returns
        -------
        float
            Effective width (um).
        """

        data = self.get_filter()

        return np.trapz(data[:, 1], data[:, 0]) / np.amax(data[:, 1])

    @typechecked

3 Source : test_construct.py
with MIT License
from wavespectra

def integrate_2d_hs(freqs, dirs, S):
    """Numerical integration of 2D spectrum."""
    sum1 = np.trapz(S, freqs, axis=0)
    sum2 = np.trapz(sum1, dirs)
    return 4 * sum2 ** 0.5


class TestJonswap(object):

3 Source : probabilistic.py
with Apache License 2.0
from xarray-contrib

def _auc(fpr, tpr, dim="probability_bin"):
    """Get area under the curve with trapez method."""
    # reverse tpr, fpr to fpr, tpr, see numpy.trapz(y, x=None)
    with suppress_warnings("The `numpy.trapz` function is not implemented"):
        with suppress_warnings("invalid value encountered in long_scalars"):
            with suppress_warnings("invalid value encountered in true_divide"):
                area = xr.apply_ufunc(
                    np.trapz, tpr, fpr, input_core_dims=[[dim], [dim]], dask="allowed"
                )
    area = abs(area)
    if ((area > 1)).any():
        area = area.clip(0, 1)  # allow only values between 0 and 1
    return area


def roc(

0 Source : jet_emitters.py
with BSD 3-Clause "New" or "Revised" License
from andreatramacere

    def _fill(self,):
        self.set_grid()

        self.f=self._eval_func(gamma=self._gamma_grid)
        self._Norm=1.0

        if self.normalize is True:
            self._Norm=1.0/np.trapz(self.f,self._gamma_grid)

        self.f = self.f*self._Norm*self.parameters.get_par_by_name('N').val

        if self.emitters_type == 'electrons':
            self.gamma_e = np.zeros(self._gamma_grid_size)
            self.n_gamma_e = np.zeros(self._gamma_grid_size)
            self.gamma_e = self._gamma_grid
            self.n_gamma_e = self.f

            self.n_gamma_e[np.isnan(self.n_gamma_e)] = 0
            self.n_gamma_e[np.isinf(self.n_gamma_e)] = 0

        if self.emitters_type == 'protons':
            self.gamma_p = np.zeros(self._gamma_grid_size)
            self.n_gamma_p = np.zeros(self._gamma_grid_size)
            if self._secondaries_done is False:
                self.gamma_e_second_inj = np.zeros(self._gamma_grid_size)
                self.n_gamma_e_second_inj = np.zeros(self._gamma_grid_size)

            self.gamma_p = self._gamma_grid
            self.n_gamma_p = self.f

            self.n_gamma_p[np.isnan(self.n_gamma_p)] = 0
            self.n_gamma_p[np.isinf(self.n_gamma_p)] = 0

            self.n_gamma_e_second_inj[np.isnan(self.n_gamma_e_second_inj)] = 0
            self.n_gamma_e_second_inj[np.isinf(self.n_gamma_e_second_inj)] = 0


    def _plot(self,m, p, y_min=None, y_max=None, x_min=None, x_max=None, energy_unit='gamma',label=None):

0 Source : jet_emitters.py
with BSD 3-Clause "New" or "Revised" License
from andreatramacere

    def _fill(self,):
        self.set_grid()

        self.f=self._eval_func(gamma=self._gamma_grid)
        self._Norm=1.0

        if self.normalize is True:
            self._Norm=1.0/np.trapz(self.f,self._gamma_grid)

        self.f = self.f*self._Norm*self.parameters.get_par_by_name('Q').val

        if self.emitters_type == 'electrons':
            self.gamma_e = np.zeros(self._gamma_grid_size)
            self.n_gamma_e = np.zeros(self._gamma_grid_size)
            self.gamma_e = self._gamma_grid
            self.n_gamma_e = self.f

            self.n_gamma_e[np.isnan(self.n_gamma_e)] = 0
            self.n_gamma_e[np.isinf(self.n_gamma_e)] = 0

    def eval_U_q(self):

0 Source : filters.py
with MIT License
from ArtificialStellarPopulations

    def dlam(self, bandpass):
        """
        Calculate the bandpass width.

        Parameters
        ----------
        bandpass : str
            The name of the filter.

        Returns
        -------
            width : float
                The bandpass width.
        """
        lam, trans = self._get_trans(bandpass)
        norm = np.trapz(trans, lam)
        width = (norm / trans.max()) * u.angstrom
        return width


class ZeroPointConverter(object):

0 Source : HaloFeedback.py
with MIT License
from bradkav

    def TotalMass(self):
        return np.trapz(-self.P_eps(), self.eps_grid)

    def TotalEnergy(self):

0 Source : integration.py
with GNU General Public License v3.0
from dgbowl

def _integrate_peaks(
    xs: list[np.ndarray],
    ys: list[np.ndarray],
    peakdata: dict,
    specdata: dict,
) -> dict:
    """
    A function which, given a trace in [`xs`, `ys`], `peakdata` containing the boundaries
    `"llim"` and `"rlim"` for each `peak`, and `specdata` containing the peak-maximum
    matching limits `"l"` and `"r"`, first assigns peaks into `truepeaks`, then
    baseline-corrects [`xs`, `ys`], and finally integrates the peaks using numpy.trapz().
    """
    xsn = xs[0]
    truepeaks = {}
    for name, species in specdata.items():
        for p in peakdata:
            if xsn[p["max"]] > species["l"] and xsn[p["max"]]   <   species["r"]:
                truepeaks[name] = p
                break
    bln = _get_baseline(ys, peakdata)
    for k, v in truepeaks.items():
        s = v["llim"]
        e = v["rlim"] + 1
        py = unp.uarray(ys[0][s:e] - bln[0][s:e], ys[1][s:e] - bln[1][s:e])
        px = unp.uarray(xs[0][s:e], xs[1][s:e])
        A = np.trapz(py, px)
        truepeaks[k]["A"] = A
        truepeaks[k]["h"] = py[v["max"] - s]
    return truepeaks


def integrate_trace(traces: dict, chromspec: dict) -> tuple[dict, dict]:

0 Source : source_creation.py
with BSD 3-Clause "New" or "Revised" License
from dnarayanan

def direct_add_stars(df_nu, stars_list, diskstars_list, bulgestars_list, cosmoflag, m, sp):

    print("--------------------------------\n")
    print("Adding unbinned stars to the grid\n")
    print("--------------------------------\n")

    totallum_newstars = 0.
    unbinned_stars_list = []

    for star in stars_list:
        if star.age   <  = cfg.par.max_age_direct:
            unbinned_stars_list.append(star)


    nstars = len(unbinned_stars_list)
    if (nstars == 0):
        print ("No unbinned stars to add")
        return m

    else:
        print ("Number of unbinned stars to added: ", nstars)
    
    stellar_nu, stellar_fnu, disk_fnu, bulge_fnu, mfrac = sg.allstars_sed_gen(unbinned_stars_list, cosmoflag, sp)
    #SED_gen now returns an additional parameter, mfrac, to properly scale the FSPS SSP spectra, which are in units of formed mass, not current stellar mass
    for i in range(nstars):
        nu = stellar_nu[:]
        fnu = stellar_fnu[i, :]

        nu, fnu = wavelength_compress(nu, fnu, df_nu)
        # reverse the arrays for hyperion
        nu = nu[::-1]
        fnu = fnu[::-1]
        
        lum = np.absolute(np.trapz(fnu, x=nu))*unbinned_stars_list[i].mass/constants.M_sun.cgs.value/mfrac[i]
        lum *= constants.L_sun.cgs.value

        pos = unbinned_stars_list[i].positions

        # add new stars
        totallum_newstars += lum
        #m.add_spherical_source(luminosity = lum,radius = 10.*const.rsun,spectrum = (nu,fnu),

        m.add_point_source(luminosity = lum,spectrum=(nu,fnu), position = pos)

    print('[source_creation/add_unbinned_newstars:] totallum_newstars = ', totallum_newstars)

    if cosmoflag == False: add_bulge_disk_stars(df_nu,stellar_nu,stellar_fnu,disk_fnu,bulge_fnu,unbinned_stars_list,diskstars_list,bulgestars_list,m)
   
    m.set_sample_sources_evenly(True)
    
    return m


def add_bulge_disk_stars(df_nu,stellar_nu,stellar_fnu,disk_fnu,bulge_fnu,stars_list,diskstars_list,bulgestars_list,m):

See More Examples