jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_pdf_against_cdf(self):
        k, v = 3, 10

        # Test whether the integrated PDF matches the CDF using cumulative
        # integration. Use a small step size to reduce error due to the
        # summation. This is slow, but tests the results well.
        x = np.arange(0, 10, step=0.01)

        y_cdf = stats.studentized_range.cdf(x, k, v)[1:]
        y_pdf_raw = stats.studentized_range.pdf(x, k, v)
        y_pdf_cumulative = np.cumsum(y_pdf_raw) * (x[1]-x[0])

        # Because of error caused by the summation, use a relatively large rtol
        assert_allclose(y_pdf_cumulative, y_cdf, rtol=1e-4)
//  [python]
def test_pdf_against_cdf(self):
        k, v = 3, 10

        # Test whether the integrated PDF matches the CDF using cumulative
        # integration. Use a small step size to reduce error due to the
        # summation. This is slow, but tests the results well.
        x = np.arange(0, 10, step=0.01)

        y_cdf = stats.studentized_range.cdf(x, k, v)[1:]
        y_pdf_raw = stats.studentized_range.pdf(x, k, v)
        y_pdf_cumulative = cumulative_trapezoid(y_pdf_raw, x)

        # Because of error caused by the summation, use a relatively large rtol
        assert_allclose(y_pdf_cumulative, y_cdf, rtol=1e-4)
//  [python]
def compute(self, dataset: xr.Dataset) -> xr.DataArray:
    u = dataset[self.u_name]
    v = dataset[self.v_name]
    divergence = _divergence(u, v)
    pascals_per_hpa = 100
    pressure = pascals_per_hpa * dataset.coords['level']
    axis = divergence.dims.index('level')
    # TODO(shoyer): consider masking out vertical wind in locations below the
    # surface of the Earth (geopotential < geopotential_at_surface).
    vertical_wind = scipy.integrate.cumtrapz(
        -divergence.values, x=pressure, axis=axis, initial=0
    )
    return divergence.copy(data=vertical_wind)
//  [python]
def compute(self, dataset: xr.Dataset) -> xr.DataArray:
    u = dataset[self.u_name]
    v = dataset[self.v_name]
    divergence = _divergence(u, v)
    pascals_per_hpa = 100
    pressure = pascals_per_hpa * dataset.coords['level']
    axis = divergence.dims.index('level')
    # TODO(shoyer): consider masking out vertical wind in locations below the
    # surface of the Earth (geopotential < geopotential_at_surface).
    vertical_wind = scipy.integrate.cumulative_trapezoid(
        -divergence.values, x=pressure, axis=axis, initial=0
    )
    return divergence.copy(data=vertical_wind)
//  [python]
def get_ia(self):
        """return Arias intensity Ia.
        """
        # time history of Arias Intensity
        acc = self.acc * self.unit_factors[f'{self.acc_unit}-m']
        series = np.pi / 2 / 9.81 * integrate.cumtrapz(
            acc ** 2, self.time, initial=0)
        # Total Arias Intensity at the end of the ground motion
        arias = series[-1]
        # time history of the normalized Arias Intensity
        arias_percent = series / arias
        # ----------------------------------------------------
        self.Arias = arias
        self.AriasSeries = series
        self.AriasPercent = arias_percent
        return arias
//  [python]
def get_ia(self):
        """return Arias intensity Ia.
        """
        # time history of Arias Intensity
        acc = self.acc * self.unit_factors[f'{self.acc_unit}-m']
        series = np.pi / 2 / 9.81 * cumulative_trapezoid(
            acc ** 2, self.time, initial=0)
        # Total Arias Intensity at the end of the ground motion
        arias = series[-1]
        # time history of the normalized Arias Intensity
        arias_percent = series / arias
        # ----------------------------------------------------
        self.Arias = arias
        self.AriasSeries = series
        self.AriasPercent = arias_percent
        return arias
//  [python]
def dalpha_dr(self):
        r"""
        Equation 39
        inherits correct :math:`\sigma_\alpha` from `d2alpha_drdtheta`
        integrate over theta

        Returns
        -------
        dalpha_dr : Array
            Derivative of alpha w.r.t :math:`r`
        """
        initial_units = self.d2alpha_drdtheta.units

        # cumulative_trapezoid strips units, integration adds no unit
        dalpha_dr = integrate.cumtrapz(
            self.d2alpha_drdtheta.m, self.regulartheta, initial=0.0
        )

        f = interp1d(self.regulartheta, dalpha_dr)

        # set dalpha/dr(r,theta=0.0)=0.0, assumed by codes, add unit back
        return (dalpha_dr - f(0.0)) * initial_units
//  [python]
def dalpha_dr(self):
        r"""
        Equation 39
        inherits correct :math:`\sigma_\alpha` from `d2alpha_drdtheta`
        integrate over theta

        Returns
        -------
        dalpha_dr : Array
            Derivative of alpha w.r.t :math:`r`
        """
        initial_units = self.d2alpha_drdtheta.units

        # cumulative_trapezoid strips units, integration adds no unit
        dalpha_dr = integrate.cumulative_trapezoid(
            self.d2alpha_drdtheta.m, self.regulartheta, initial=0.0
        )

        f = interp1d(self.regulartheta, dalpha_dr)

        # set dalpha/dr(r,theta=0.0)=0.0, assumed by codes, add unit back
        return (dalpha_dr - f(0.0)) * initial_units
//  [python]
def alpha(self):
        r"""
        Equation 37
        inherits correct :math:`\sigma_\alpha` from `dalpha_dtheta`
        integrate over theta

        Returns
        -------
        dalpha_dr : Array
            Derivative of alpha w.r.t :math:`r`
        """
        initial_units = self.dalpha_dtheta.units

        # cumulative_trapezoid strips units, integration adds no unit
        dalpha_dtheta = integrate.cumtrapz(
            self.dalpha_dtheta, self.regulartheta, initial=0.0
        )
        f = interp1d(self.regulartheta, dalpha_dtheta)

        # set dalpha/dr(r,theta=0.0)=0.0, assumed by codes, add unit back
        return (dalpha_dtheta - f(0.0)) * initial_units
//  [python]
def alpha(self):
        r"""
        Equation 37
        inherits correct :math:`\sigma_\alpha` from `dalpha_dtheta`
        integrate over theta

        Returns
        -------
        dalpha_dr : Array
            Derivative of alpha w.r.t :math:`r`
        """
        initial_units = self.dalpha_dtheta.units

        # cumulative_trapezoid strips units, integration adds no unit
        dalpha_dtheta = integrate.cumulative_trapezoid(
            self.dalpha_dtheta, self.regulartheta, initial=0.0
        )
        f = interp1d(self.regulartheta, dalpha_dtheta)

        # set dalpha/dr(r,theta=0.0)=0.0, assumed by codes, add unit back
        return (dalpha_dtheta - f(0.0)) * initial_units
//  [python]
def integrate_cumtrapz(data, dx, **kwargs):
    """
    Performs first order integration of data using the trapezoidal rule.

    :param data: Data array to integrate.
    :param dx: Sample spacing usually in seconds.
    """
    # Integrate. Set first value to zero to avoid changing the total
    # length of the array.
    return scipy.integrate.cumtrapz(data, dx=dx, initial=0)
//  [python]
def integrate_cumtrapz(data, dx, **kwargs):
    """
    Performs first order integration of data using the trapezoidal rule.

    :param data: Data array to integrate.
    :param dx: Sample spacing usually in seconds.
    """
    # Integrate. Set first value to zero to avoid changing the total
    # length of the array.
    return scipy.integrate.cumulative_trapezoid(data, dx=dx, initial=0)
//  [python]
def dynamic_pressure(T, S):
    for i in range(10):
        S[i] -= 0.1*(10-i)*2e-4
#    S[:10] -= 0.00016  # try making the top of the domain a bit fresher as a hack to get faster flow at the rhs...
    for i in range(10, len(T)):
        S[i] = 34
        T[i] = -0.5
   
    density_rhs =  -g.values()[0] *(-beta_temp.values()[0] * (T-T_ref.values()[0]) +  beta_sal.values()[0] * (S - S_ref.values()[0]))
  #  print(density_rhs)



#    print("len z", len(z_rhs))
#    print("len density", len(density_rhs))
    pcumulative = scipy.integrate.cumtrapz(density_rhs, z_rhs, initial=0)
 #   print("pcumulative", pcumulative)
 #   print("len pcumulative", len(pcumulative))

    return pcumulative
//  [python]
def dynamic_pressure(T, S):
    for i in range(10):
        S[i] -= 0.1*(10-i)*2e-4
#    S[:10] -= 0.00016  # try making the top of the domain a bit fresher as a hack to get faster flow at the rhs...
    for i in range(10, len(T)):
        S[i] = 34
        T[i] = -0.5
   
    density_rhs =  -g.values()[0] *(-beta_temp.values()[0] * (T-T_ref.values()[0]) +  beta_sal.values()[0] * (S - S_ref.values()[0]))
  #  print(density_rhs)



#    print("len z", len(z_rhs))
#    print("len density", len(density_rhs))
    pcumulative = scipy.integrate.cumulative_trapezoid(density_rhs, z_rhs, initial=0)
 #   print("pcumulative", pcumulative)
 #   print("len pcumulative", len(pcumulative))

    return pcumulative
//  [python]
def set_units(self,
                  acc: str = "g",
                  vel: str = "cm",
                  disp: str = "cm"):
        """Specify the unit of input acceleration time-history and the units of output velocity and displacement.

        Parameters
        ----------
        acc : str, optional, one of ('g', 'm', 'cm', 'mm', 'in', 'ft')
            Unit of input acceleration time-history, by default "g",  ignoring time unit /s2.
        vel : str, optional, one of ('m', 'cm', 'mm', 'in', 'ft')
            Unit of output velocity, by default "cm",  ignoring time unit /s.
        disp : str, optional, one of ('m', 'cm', 'mm', 'in', 'ft')
            Unit of output displacement, by default "cm".
        """
        self.acc_factor = self.unit_factors[f"{self.acc_unit}-{acc}"]
        self.acc_unit = acc
        self.acc *= self.acc_factor
        self.vel = self.cumulative_trapezoid(self.acc, self.time, initial=0)
        self.disp = self.cumulative_trapezoid(self.vel, self.time, initial=0)
        self.vel_factor = self.unit_factors[f"{acc}-{vel}"]
        self.disp_factor = self.unit_factors[f"{acc}-{disp}"]
        self.vel_unit = vel
        self.disp_unit = disp
        self.vel *= self.vel_factor
        self.disp *= self.disp_factor
        acc_end = '' if self.acc_unit == 'g' else "/s2"
        print(f"[#0099e5]acc-unit: {self.acc_unit}{acc_end};[/]\n"
              f"[#ff4c4c]vel-unit；{self.vel_unit}/s;[/]\n"
              f"[#34bf49]disp-unit: {self.disp_unit}[/]")
//  [python]
def set_units(self,
                  acc: str = "g",
                  vel: str = "cm",
                  disp: str = "cm"):
        """Specify the unit of input acceleration time-history and the units of output velocity and displacement.

        Parameters
        ----------
        acc : str, optional, one of ('g', 'm', 'cm', 'mm', 'in', 'ft')
            Unit of input acceleration time-history, by default "g",  ignoring time unit /s2.
        vel : str, optional, one of ('m', 'cm', 'mm', 'in', 'ft')
            Unit of output velocity, by default "cm",  ignoring time unit /s.
        disp : str, optional, one of ('m', 'cm', 'mm', 'in', 'ft')
            Unit of output displacement, by default "cm".
        """
        self.acc_factor = self.unit_factors[f"{self.acc_unit}-{acc}"]
        self.acc_unit = acc
        self.acc *= self.acc_factor
        self.vel = cumulative_trapezoid(self.acc, self.time, initial=0)
        self.disp = cumulative_trapezoid(self.vel, self.time, initial=0)
        self.vel_factor = self.unit_factors[f"{acc}-{vel}"]
        self.disp_factor = self.unit_factors[f"{acc}-{disp}"]
        self.vel_unit = vel
        self.disp_unit = disp
        self.vel *= self.vel_factor
        self.disp *= self.disp_factor
        acc_end = '' if self.acc_unit == 'g' else "/s2"
        print(f"[#0099e5]acc-unit: {self.acc_unit}{acc_end};[/]\n"
              f"[#ff4c4c]vel-unit；{self.vel_unit}/s;[/]\n"
              f"[#34bf49]disp-unit: {self.disp_unit}[/]")
//  [python]
def interpolate(spd, wavelengths):
    if type(wavelengths) == SpectralPowerDistribution:
        wavelengths = wavelengths.wavelengths

    def diff(arr):  # Derivative
        return np.diff(arr, prepend=2 * arr[0] - arr[1])

    # Interpolate the integral, then derivate

    integral = scipy.integrate.cumtrapz(
        y=spd.data,
        x=spd.wavelengths,
        initial=0,
    )
    interpolator = scipy.interpolate.CubicHermiteSpline(
        x=spd.wavelengths,
        y=integral,
        dydx=spd.data,  # The data is the derivative of its own integral
        extrapolate=False,
    )
    # Evaluate in the middle of the bin (logic unclear, but better results)
    interpolated_integral = interpolator(wavelengths + diff(wavelengths / 2))
    valid = np.where(~np.isnan(interpolated_integral))[0]
    interpolated_integral[: valid[0]] = interpolated_integral[valid[0]]
    interpolated_integral[valid[-1] :] = interpolated_integral[valid[-1]]

    interpolated_data = diff(interpolated_integral) / diff(wavelengths)  # Derivate

    return SpectralPowerDistribution(
        wavelengths=wavelengths,
        data=interpolated_data,
        description=spd.description,
        quantity=spd.quantity,
    )
//  [python]
def interpolate(spd, wavelengths):
    if type(wavelengths) == SpectralPowerDistribution:
        wavelengths = wavelengths.wavelengths

    def diff(arr):  # Derivative
        return np.diff(arr, prepend=2 * arr[0] - arr[1])

    # Interpolate the integral, then derivate

    integral = scipy.integrate.cumulative_trapezoid(
        y=spd.data,
        x=spd.wavelengths,
        initial=0,
    )
    interpolator = scipy.interpolate.CubicHermiteSpline(
        x=spd.wavelengths,
        y=integral,
        dydx=spd.data,  # The data is the derivative of its own integral
        extrapolate=False,
    )
    # Evaluate in the middle of the bin (logic unclear, but better results)
    interpolated_integral = interpolator(wavelengths + diff(wavelengths / 2))
    valid = np.where(~np.isnan(interpolated_integral))[0]
    interpolated_integral[: valid[0]] = interpolated_integral[valid[0]]
    interpolated_integral[valid[-1] :] = interpolated_integral[valid[-1]]

    interpolated_data = diff(interpolated_integral) / diff(wavelengths)  # Derivate

    return SpectralPowerDistribution(
        wavelengths=wavelengths,
        data=interpolated_data,
        description=spd.description,
        quantity=spd.quantity,
    )
//  [python]
def process(self):
        # Read the input data
        input_signal = self.inputs[0].data
        int_rule = self.parameters["int_rule"].value
        # Calculate the ordinate
        if int_rule == "trapz":
            ordinate_int = integrate.cumtrapz(y=input_signal.ordinate,
                                              dx=input_signal.increment,
                                              initial=0)
        elif int_rule == "rect":
            ordinate_int = np.cumsum(
                input_signal.ordinate) * input_signal.increment
        # Apply new signal to the output
        self.outputs[0].data = data_types.Signal(
            abscissa_start=input_signal.abscissa_start,
            values=input_signal.values,
            increment=input_signal.increment,
            ordinate=ordinate_int,
        )
        # Calculate units for abscissa and ordinate
        unit_a = self.inputs[0].metadata.unit_a
        unit_o = self.inputs[0].metadata.unit_o * self.inputs[0].metadata.unit_a
        # Apply new metadata to the output
        self.outputs[0].process_metadata = data_types.MetaData(
            name=None, unit_a=unit_a, unit_o=unit_o
        )
//  [python]
def process(self):
        # Read the input data
        input_signal = self.inputs[0].data
        int_rule = self.parameters["int_rule"].value
        # Calculate the ordinate
        if int_rule == "trapz":
            ordinate_int = integrate.cumulative_trapezoid(y=input_signal.ordinate,
                                              dx=input_signal.increment,
                                              initial=0)
        elif int_rule == "rect":
            ordinate_int = np.cumsum(
                input_signal.ordinate) * input_signal.increment
        # Apply new signal to the output
        self.outputs[0].data = data_types.Signal(
            abscissa_start=input_signal.abscissa_start,
            values=input_signal.values,
            increment=input_signal.increment,
            ordinate=ordinate_int,
        )
        # Calculate units for abscissa and ordinate
        unit_a = self.inputs[0].metadata.unit_a
        unit_o = self.inputs[0].metadata.unit_o * self.inputs[0].metadata.unit_a
        # Apply new metadata to the output
        self.outputs[0].process_metadata = data_types.MetaData(
            name=None, unit_a=unit_a, unit_o=unit_o
        )
//  [python]
def pseudopressure(
    pressure: NDArray[np.float64],
    viscosity: NDArray[np.float64],
    z_factor: NDArray[np.float64],
) -> NDArray[np.float64]:
    """Calculate the pseudopressure using Al-Hussainy's relation.

    Parameters
    ----------
    pressure: NDArray, psi
    viscosity: NDArray, cp
    z_factor: NDArray, dimensionless

    Returns
    -------
    m : NDArray
        pseudopressure, psia^2 / cp
    """
    pp = 2 * pressure / (viscosity * z_factor)
    return sp.integrate.cumtrapz(pp, pressure, initial=0.0)
//  [python]
def pseudopressure(
    pressure: NDArray[np.float64],
    viscosity: NDArray[np.float64],
    z_factor: NDArray[np.float64],
) -> NDArray[np.float64]:
    """Calculate the pseudopressure using Al-Hussainy's relation.

    Parameters
    ----------
    pressure: NDArray, psi
    viscosity: NDArray, cp
    z_factor: NDArray, dimensionless

    Returns
    -------
    m : NDArray
        pseudopressure, psia^2 / cp
    """
    pp = 2 * pressure / (viscosity * z_factor)
    return sp.integrate.cumulative_trapezoid(pp, pressure, initial=0.0)
//  [python]
def cumulative_mass(self, r: np.ndarray) -> np.ndarray:
        """ Compute the enclosed mass at each radius """
        # check if the array r is equally spaced
        dr = r[1] - r[0]
        if np.any(np.abs(np.diff(r) - dr) > 1e-6):
            cmass = integrate.cumtrapz(
                4 * np.pi * r**2 * self.density(r), dx=dr)
        else:
            cmass = integrate.cumtrapz(
                4 * np.pi * r**2 * self.density(r), r)
        cmass = np.append(cmass, cmass[-1])
        return cmass
//  [python]
def cumulative_mass(self, r: np.ndarray) -> np.ndarray:
        """ Compute the enclosed mass at each radius """
        # check if the array r is equally spaced
        dr = r[1] - r[0]
        if np.any(np.abs(np.diff(r) - dr) > 1e-6):
            cmass = integrate.cumulative_trapezoid(
                4 * np.pi * r**2 * self.density(r), dx=dr)
        else:
            cmass = integrate.cumulative_trapezoid(
                4 * np.pi * r**2 * self.density(r), r)
        cmass = np.append(cmass, cmass[-1])
        return cmass
//  [python]
def integral(_item, xdata: list, ydata: list) -> _return:
    """Calculate indefinite integral of all selected data."""
    x_values = numpy.array(xdata)
    y_values = numpy.array(ydata)
    indefinite_integral = scipy.integrate.cumtrapz(
        y_values,
        x_values,
        initial=0,
    ).tolist()
    return xdata, indefinite_integral, False, True
//  [python]
def integral(_item, xdata: list, ydata: list) -> _return:
    """Calculate indefinite integral of all selected data."""
    x_values = numpy.array(xdata)
    y_values = numpy.array(ydata)
    indefinite_integral = scipy.integrate.cumulative_trapezoid(
        y_values,
        x_values,
        initial=0,
    ).tolist()
    return xdata, indefinite_integral, False, True
//  [python]
def test_instantaneous_rate_rate_estimation_consistency(self):
        """
        Test, whether the integral of the rate estimation curve is (almost)
        equal to the number of spikes of the spike train.
        """
        kernel_types = tuple(
            kern_cls for kern_cls in kernels.__dict__.values()
            if isinstance(kern_cls, type) and
            issubclass(kern_cls, kernels.Kernel) and
            kern_cls is not kernels.Kernel and
            kern_cls is not kernels.SymmetricKernel)
        # set sigma
        kernels_available = [kern_cls(sigma=0.5 * pq.s, invert=False)
                             for kern_cls in kernel_types]
        kernels_available.append('auto')
        kernel_resolution = 0.01 * pq.s
        for kernel in kernels_available:
            border_correction = False
            if isinstance(kernel, kernels.GaussianKernel):
                border_correction = True
            for center_kernel in (False, True):
                rate_estimate = statistics.instantaneous_rate(
                    self.spike_train,
                    sampling_period=kernel_resolution,
                    kernel=kernel,
                    t_start=self.st_tr[0] * pq.s,
                    t_stop=self.st_tr[1] * pq.s,
                    trim=False,
                    center_kernel=center_kernel,
                    border_correction=border_correction
                )
                num_spikes = len(self.spike_train)
                area_under_curve = spint.trapz(
                    y=rate_estimate.magnitude[:, 0],
                    x=rate_estimate.times.rescale('s').magnitude)
                self.assertAlmostEqual(num_spikes, area_under_curve,
                                       delta=0.01 * num_spikes)
//  [python]
def test_instantaneous_rate_rate_estimation_consistency(self):
        """
        Test, whether the integral of the rate estimation curve is (almost)
        equal to the number of spikes of the spike train.
        """
        kernel_types = tuple(
            kern_cls for kern_cls in kernels.__dict__.values()
            if isinstance(kern_cls, type) and
            issubclass(kern_cls, kernels.Kernel) and
            kern_cls is not kernels.Kernel and
            kern_cls is not kernels.SymmetricKernel)
        # set sigma
        kernels_available = [kern_cls(sigma=0.5 * pq.s, invert=False)
                             for kern_cls in kernel_types]
        kernels_available.append('auto')
        kernel_resolution = 0.01 * pq.s
        for kernel in kernels_available:
            border_correction = False
            if isinstance(kernel, kernels.GaussianKernel):
                border_correction = True
            for center_kernel in (False, True):
                rate_estimate = statistics.instantaneous_rate(
                    self.spike_train,
                    sampling_period=kernel_resolution,
                    kernel=kernel,
                    t_start=self.st_tr[0] * pq.s,
                    t_stop=self.st_tr[1] * pq.s,
                    trim=False,
                    center_kernel=center_kernel,
                    border_correction=border_correction
                )
                num_spikes = len(self.spike_train)
                area_under_curve = spint.cumulative_trapezoid(
                    y=rate_estimate.magnitude[:, 0],
                    x=rate_estimate.times.rescale('s').magnitude)[-1]
                self.assertAlmostEqual(num_spikes, area_under_curve,
                                       delta=0.01 * num_spikes)
//  [python]
def nonzero_integral(x, y):
    from scipy.integrate import trapz

    cumsum = np.concatenate(((0.0,), np.cumsum(trapz(y, x))))
    return cumsum[:-1] != cumsum[1:]
//  [python]
def nonzero_integral(x, y):
    from scipy.integrate import cumulative_trapezoid

    cumsum = np.concatenate(((0.0,), cumulative_trapezoid(y, x)))
    return cumsum[:-1] != cumsum[1:]
//  [python]
def get_eul_diff(M_omega, uL_r_v, 
                 eta, par_simp_prec, 
                 c_beta_0,
                 al_offset=0.):
    al_0, al_1_wrap, beta, c_beta, ep_0 \
        = get_eul_diff_core(M_omega, uL_r_v, 
                            eta, par_simp_prec, 
                            c_beta_0, al_offset)
    al_1 = np.unwrap(al_1_wrap)
    al = al_0 + al_1
    ep_1 = s.cumtrapz(c_beta - c_beta_0, al, initial=0)\
           + c_beta_0 * al_1
    return al_1, beta, ep_1, al_0, ep_0
//  [python]
def get_eul_diff(M_omega, uL_r_v, 
                 eta, par_simp_prec, 
                 c_beta_0,
                 al_offset=0.):
    al_0, al_1_wrap, beta, c_beta, ep_0 \
        = get_eul_diff_core(M_omega, uL_r_v, 
                            eta, par_simp_prec, 
                            c_beta_0, al_offset)
    al_1 = np.unwrap(al_1_wrap)
    al = al_0 + al_1
    ep_1 = integ.cumulative_trapezoid(c_beta - c_beta_0, al, initial=0)\
           + c_beta_0 * al_1
    return al_1, beta, ep_1, al_0, ep_0
//  [python]
def dynamic_pressure(T, S):

# because flow is out the domain with positive slope dont do any modification of sal/temp.

 #   for i in range(10):
#        S[i] -= 0.1*(10-i)*2e-4
#    S[:10] -= 0.00016  # try making the top of the domain a bit fresher as a hack to get faster flow at the rhs...
#    for i in range(10, len(T)):  
#        S[i] = 34
#        T[i] = -0.5
   
    density_rhs =  -g.values()[0] *(-beta_temp.values()[0] * (T-T_ref.values()[0]) +  beta_sal.values()[0] * (S - S_ref.values()[0]))
  #  print(density_rhs)



#    print("len z", len(z_rhs))
#    print("len density", len(density_rhs))
    pcumulative = scipy.integrate.cumtrapz(density_rhs, z_rhs, initial=0)
 #   print("pcumulative", pcumulative)
 #   print("len pcumulative", len(pcumulative))

    return pcumulative
//  [python]
def dynamic_pressure(T, S):

# because flow is out the domain with positive slope dont do any modification of sal/temp.

 #   for i in range(10):
#        S[i] -= 0.1*(10-i)*2e-4
#    S[:10] -= 0.00016  # try making the top of the domain a bit fresher as a hack to get faster flow at the rhs...
#    for i in range(10, len(T)):  
#        S[i] = 34
#        T[i] = -0.5
   
    density_rhs =  -g.values()[0] *(-beta_temp.values()[0] * (T-T_ref.values()[0]) +  beta_sal.values()[0] * (S - S_ref.values()[0]))
  #  print(density_rhs)



#    print("len z", len(z_rhs))
#    print("len density", len(density_rhs))
    pcumulative = scipy.integrate.cumulative_trapezoid(density_rhs, z_rhs, initial=0)
 #   print("pcumulative", pcumulative)
 #   print("len pcumulative", len(pcumulative))

    return pcumulative
//  [python]
def test_cumulative_trapz(self, seed, initial):
    """Test that cumulative_trapezoid matches the scipy implementation."""
    rng_state = jax.random.PRNGKey(seed)
    del seed  # Make sure seed isn't accidentally re-used

    rng_use_dim, rng_use_y, rng_use_x, _ = jax.random.split(
        rng_state, 4
    )
    dim = int(jax.random.randint(rng_use_dim, (1,), 1, 100)[0])
    y = jax.random.normal(rng_use_y, (dim,))
    del rng_use_y  # Make sure rng_use_y isn't accidentally re-used
    x = jax.random.normal(rng_use_x, (dim,))
    del rng_use_x  # Make sure rng_use_x isn't accidentally re-used

    cumulative = math_utils.cumulative_trapezoid(x, y, initial=initial)

    ref = scipy.integrate.trapz(y, x, initial=initial)

    np.testing.assert_allclose(cumulative, ref)
//  [python]
def test_cumulative_trapz(self, seed, initial):
    """Test that cumulative_trapezoid matches the scipy implementation."""
    rng_state = jax.random.PRNGKey(seed)
    del seed  # Make sure seed isn't accidentally re-used

    rng_use_dim, rng_use_y, rng_use_x, _ = jax.random.split(
        rng_state, 4
    )
    dim = int(jax.random.randint(rng_use_dim, (1,), 1, 100)[0])
    y = jax.random.normal(rng_use_y, (dim,))
    del rng_use_y  # Make sure rng_use_y isn't accidentally re-used
    x = jax.random.normal(rng_use_x, (dim,))
    del rng_use_x  # Make sure rng_use_x isn't accidentally re-used

    cumulative = math_utils.cumulative_trapezoid(x, y, initial=initial)

    ref = scipy.integrate.cumulative_trapezoid(y, x, initial=initial)

    np.testing.assert_allclose(cumulative, ref)
//  [python]
def energy_radiated(self) -> np.ndarray:
        """Energy radiated, :math:`E`.

        https://arxiv.org/pdf/0707.4654.pdf
        eq 3.8

        Returns:
            numpy.ndarray: cumulative :math:`E` radiated

        """
        energy_dot = self.dEnergy_dt_radiated
        energy_radiated = scipy.integrate.cumtrapz(energy_dot, self.time, initial=0)
        return energy_radiated
//  [python]
def energy_radiated(self) -> np.ndarray:
        """Energy radiated, :math:`E`.

        https://arxiv.org/pdf/0707.4654.pdf
        eq 3.8

        Returns:
            numpy.ndarray: cumulative :math:`E` radiated

        """
        energy_dot = self.dEnergy_dt_radiated
        energy_radiated = scipy.integrate.cumulative_trapezoid(energy_dot, self.time, initial=0)
        return energy_radiated
//  [python]
def _sample_pdf(self, f_idx, us):
        """
        Generates samples xs from the f_idx'th pdf such that F(xs) = us

        :param f_idx: integer indexing into self.pdfs
        :param us: np.ndarray of shape (num_samples,). The number of
                   samples returned will match this
        :param num_integration_samples: number of samples used to approximate F(x)
        :returns: np.ndarray of same shape as us
        """
        cache = self.pdf_cache[f_idx]
        # we also need to redo the cache if the number of samples changed
        if cache is None:
            A, B = self.pdf_bounds[f_idx]
            xs = np.linspace(A, B, self.pdf_num_samples)

            Fs = scipy.integrate.cumtrapz(self.pdfs[f_idx](xs), xs, initial = 0)
            # normalize the CDF so endpoint is at 1 (as pdf f might be unnormalized)
            Fs /= np.max(Fs)

            # shape (num_samples, 2):
            #   first column contains F(x)s
            #   second column contains xs
            cache = np.stack([Fs, xs]).T
            self.pdf_cache[f_idx] = cache

        # Find the idx such that F(x[idx]) = us
        cache_idx = np.searchsorted(cache[:, 0], us, side = 'right')
        samples = cache[cache_idx, 1]
        return samples
//  [python]
def _sample_pdf(self, f_idx, us):
        """
        Generates samples xs from the f_idx'th pdf such that F(xs) = us

        :param f_idx: integer indexing into self.pdfs
        :param us: np.ndarray of shape (num_samples,). The number of
                   samples returned will match this
        :param num_integration_samples: number of samples used to approximate F(x)
        :returns: np.ndarray of same shape as us
        """
        cache = self.pdf_cache[f_idx]
        # we also need to redo the cache if the number of samples changed
        if cache is None:
            A, B = self.pdf_bounds[f_idx]
            xs = np.linspace(A, B, self.pdf_num_samples)

            Fs = scipy.integrate.cumulative_trapezoid(self.pdfs[f_idx](xs), xs, initial = 0)
            # normalize the CDF so endpoint is at 1 (as pdf f might be unnormalized)
            Fs /= np.max(Fs)

            # shape (num_samples, 2):
            #   first column contains F(x)s
            #   second column contains xs
            cache = np.stack([Fs, xs]).T
            self.pdf_cache[f_idx] = cache

        # Find the idx such that F(x[idx]) = us
        cache_idx = np.searchsorted(cache[:, 0], us, side = 'right')
        samples = cache[cache_idx, 1]
        return samples
//  [python]
def linear_momentum_radiated(self) -> np.ndarray:
        """Linear momentum radiated as gravitational waves

        https://arxiv.org/pdf/0707.4654.pdf
        eqs 3.14, 3.15

        Returns:
            numpy.ndarray: linear momentum radiated

        """
        Pdot = self.dP_dt_radiated
        linear_momentum_radiated = scipy.integrate.cumtrapz(Pdot, self.time, initial=0, axis=0)
        return linear_momentum_radiated
//  [python]
def linear_momentum_radiated(self) -> np.ndarray:
        """Linear momentum radiated as gravitational waves

        https://arxiv.org/pdf/0707.4654.pdf
        eqs 3.14, 3.15

        Returns:
            numpy.ndarray: linear momentum radiated

        """
        Pdot = self.dP_dt_radiated
        linear_momentum_radiated = scipy.integrate.cumulative_trapezoid(Pdot, self.time, initial=0, axis=0)
        return linear_momentum_radiated
//  [python]
def plot_running_integral(
        self,
        start=0,
        stop=0,
        step=1,
        initial=0,
        xlabel="Time (ps)",
        ylabel="Running Integral of the VACF (Å^2 / ps)",
    ):
        """
        Returns a plot of the running integral of the
        velocity autocorrelation function (VACF) via ``Matplotlib``.
        In this case, the running integral is the integral of the VACF
        divided by the dimensionality. Analysis must be run prior to plotting.

        Parameters
        ----------
        start : Optional[int]
            The first frame of ``self.results.timeseries``
            used for the plot.
        stop : Optional[int]
            The frame of ``self.results.timeseries`` to stop at
            for the plot, non-inclusive.
        step : Optional[int]
            Number of frames to skip between each plotted frame.
        initial : Optional[float]
            Inserted value at the beginning of the integrated result array.
            Defaults to 0.
        xlabel : Optional[str]
            The x-axis label text. Defaults to "Time (ps)".
        ylabel : Optional[str]
            The y-axis label text.
            Defaults to "Running Integral of the VACF (Å^2 / ps)".

        Returns
        -------
        :class:`matplotlib.lines.Line2D`
            A :class:`matplotlib.lines.Line2D` instance with
            the desired VACF plotting information.
        """
        if not self._run_called:
            raise RuntimeError("Analysis must be run prior to plotting")

        stop = self.n_frames if stop == 0 else stop

        running_integral = (
            integrate.cumtrapz(
                self.results.timeseries[start:stop:step],
                self.times[start:stop:step],
                initial=initial,
            )
            / self.dim_fac
        )

        fig, ax_running_integral = plt.subplots()
        ax_running_integral.set_xlabel(xlabel)
        ax_running_integral.set_ylabel(ylabel)
        return ax_running_integral.plot(
            self.times[start:stop:step],
            running_integral,
        )
//  [python]
def plot_running_integral(
        self,
        start=0,
        stop=0,
        step=1,
        initial=0,
        xlabel="Time (ps)",
        ylabel="Running Integral of the VACF (Å^2 / ps)",
    ):
        """
        Returns a plot of the running integral of the
        velocity autocorrelation function (VACF) via ``Matplotlib``.
        In this case, the running integral is the integral of the VACF
        divided by the dimensionality. Analysis must be run prior to plotting.

        Parameters
        ----------
        start : Optional[int]
            The first frame of ``self.results.timeseries``
            used for the plot.
        stop : Optional[int]
            The frame of ``self.results.timeseries`` to stop at
            for the plot, non-inclusive.
        step : Optional[int]
            Number of frames to skip between each plotted frame.
        initial : Optional[float]
            Inserted value at the beginning of the integrated result array.
            Defaults to 0.
        xlabel : Optional[str]
            The x-axis label text. Defaults to "Time (ps)".
        ylabel : Optional[str]
            The y-axis label text.
            Defaults to "Running Integral of the VACF (Å^2 / ps)".

        Returns
        -------
        :class:`matplotlib.lines.Line2D`
            A :class:`matplotlib.lines.Line2D` instance with
            the desired VACF plotting information.
        """
        if not self._run_called:
            raise RuntimeError("Analysis must be run prior to plotting")

        stop = self.n_frames if stop == 0 else stop

        running_integral = (
            integrate.cumulative_trapezoid(
                self.results.timeseries[start:stop:step],
                self.times[start:stop:step],
                initial=initial,
            )
            / self.dim_fac
        )

        fig, ax_running_integral = plt.subplots()
        ax_running_integral.set_xlabel(xlabel)
        ax_running_integral.set_ylabel(ylabel)
        return ax_running_integral.plot(
            self.times[start:stop:step],
            running_integral,
        )
//  [python]
def _build_attributes(self):
        """
        Method that builds the inverse cdf of the P(pixel) distribution for rescaling
        """
        from scipy.integrate import trapz
        yy = self._all_interped(self.pix_xx)
        yy /= np.trapz(yy, self.pix_xx)
        YY = np.cumsum(yy * np.diff(self.pix_xx))
        YY = np.concatenate(([0],YY))
        YY /= YY[-1]
        self.inverse_cdf = interp1d(x=YY, y=self.pix_xx, bounds_error=True)
//  [python]
def _build_attributes(self):
        """
        Method that builds the inverse cdf of the P(pixel) distribution for rescaling
        """
        from scipy.integrate import cumulative_trapezoid
        yy = self._all_interped(self.pix_xx)
        yy /= np.trapz(yy, self.pix_xx)
        YY = cumulative_trapezoid(yy, self.pix_xx, initial=0)
        YY[-1] = 1
        self.inverse_cdf = interp1d(x=YY, y=self.pix_xx, bounds_error=True)
//  [python]
def _draw_random_points_from_tab_distribution(x_tab, pdf_tab, nobj=1, xmin=None, xmax=None):
    """Draw random points from a tabulated distribution.

    Parameters
    ----------
    x_tab : array-like
        Values for which the tabulated pdf is provided
    pdf_tab : array-like
        Value of the pdf at the x_tab locations
    nobj : int, optional
        Number of random samples to generate. Default is 1.
    xmin : float, optional
        Lower bound to draw redshift. Default is the min(x_tab)
    xmax : float, optional
        Upper bound to draw redshift. Default is the max(x_tab)

    Returns
    -------
    samples : numpy.ndarray
        Random points following the pdf_tab distribution
    """
    x_tab = np.array(x_tab)
    pdf_tab = np.array(pdf_tab)
    cdf = np.array([simps(pdf_tab[:j], x_tab[:j]) for j in range(1, len(x_tab)+1)])
    cdf /= cdf.max()
    cdf_xmin, cdf_xmax = 0.0, 1.0
    if xmin or xmax:
        cdf_interp = interp1d(x_tab, cdf, kind="linear")
        if xmin is not None:
            if xmin < x_tab.min():
                warnings.warn(
                    "`xmin` is less than the minimum value of `x_tab`. "
                    + f"Using min(x_tab)={x_tab.min()} instead."
                )
            else:
                cdf_xmin = cdf_interp(xmin)
        if xmax is not None:
            if xmax > x_tab.max():
                warnings.warn(
                    "`xmax` is greater than the maximum value of `x_tab`. "
                    + f"Using max(x_tab)={x_tab.max()} instead."
                )
            else:
                cdf_xmax = cdf_interp(xmax)
    inv_cdf = interp1d(cdf, x_tab, kind="linear", bounds_error=False, fill_value=0.0)
    samples = inv_cdf(np.random.random(nobj) * (cdf_xmax - cdf_xmin) + cdf_xmin)
    return samples
//  [python]
def _draw_random_points_from_tab_distribution(x_tab, pdf_tab, nobj=1, xmin=None, xmax=None):
    """Draw random points from a tabulated distribution.

    Parameters
    ----------
    x_tab : array-like
        Values for which the tabulated pdf is provided
    pdf_tab : array-like
        Value of the pdf at the x_tab locations
    nobj : int, optional
        Number of random samples to generate. Default is 1.
    xmin : float, optional
        Lower bound to draw redshift. Default is the min(x_tab)
    xmax : float, optional
        Upper bound to draw redshift. Default is the max(x_tab)

    Returns
    -------
    samples : numpy.ndarray
        Random points following the pdf_tab distribution
    """
    x_tab = np.array(x_tab)
    pdf_tab = np.array(pdf_tab)
    # cdf = np.array([simps(pdf_tab[:j], x_tab[:j]) for j in range(1, len(x_tab)+1)])
    cdf = cumulative_trapezoid(pdf_tab, x_tab, initial=0)
    # Normalise it
    cdf /= cdf.max()
    cdf_xmin, cdf_xmax = 0.0, 1.0
    # Interpolate cdf at xmin and xmax
    if xmin or xmax:
        cdf_interp = interp1d(x_tab, cdf, kind="linear")
        if xmin is not None:
            if xmin < x_tab.min():
                warnings.warn(
                    "`xmin` is less than the minimum value of `x_tab`. "
                    + f"Using min(x_tab)={x_tab.min()} instead."
                )
            else:
                cdf_xmin = cdf_interp(xmin)
        if xmax is not None:
            if xmax > x_tab.max():
                warnings.warn(
                    "`xmax` is greater than the maximum value of `x_tab`. "
                    + f"Using max(x_tab)={x_tab.max()} instead."
                )
            else:
                cdf_xmax = cdf_interp(xmax)
    # Interpolate the inverse CDF
    inv_cdf = interp1d(cdf, x_tab, kind="linear", bounds_error=False, fill_value=0.0)
    # Finally generate sample from uniform distribution and
    # get the corresponding samples
    samples = inv_cdf(np.random.random(nobj) * (cdf_xmax - cdf_xmin) + cdf_xmin)
    return samples
//  [python]
def _inverse_cdf_and_jacobian(cdf_val, points, pdf_points):
    """
    Find the value of x such that
        int_{-inf}^x P(x') dx' = cdf
    where P(x) is a linear spline interpolating {points: pdf_points},
    then normalized to integrate to 1.
    Also return the jacobian dc/dx.
    Note: we interpolate P(x) with a linear spline because that's the
    highest order that preserves P >= 0.
    """
    if np.any(points[:-1] >= points[1:]):
        raise ValueError('`points` should be sorted.')

    if np.any(pdf_points < 0):
        raise ValueError('`pdf_points` should be >= 0.')

    cdf_points = np.cumsum(pdf_points * np.diff(points, prepend=0))
    pdf_points /= cdf_points[-1]
    cdf_points /= cdf_points[-1]
    x_guess = np.interp(cdf_val, cdf_points, points)

    pdf = scipy.interpolate.InterpolatedUnivariateSpline(points, pdf_points,
                                                         k=1, ext='raise')
    cdf = pdf.antiderivative()
    x_val = scipy.optimize.newton(lambda x: cdf(x) - cdf_val, x_guess,
                                  fprime=pdf,
                                  # fprime2=pdf.derivative()
                                  )

    dc_dx = pdf(x_val)[()]
    return x_val, dc_dx
//  [python]
def _inverse_cdf_and_jacobian(cdf_val, points, pdf_points):
    """
    Find the value of x such that
        int_{-inf}^x P(x') dx' = cdf
    where P(x) is a linear spline interpolating {points: pdf_points},
    then normalized to integrate to 1.
    Also return the jacobian dc/dx.
    Note: we interpolate P(x) with a linear spline because that's the
    highest order that preserves P >= 0.
    """
    if np.any(points[:-1] >= points[1:]):
        raise ValueError('`points` should be sorted.')

    if np.any(pdf_points < 0):
        raise ValueError('`pdf_points` should be >= 0.')

    cdf_points = scipy.integrate.cumulative_trapezoid(pdf_points, points,
                                                      initial=0)
    pdf_points /= cdf_points[-1]
    cdf_points /= cdf_points[-1]
    x_guess = np.interp(cdf_val, cdf_points, points)

    pdf = scipy.interpolate.InterpolatedUnivariateSpline(points, pdf_points,
                                                         k=1, ext='raise')
    cdf = pdf.antiderivative()
    x_val = scipy.optimize.newton(lambda x: cdf(x) - cdf_val, x_guess,
                                  fprime=pdf,
                                  # fprime2=pdf.derivative()
                                  )

    dc_dx = pdf(x_val)[()]
    return x_val, dc_dx
//  [python]
def test_energy_radiated(self):
        # check with what it should be
        from mayawaves.coalescence import Coalescence
        coalescence = Coalescence(os.path.join(self.CURR_DIR,
                                               'resources/radiative_quantities_resources/D11_q2_a1_0.0_0.0_0.4_a2_0.0_0.0_0.4_m282.35.h5'))

        radiation_bundle = coalescence.radiationbundle
        radiation_sphere = radiation_bundle.radiation_spheres[75]
        radiation_mode = radiation_sphere.modes[(2, 2)]
        generated_energy_radiated = radiation_mode.energy_radiated

        denergy_dt_radiated = radiation_mode.dEnergy_dt_radiated
        time = radiation_mode.time
        expected_energy_radiated = scipy.integrate.cumtrapz(denergy_dt_radiated, time, initial=0)

        self.assertTrue(np.all(expected_energy_radiated == generated_energy_radiated))

        # check that 22 mode is greater than 33 mode
        energy_radiated_22 = radiation_sphere.modes[(2, 2)].energy_radiated
        energy_radiated_33 = radiation_sphere.modes[(3, 3)].energy_radiated
        self.assertTrue(energy_radiated_22[-1] > energy_radiated_33[-1])
//  [python]
def test_energy_radiated(self):
        # check with what it should be
        from mayawaves.coalescence import Coalescence
        coalescence = Coalescence(os.path.join(self.CURR_DIR,
                                               'resources/radiative_quantities_resources/D11_q2_a1_0.0_0.0_0.4_a2_0.0_0.0_0.4_m282.35.h5'))

        radiation_bundle = coalescence.radiationbundle
        radiation_sphere = radiation_bundle.radiation_spheres[75]
        radiation_mode = radiation_sphere.modes[(2, 2)]
        generated_energy_radiated = radiation_mode.energy_radiated

        denergy_dt_radiated = radiation_mode.dEnergy_dt_radiated
        time = radiation_mode.time
        expected_energy_radiated = scipy.integrate.cumulative_trapezoid(denergy_dt_radiated, time, initial=0)

        self.assertTrue(np.all(expected_energy_radiated == generated_energy_radiated))

        # check that 22 mode is greater than 33 mode
        energy_radiated_22 = radiation_sphere.modes[(2, 2)].energy_radiated
        energy_radiated_33 = radiation_sphere.modes[(3, 3)].energy_radiated
        self.assertTrue(energy_radiated_22[-1] > energy_radiated_33[-1])
//  [python]
def cumulative_integral(
        self, integration_type: INTEGRATION_TYPE_OPTS = "trapz"
    ) -> NumpyRealNumberArray:
        """Cumulative integration starting at t=0 and ending at each frame_end.

        If start_time > 0, the triangular area between (t=0, 0) and
        (t=start_time, dataobj value at 0th frame) will be added to each
        cumulative integral.

        Args:
            integration_type: rect (rectangular) or trapz (trapezoidal).

        Returns:
            cumulative integral, with same shape as dataobj

        Raises:
            ValueError: invalid integration type
        """
        if self.has_gaps():
            warnings.warn(
                (
                    "TemporalObject has time gaps between frames. "
                    "Make sure that gaps do not mask important temporal dynamics."
                ),
                RuntimeWarning,
                stacklevel=2,
            )
            if integration_type == "rect":
                warnings.warn(
                    (
                        "Rectangular integration is not available for "
                        "TemporalObjects with time gaps between frames. "
                        "Changing to trapezoidal integration."
                    ),
                    RuntimeWarning,
                    stacklevel=2,
                )
                integration_type = "trapz"

        # if start_time > 0, then we assume activity linearly increased from 0
        # to values attained in first frame
        initial = self.start_time * self.dataobj[..., 0] / 2
        res: NumpyRealNumberArray

        if integration_type == "rect":
            res = (
                np.cumsum(self.dataobj * self.frame_duration, axis=-1)
                + initial[..., np.newaxis]
            )
        elif integration_type == "trapz":
            res = (
                np.cumsum((self.dataobj[..., 1:] + self.dataobj[..., :-1]) / 2 * np.diff(self.frame_mid, axis=-1), axis=-1)
                + initial[..., np.newaxis]
            )
        else:
            raise ValueError("integration_type" + integration_type + "is invalid")
        return res