jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def prior_energy_balance(data, GALAXYatt_dict, GALAXYFdict, gal_obj, GA, STARBURST_LIRdict,sb_obj,SB, models):

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

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

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

    if Lsb_emit < Lgal_att:
        return -9999 #-np.inf
    elif (Lsb_emit >= Lgal_att) and (models.settings['PRIOR_energy_balance'] == 'Flexible'):
        return 0
    elif (Lsb_emit >= Lgal_att) and (models.settings['PRIOR_energy_balance'] == 'Restrictive'):
        frac_SB_attGal = np.log10(Lsb_emit/Lgal_att)
        mu = 0
        sigma = 0.1
        prior_frac = Gaussian_prior(mu, sigma, frac_SB_attGal)
        return prior_frac
//  [python]
def get_cavdi(self):
        """Cumulative Absolute Velocity (CAV) ，Displacement (CAD) and Impetus(CAI).
        """
        CAV = trapz(np.abs(self.acc), self.time)
        CAD = trapz(np.abs(self.vel), self.time)
        CAI = trapz(np.abs(self.disp), self.time)
        return CAV * self.vel_factor, CAD, CAI
//  [python]
def get_cavdi(self):
        """Cumulative Absolute Velocity (CAV) ，Displacement (CAD) and Impetus(CAI).
        """
        CAV = trapezoid(np.abs(self.acc), self.time)
        CAD = trapezoid(np.abs(self.vel), self.time)
        CAI = trapezoid(np.abs(self.disp), self.time)
        return CAV * self.vel_factor, CAD, CAI
//  [python]
def simulated_age_intervals(data_type, n, a, pi_age_true, sigma_true):
    # choose age intervals to measure
    age_start = pl.array(mc.runiform(0, 100, n), dtype=int)
    age_start.sort()  # sort to make it easy to discard the edges when testing
    age_end = pl.array(mc.runiform(age_start+1, pl.minimum(age_start+10,100)), dtype=int)

    # find truth for the integral across the age intervals
    import scipy.integrate
    pi_interval_true = [scipy.integrate.trapz(pi_age_true[a_0i:(a_1i+1)]) / (a_1i - a_0i) 
                        for a_0i, a_1i in zip(age_start, age_end)]

    # generate covariates that add explained variation
    X = mc.rnormal(0., 1.**2, size=(n,3))
    beta_true = [-.1, .1, .2]
    beta_true = [0, 0, 0]
    Y_true = pl.dot(X, beta_true)

    # calculate the true value of the rate in each interval
    pi_true = pi_interval_true*pl.exp(Y_true)

    # simulate the noisy measurement of the rate in each interval
    p = pl.maximum(0., mc.rnormal(pi_true, 1./sigma_true**2.))

    # store the simulated data in a pandas DataFrame
    data = pandas.DataFrame(dict(value=p, age_start=age_start, age_end=age_end,
                                 x_0=X[:,0], x_1=X[:,1], x_2=X[:,2]))
    data['effective_sample_size'] = pl.maximum(p*(1-p)/sigma_true**2, 1.)

    data['standard_error'] = pl.nan
    data['upper_ci'] = pl.nan
    data['lower_ci'] = pl.nan

    data['year_start'] = 2005.  # TODO: make these vary
    data['year_end'] = 2005.
    data['sex'] = 'total'
    data['area'] = 'all'
    data['data_type'] = data_type
    
    return data
//  [python]
def simulated_age_intervals(data_type, n, a, pi_age_true, sigma_true):
    # choose age intervals to measure
    age_start = pl.array(mc.runiform(0, 100, n), dtype=int)
    age_start.sort()  # sort to make it easy to discard the edges when testing
    age_end = pl.array(mc.runiform(age_start+1, pl.minimum(age_start+10,100)), dtype=int)

    # find truth for the integral across the age intervals
    import scipy.integrate
    pi_interval_true = [scipy.integrate.trapezoid(pi_age_true[a_0i:(a_1i+1)]) / (a_1i - a_0i) 
                        for a_0i, a_1i in zip(age_start, age_end)]

    # generate covariates that add explained variation
    X = mc.rnormal(0., 1.**2, size=(n,3))
    beta_true = [-.1, .1, .2]
    beta_true = [0, 0, 0]
    Y_true = pl.dot(X, beta_true)

    # calculate the true value of the rate in each interval
    pi_true = pi_interval_true*pl.exp(Y_true)

    # simulate the noisy measurement of the rate in each interval
    p = pl.maximum(0., mc.rnormal(pi_true, 1./sigma_true**2.))

    # store the simulated data in a pandas DataFrame
    data = pandas.DataFrame(dict(value=p, age_start=age_start, age_end=age_end,
                                 x_0=X[:,0], x_1=X[:,1], x_2=X[:,2]))
    data['effective_sample_size'] = pl.maximum(p*(1-p)/sigma_true**2, 1.)

    data['standard_error'] = pl.nan
    data['upper_ci'] = pl.nan
    data['lower_ci'] = pl.nan

    data['year_start'] = 2005.  # TODO: make these vary
    data['year_end'] = 2005.
    data['sex'] = 'total'
    data['area'] = 'all'
    data['data_type'] = data_type
    
    return data
//  [python]
def get_pavd(self):
        """Housner earthquake power index, Pa, Pv, Pd"""
        if self.Arias is None:
            _ = self.get_ia()
        Arias = self.Arias
        series = self.AriasSeries
        idx_5_95 = (series >= 0.05 * Arias) & (series <= 0.95 * Arias)
        timed = self.time[idx_5_95]
        accsigDura = self.acc[idx_5_95]
        Pa = trapz(accsigDura ** 2, timed) / (timed[-1] - timed[0])
        Pv = trapz(self.vel[idx_5_95] ** 2, timed) / (timed[-1] - timed[0])
        Pd = trapz(self.disp[idx_5_95] ** 2, timed) / (timed[-1] - timed[0])
        return Pa, Pv, Pd
//  [python]
def get_pavd(self):
        """Housner earthquake power index, Pa, Pv, Pd"""
        if self.Arias is None:
            _ = self.get_ia()
        Arias = self.Arias
        series = self.AriasSeries
        idx_5_95 = (series >= 0.05 * Arias) & (series <= 0.95 * Arias)
        timed = self.time[idx_5_95]
        accsigDura = self.acc[idx_5_95]
        Pa = trapezoid(accsigDura ** 2, timed) / (timed[-1] - timed[0])
        Pv = trapezoid(self.vel[idx_5_95] ** 2, timed) / (timed[-1] - timed[0])
        Pd = trapezoid(self.disp[idx_5_95] ** 2, timed) / (timed[-1] - timed[0])
        return Pa, Pv, Pd
//  [python]
def A_H1HW(u,tau,P0T,lambd,eta,kappa,gamma,vbar,v0,rhoxv,rhoxr):
    i  = np.complex(0.0,1.0)
    D1 = np.sqrt(np.power(kappa-gamma*rhoxv*i*u,2)+(u*u+i*u)*gamma*gamma)
    g  = (kappa-gamma*rhoxv*i*u-D1)/(kappa-gamma*rhoxv*i*u+D1)
    
    # Function theta(t)

    dt = 0.0001    
    f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2.0*dt)
    theta = lambda t: 1.0/lambd * (f0T(t+dt)-f0T(t-dt))/(2.0*dt) + f0T(t) + eta*eta/(2.0*lambd*lambd)*(1.0-np.exp(-2.0*lambd*t))  

    # Integration within the function I_1

    N  = 500
    z  = np.linspace(0,tau-1e-10,N)
    f1 = (1.0-np.exp(-lambd*z))*theta(tau-z)
    value1 = integrate.trapz(f1,z)
    
    # Note that I_1_adj also allows time-dependent theta 
    # Therefore it is not exactly the same as in the book

    I_1_adj = (i*u-1.0) * value1
    I_2     = tau/(gamma**2.0) *(kappa-gamma*rhoxv*i*u-D1) - 2.0/(gamma**2.0)*np.log((1.0-g*np.exp(-D1*tau))/(1.0-g))
    I_3     = 1.0/(2.0*np.power(lambd,3.0))* np.power(i+u,2.0)*(3.0+np.exp(-2.0*lambd*tau)-4.0*np.exp(-lambd*tau)-2.0*lambd*tau)
    
    meanSqrtV = meanSqrtV_3(kappa,v0,vbar,gamma)
    f2        = meanSqrtV(tau-z)*(1.0-np.exp(-lambd*z))
    value2    = integrate.trapz(f2,z)
    I_4       = -1.0/lambd * (i*u+u**2.0)*value2
    
    return I_1_adj + kappa*vbar*I_2 + 0.5*eta**2.0*I_3+eta*rhoxr*I_4
//  [python]
def A_H1HW(u,tau,P0T,lambd,eta,kappa,gamma,vbar,v0,rhoxv,rhoxr):
    i  = np.complex(0.0,1.0)
    D1 = np.sqrt(np.power(kappa-gamma*rhoxv*i*u,2)+(u*u+i*u)*gamma*gamma)
    g  = (kappa-gamma*rhoxv*i*u-D1)/(kappa-gamma*rhoxv*i*u+D1)
    
    # Function theta(t)

    dt = 0.0001    
    f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2.0*dt)
    theta = lambda t: 1.0/lambd * (f0T(t+dt)-f0T(t-dt))/(2.0*dt) + f0T(t) + eta*eta/(2.0*lambd*lambd)*(1.0-np.exp(-2.0*lambd*t))  

    # Integration within the function I_1

    N  = 500
    z  = np.linspace(0,tau-1e-10,N)
    f1 = (1.0-np.exp(-lambd*z))*theta(tau-z)
    value1 = integrate.trapezoid(f1,z)
    
    # Note that I_1_adj also allows time-dependent theta 
    # Therefore it is not exactly the same as in the book

    I_1_adj = (i*u-1.0) * value1
    I_2     = tau/(gamma**2.0) *(kappa-gamma*rhoxv*i*u-D1) - 2.0/(gamma**2.0)*np.log((1.0-g*np.exp(-D1*tau))/(1.0-g))
    I_3     = 1.0/(2.0*np.power(lambd,3.0))* np.power(i+u,2.0)*(3.0+np.exp(-2.0*lambd*tau)-4.0*np.exp(-lambd*tau)-2.0*lambd*tau)
    
    meanSqrtV = meanSqrtV_3(kappa,v0,vbar,gamma)
    f2        = meanSqrtV(tau-z)*(1.0-np.exp(-lambd*z))
    value2    = integrate.trapezoid(f2,z)
    I_4       = -1.0/lambd * (i*u+u**2.0)*value2
    
    return I_1_adj + kappa*vbar*I_2 + 0.5*eta**2.0*I_3+eta*rhoxr*I_4
//  [python]
def get_cavstd(self):
        """Standardized Cumulative Absolute Velocity (CAVSTD) [Campbell and Bozorgnia 2011].
        """
        ts = np.arange(np.floor(self.time[-1]) + 1)
        acc = self.acc / self.unit_factors[f'g-{self.acc_unit}']
        idxs = []
        for t in ts:
            idx = np.argmin(np.abs(self.time - t))
            idxs.append(idx)
        idxs.append(len(self.time) - 1)
        cavs = []
        for i in range(len(idxs) - 1):
            p = trapz(np.abs(acc[idxs[i]:idxs[i + 1] + 1]),
                      self.time[idxs[i]:idxs[i + 1] + 1])
            pgai = np.max(np.abs(acc[idxs[i]:idxs[i + 1] + 1]))
            a = 0 if pgai - 0.025 < 0 else 1
            cavs.append(a * p)
        cavstd = np.sum(cavs)
        return cavstd
//  [python]
def get_cavstd(self):
        """Standardized Cumulative Absolute Velocity (CAVSTD) [Campbell and Bozorgnia 2011].
        """
        ts = np.arange(np.floor(self.time[-1]) + 1)
        acc = self.acc / self.unit_factors[f'g-{self.acc_unit}']
        idxs = []
        for t in ts:
            idx = np.argmin(np.abs(self.time - t))
            idxs.append(idx)
        idxs.append(len(self.time) - 1)
        cavs = []
        for i in range(len(idxs) - 1):
            p = np.trapz(np.abs(acc[idxs[i]:idxs[i + 1] + 1]),
                      self.time[idxs[i]:idxs[i + 1] + 1])
            pgai = np.max(np.abs(acc[idxs[i]:idxs[i + 1] + 1]))
            a = 0 if pgai - 0.025 < 0 else 1
            cavs.append(a * p)
        cavstd = np.sum(cavs)
        return cavstd
//  [python]
def expected_cumulative_spectral_distribution(self, lam, precision=PRECISION, accumulate=False):
        if lam < self.min_lam:
            return 0.

        lams = self.generate_lams(lam, precision)

        singular_mass = self.expected_spectral_singular_mass()
        density_values = [self.expected_spectral_density(lam) for lam in lams]
        if not accumulate:
            accumulated_density = scipy.integrate.trapz(density_values, lams)
            return ((lam >= 0) * singular_mass) + accumulated_density
        else:
            accumulated_densities = scipy.integrate.cumtrapz(density_values, lams)
            accumulated_masses = singular_mass * (lams[1:] >= 0) + accumulated_densities
            return accumulated_masses
//  [python]
def expected_cumulative_spectral_distribution(self, lam, precision=PRECISION, accumulate=False):
        if lam < self.min_lam:
            return 0.

        lams = self.generate_lams(lam, precision)

        singular_mass = self.expected_spectral_singular_mass()
        density_values = [self.expected_spectral_density(lam) for lam in lams]
        if not accumulate:
            accumulated_density = scipy.integrate.trapezoid(density_values, lams)
            return ((lam >= 0) * singular_mass) + accumulated_density
        else:
            accumulated_densities = scipy.integrate.cumtrapz(density_values, lams)
            accumulated_masses = singular_mass * (lams[1:] >= 0) + accumulated_densities
            return accumulated_masses
//  [python]
def get_hsi(self,
                damp_ratio: float = 0.05):
        """Housner Spectra Intensity (HSI).

        Parameters
        ----------
        damp_ratio : float, optional
            Damping ratio, by default 0.05.

        Returns
        -------
        HSI: float
            Housner Spectra Intensity (HSI)
        """
        if self.Tsp is None:
            output = self._spectrum_prefit(damp_ratio)
        else:
            output = self.Spec_sp
        PSv = output[:, 1]
        HSIidxLow = np.argwhere(np.abs(self.Tsp - 0.1) <= 1E-8).item()
        HSIidxTop = np.argwhere(np.abs(self.Tsp - 2.5) <= 1E-8).item()
        hsi = 1 / 2.4 * trapz(PSv[HSIidxLow:HSIidxTop],
                              self.Tsp[HSIidxLow:HSIidxTop])
        return hsi
//  [python]
def get_hsi(self,
                damp_ratio: float = 0.05):
        """Housner Spectra Intensity (HSI).

        Parameters
        ----------
        damp_ratio : float, optional
            Damping ratio, by default 0.05.

        Returns
        -------
        HSI: float
            Housner Spectra Intensity (HSI)
        """
        if self.Tsp is None:
            output = self._spectrum_prefit(damp_ratio)
        else:
            output = self.Spec_sp
        PSv = output[:, 1]
        HSIidxLow = np.argwhere(np.abs(self.Tsp - 0.1) <= 1E-8).item()
        HSIidxTop = np.argwhere(np.abs(self.Tsp - 2.5) <= 1E-8).item()
        hsi = 1 / 2.4 * np.trapz(PSv[HSIidxLow:HSIidxTop],
                              self.Tsp[HSIidxLow:HSIidxTop])
        return hsi
//  [python]
def debye_func(x, nstep=100, zero=1e-8):
    r"""Debye function

    :math:`f(x) = 3 \int_0^1 t^3 / [\exp(t x) - 1] dt`

    Parameters
    ----------
    x : float or 1d array
    nstep : int
        number of points for integration
    zero : float
        approximate the 0 in the integral by this (small!) number
    """
    x = np.atleast_1d(x)
    if x.ndim == 1:
        x = x[:,None]
    else:
        raise Exception("x is not 1d array")
    tt = np.linspace(zero, 1.0, nstep)
    return 3.0 * trapz(tt**3.0 / (np.exp(tt*x) - 1.0), tt, axis=1)
//  [python]
def debye_func(x, nstep=100, zero=1e-8):
    r"""Debye function

    :math:`f(x) = 3 \int_0^1 t^3 / [\exp(t x) - 1] dt`

    Parameters
    ----------
    x : float or 1d array
    nstep : int
        number of points for integration
    zero : float
        approximate the 0 in the integral by this (small!) number
    """
    x = np.atleast_1d(x)
    if x.ndim == 1:
        x = x[:,None]
    else:
        raise Exception("x is not 1d array")
    tt = np.linspace(zero, 1.0, nstep)
    return 3.0 * trapezoid(tt**3.0 / (np.exp(tt*x) - 1.0), tt, axis=1)
//  [python]
def get_avdsi(self,
                  damp_ratio: float = 0.05):
        """Acceleration (ASI)，Velocity (VSI) and Displacement(DSI) Spectrum Intensity.

        Parameters
        ----------
        damp_ratio : float, optional
            Damping ratio, by default 0.05.

        Returns
        -------
        AVD_SI: 1D ArrayLike
            Each element is in the order of acceleration, velocity and displacement.
        """
        if self.Tsp is None:
            output = self._spectrum_prefit(damp_ratio)
        else:
            output = self.Spec_sp
        SIidx1 = np.argwhere(np.abs(self.Tsp - 0.1) <= 1E-8).item()
        SIidx2 = np.argwhere(np.abs(self.Tsp - 0.5) <= 1E-8).item()
        SIidx3 = np.argwhere(np.abs(self.Tsp - 2.5) <= 1E-8).item()
        SIidx4 = np.argwhere(np.abs(self.Tsp - 4.0) <= 1E-8).item()
        Sasp, Svsp, Sdsp = output[:, 2], output[:, 3], output[:, 4]
        ASI = trapz(Sasp[SIidx1:SIidx2], self.Tsp[SIidx1:SIidx2])
        VSI = trapz(Svsp[SIidx1:SIidx3], self.Tsp[SIidx1:SIidx3])
        DSI = trapz(Sdsp[SIidx3:SIidx4], self.Tsp[SIidx3:SIidx4])
        return np.array([ASI, VSI, DSI])
//  [python]
def get_avdsi(self,
                  damp_ratio: float = 0.05):
        """Acceleration (ASI)，Velocity (VSI) and Displacement(DSI) Spectrum Intensity.

        Parameters
        ----------
        damp_ratio : float, optional
            Damping ratio, by default 0.05.

        Returns
        -------
        AVD_SI: 1D ArrayLike
            Each element is in the order of acceleration, velocity and displacement.
        """
        if self.Tsp is None:
            output = self._spectrum_prefit(damp_ratio)
        else:
            output = self.Spec_sp
        SIidx1 = np.argwhere(np.abs(self.Tsp - 0.1) <= 1E-8).item()
        SIidx2 = np.argwhere(np.abs(self.Tsp - 0.5) <= 1E-8).item()
        SIidx3 = np.argwhere(np.abs(self.Tsp - 2.5) <= 1E-8).item()
        SIidx4 = np.argwhere(np.abs(self.Tsp - 4.0) <= 1E-8).item()
        Sasp, Svsp, Sdsp = output[:, 2], output[:, 3], output[:, 4]
        ASI = trapezoid(Sasp[SIidx1:SIidx2], self.Tsp[SIidx1:SIidx2])
        VSI = trapezoid(Svsp[SIidx1:SIidx3], self.Tsp[SIidx1:SIidx3])
        DSI = trapezoid(Sdsp[SIidx3:SIidx4], self.Tsp[SIidx3:SIidx4])
        return np.array([ASI, VSI, DSI])
//  [python]
def integrated_flux(wave, flambda, f_wave, f_throughput, exptime=15.0, eff_diam=670):
    """Integrates product of SED and filter throughput, and multiplies
    by typical LSST exposure time (in seconds) and collecting area
    (specified by effective diameter in cm) to estimate the number of
    photons collected by CCD.

    Units
    -----

    wave, f_wave : nm (corresponds to SED and filter resp.)
    flambda : erg/s/cm^2/Ang
    f_throughput : dimensionless
    exptime : seconds
    eff_diam : cm (effective diameter of aperture)
    """
    wave_union = numpy.union1d(wave, f_wave) #note union1d sorts its output
    flambda_i = numpy.interp(wave_union, wave, flambda)
    throughput_i = numpy.interp(wave_union, f_wave, f_throughput)

    hc = 1.98644521e-9 # (PlanckConstant * speedOfLight) in erg nm
    integrand = flambda_i * throughput_i * wave_union * 10 / hc
    photon_rate = scipy.integrate.trapz(integrand, wave_union)
    return photon_rate * numpy.pi * (eff_diam / 2)**2 * exptime
//  [python]
def integrated_flux(wave, flambda, f_wave, f_throughput, exptime=15.0, eff_diam=670):
    """Integrates product of SED and filter throughput, and multiplies
    by typical LSST exposure time (in seconds) and collecting area
    (specified by effective diameter in cm) to estimate the number of
    photons collected by CCD.

    Units
    -----

    wave, f_wave : nm (corresponds to SED and filter resp.)
    flambda : erg/s/cm^2/Ang
    f_throughput : dimensionless
    exptime : seconds
    eff_diam : cm (effective diameter of aperture)
    """
    wave_union = numpy.union1d(wave, f_wave) #note union1d sorts its output
    flambda_i = numpy.interp(wave_union, wave, flambda)
    throughput_i = numpy.interp(wave_union, f_wave, f_throughput)

    hc = 1.98644521e-9 # (PlanckConstant * speedOfLight) in erg nm
    integrand = flambda_i * throughput_i * wave_union * 10 / hc
    photon_rate = scipy.integrate.trapezoid(integrand, wave_union)
    return photon_rate * numpy.pi * (eff_diam / 2)**2 * exptime
//  [python]
def environment_signal_peak_area(self, env_window, scale, sig_window,
                                     edge, threshold, below_threshold=False):

        # obtain the signal
        signal = self.environment_signal(env_window, scale, sig_window, edge)

        # translate x-axis to threshold y-value
        translated_signal = signal - threshold

        # flip the signal around x-axis if below threshold is requested
        if(below_threshold):
            translated_signal = translated_signal * -1

        # clip negative values to 0
        peaks = translated_signal.clip(0.0)

        # obtain area under the curve using composite trapezoidal rule
        area = scipy.integrate.trapz(peaks)

        return area
//  [python]
def environment_signal_peak_area(self, env_window, scale, sig_window,
                                     edge, threshold, below_threshold=False):

        # obtain the signal
        signal = self.environment_signal(env_window, scale, sig_window, edge)

        # translate x-axis to threshold y-value
        translated_signal = signal - threshold

        # flip the signal around x-axis if below threshold is requested
        if(below_threshold):
            translated_signal = translated_signal * -1

        # clip negative values to 0
        peaks = translated_signal.clip(0.0)

        # obtain area under the curve using composite trapezoidal rule
        area = scipy.integrate.trapezoid(peaks)

        return area
//  [python]
def firstpassagetime_cdf(self, x0, A, *args, **kwargs):
        """
        Computes the CDF of the first passage time, :math:`Prob_{x0,t0}[\tau_A<t]`,
        or its derivatives, by solving the Fokker-Planck equation.
        """
        t0 = kwargs.pop('t0', 0.0)
        if 'P0' in kwargs:
            del kwargs['P0']
        if 'bc' not in kwargs:
            kwargs['bc'] = ('reflecting', 'absorbing')
        bnds = (kwargs.pop('bounds', (-10.0, 0.0))[0], A)
        time = np.sort([t0]+list(args))
        time = time[time >= t0]
        G = [1.0 if x0 < A else 0.0]
        fpe = fp.FokkerPlanck1D.from_sde(self.model)
        P0 = fpe.dirac1d(x0, np.linspace(bnds[0], bnds[1], num=kwargs.get('npts', 100)))
        t, X, P = fpe.fpintegrate(t0, 0.0, P0=P0, bounds=bnds, **kwargs)
        for t in time[1:]:
            t, X, P = fpe.fpintegrate(t0, t-t0, P0=P, bounds=bnds, **kwargs)
            G += [integrate.trapz(P[X < A], X[X < A])]
            t0 = t
        G = np.array(G)
        output = {'cdf': (time, 1.0-G), 'G': (time, G),
                  'pdf': (time[1:-1], -edpy.CenteredFD(time).grad(G)),
                  'lambda': (time[1:-1], -edpy.CenteredFD(time).grad(np.log(G)))}
        return output.get(kwargs.get('out', 'G'))
//  [python]
def firstpassagetime_cdf(self, x0, A, *args, **kwargs):
        """
        Computes the CDF of the first passage time, :math:`Prob_{x0,t0}[\tau_A<t]`,
        or its derivatives, by solving the Fokker-Planck equation.
        """
        t0 = kwargs.pop('t0', 0.0)
        if 'P0' in kwargs:
            del kwargs['P0']
        if 'bc' not in kwargs:
            kwargs['bc'] = ('reflecting', 'absorbing')
        bnds = (kwargs.pop('bounds', (-10.0, 0.0))[0], A)
        time = np.sort([t0]+list(args))
        time = time[time >= t0]
        G = [1.0 if x0 < A else 0.0]
        fpe = fp.FokkerPlanck1D.from_sde(self.model)
        P0 = fpe.dirac1d(x0, np.linspace(bnds[0], bnds[1], num=kwargs.get('npts', 100)))
        t, X, P = fpe.fpintegrate(t0, 0.0, P0=P0, bounds=bnds, **kwargs)
        for t in time[1:]:
            t, X, P = fpe.fpintegrate(t0, t-t0, P0=P, bounds=bnds, **kwargs)
            G += [integrate.trapezoid(P[X < A], X[X < A])]
            t0 = t
        G = np.array(G)
        output = {'cdf': (time, 1.0-G), 'G': (time, G),
                  'pdf': (time[1:-1], -edpy.CenteredFD(time).grad(G)),
                  'lambda': (time[1:-1], -edpy.CenteredFD(time).grad(np.log(G)))}
        return output.get(kwargs.get('out', 'G'))
//  [python]
def firstpassagetime_avg_theory(self, x0, *args, **kwargs):
        r"""
        Compute the mean first-passage time using the theoretical formula:

        :math:`\mathbb{E}[\tau_M] = \frac{1}{D} \int_{x_0}^{M} dx e^{V(x)/D} \int_{-\infty}^x e^{-V(y)/D}dy.`

        This formula is valid for a homogeneous process, conditioned on the initial position :math:`x_0`.

        Parameters
        ----------
        x0 : float
            Initial position
        """
        t0 = kwargs.pop('t0', 0.0)
        inf = kwargs.pop('inf', -10.0)
        # args have to be sorted in increasing order:
        args = np.sort(args)
        # remove the values of args which are <= x0:
        badargs, args = (args[args <= x0], args[args > x0])

        def exppot_int(a, b, sign=-1, fun=lambda z: 1):
            z = np.linspace(a, b, **kwargs)
            return integrate.trapz(np.exp(sign*self.model.potential(z, t0)/self.model.D0)*fun(z), z)
        # compute the inner integral and interpolate:
        y = np.linspace(x0, args[-1], **kwargs)
        arr = np.array([exppot_int(*u) for u in [(inf, y[0])]+list(zip(y[:-1], y[1:]))])
        ifun = interp1d(y, arr.cumsum(), fill_value='extrapolate')
        # now compute the outer integral by chunks
        oint = np.array([exppot_int(*bds, sign=1, fun=ifun) for bds in [(x0, args[0])]+list(zip(args[:-1], args[1:]))]).cumsum()/self.model.D0
        return np.concatenate((badargs, args)), np.concatenate((np.zeros_like(badargs), oint))
//  [python]
def firstpassagetime_avg_theory(self, x0, *args, **kwargs):
        r"""
        Compute the mean first-passage time using the theoretical formula:

        :math:`\mathbb{E}[\tau_M] = \frac{1}{D} \int_{x_0}^{M} dx e^{V(x)/D} \int_{-\infty}^x e^{-V(y)/D}dy.`

        This formula is valid for a homogeneous process, conditioned on the initial position :math:`x_0`.

        Parameters
        ----------
        x0 : float
            Initial position
        """
        t0 = kwargs.pop('t0', 0.0)
        inf = kwargs.pop('inf', -10.0)
        # args have to be sorted in increasing order:
        args = np.sort(args)
        # remove the values of args which are <= x0:
        badargs, args = (args[args <= x0], args[args > x0])

        def exppot_int(a, b, sign=-1, fun=lambda z: 1):
            z = np.linspace(a, b, **kwargs)
            return integrate.trapezoid(np.exp(sign*self.model.potential(z, t0)/self.model.D0)*fun(z), z)
        # compute the inner integral and interpolate:
        y = np.linspace(x0, args[-1], **kwargs)
        arr = np.array([exppot_int(*u) for u in [(inf, y[0])]+list(zip(y[:-1], y[1:]))])
        ifun = interp1d(y, arr.cumsum(), fill_value='extrapolate')
        # now compute the outer integral by chunks
        oint = np.array([exppot_int(*bds, sign=1, fun=ifun) for bds in [(x0, args[0])]+list(zip(args[:-1], args[1:]))]).cumsum()/self.model.D0
        return np.concatenate((badargs, args)), np.concatenate((np.zeros_like(badargs), oint))
//  [python]
def FindDs(GMData, Dt, min=.05, max=0.95):
    import numpy as np
    from scipy.integrate import trapz
    T = np.array(list(range(0,len(GMData))))*Dt
    Total = trapz(np.array(GMData)**2,dx=Dt)
    Ds = []
    mini = None
    maxi = None
    for i in range(0,len(GMData)):
        Ds.append(trapz(GMData[0:i]**2,dx=Dt)/Total)
        if min < Ds[i] and min > Ds[i-1]:
            mini = i
        if max < Ds[i] and max > Ds[i-1]:
            maxi = i
    DsMinMax = T[maxi]-T[mini]
    Ds = np.array(Ds)

    class Output:
        def __init__(self):
            self.Ds = DsMinMax
            self.MaxIndex = maxi
            self.MinIndex = mini

    O = Output()

    return DsMinMax
//  [python]
def FindDs(GMData, Dt, min=.05, max=0.95):
    import numpy as np
    from scipy.integrate import trapezoid
    T = np.array(list(range(0,len(GMData))))*Dt
    Total = trapezoid(np.array(GMData)**2,dx=Dt)
    Ds = []
    mini = None
    maxi = None
    for i in range(0,len(GMData)):
        Ds.append(trapezoid(GMData[0:i]**2,dx=Dt)/Total)
        if min < Ds[i] and min > Ds[i-1]:
            mini = i
        if max < Ds[i] and max > Ds[i-1]:
            maxi = i
    DsMinMax = T[maxi]-T[mini]
    Ds = np.array(Ds)

    class Output:
        def __init__(self):
            self.Ds = DsMinMax
            self.MaxIndex = maxi
            self.MinIndex = mini

    O = Output()

    return DsMinMax
//  [python]
def FindDsFromGMid(GMFolder, GMid, min=.05, max=0.95):
    Dt, NumPoints, GMData = ExtractOneGroundMotion(GMFolder, GMid)

    import numpy as np
    from scipy.integrate import trapz
    T = np.array(list(range(0,len(GMData))))*Dt
    Total = trapz(np.array(GMData)**2,dx=Dt)
    Ds = []
    mini = None
    maxi = None
    for i in range(0,len(GMData)):
        Ds.append(trapz(GMData[0:i]**2,dx=Dt)/Total)
        if min < Ds[i] and min > Ds[i-1]:
            mini = i
        if max < Ds[i] and max > Ds[i-1]:
            maxi = i
    DsMinMax = T[maxi]-T[mini]
    Ds = np.array(Ds)

    class Output:
        def __init__(self):
            self.Ds = DsMinMax
            self.MaxIndex = maxi
            self.MinIndex = mini

    O = Output()

    return DsMinMax
//  [python]
def FindDsFromGMid(GMFolder, GMid, min=.05, max=0.95):
    Dt, NumPoints, GMData = ExtractOneGroundMotion(GMFolder, GMid)

    import numpy as np
    from scipy.integrate import trapezoid
    T = np.array(list(range(0,len(GMData))))*Dt
    Total = trapezoid(np.array(GMData)**2,dx=Dt)
    Ds = []
    mini = None
    maxi = None
    for i in range(0,len(GMData)):
        Ds.append(trapezoid(GMData[0:i]**2,dx=Dt)/Total)
        if min < Ds[i] and min > Ds[i-1]:
            mini = i
        if max < Ds[i] and max > Ds[i-1]:
            maxi = i
    DsMinMax = T[maxi]-T[mini]
    Ds = np.array(Ds)

    class Output:
        def __init__(self):
            self.Ds = DsMinMax
            self.MaxIndex = maxi
            self.MinIndex = mini

    O = Output()

    return DsMinMax
//  [python]
def GetSS(GMData, Dt, Zeta, T1, T2, dt=0.01):
    import numpy as np
    Sas = []
    T = np.arange(T1,T2+dt,dt)
    for t in T:
        SD, SV, SA = FindSa(GMData, Dt, t, Zeta)
        Sas.append(SA)

    import scipy.integrate as scipyint
    SS = scipyint.trapz(Sas, T)
    SS = SS/(Sas[0]*(T2-T1))
    return SS
//  [python]
def GetSS(GMData, Dt, Zeta, T1, T2, dt=0.01):
    import numpy as np
    Sas = []
    T = np.arange(T1,T2+dt,dt)
    for t in T:
        SD, SV, SA = FindSa(GMData, Dt, t, Zeta)
        Sas.append(SA)

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(Sas, T)
    SS = SS/(Sas[0]*(T2-T1))
    return SS
//  [python]
def GetDs(GMData, Dt, min=.05, max=0.95):
    import numpy as np
    from scipy.integrate import trapz
    T = np.array(list(range(0,len(GMData))))*Dt
    Total = trapz(np.array(GMData)**2,dx=Dt)
    Ds = []
    mini = None
    maxi = None
    for i in range(0,len(GMData)):
        Ds.append(trapz(GMData[0:i]**2,dx=Dt)/Total)
        if min < Ds[i] and min > Ds[i-1]:
            mini = i
        if max < Ds[i] and max > Ds[i-1]:
            maxi = i
    DsMinMax = T[maxi]-T[mini]
    Ds = np.array(Ds)

    class Output:
        def __init__(self):
            self.Ds = DsMinMax
            self.MaxIndex = maxi
            self.MinIndex = mini

    O = Output()

    return O
//  [python]
def GetDs(GMData, Dt, min=.05, max=0.95):
    import numpy as np
    from scipy.integrate import trapezoid
    T = np.array(list(range(0,len(GMData))))*Dt
    Total = trapezoid(np.array(GMData)**2,dx=Dt)
    Ds = []
    mini = None
    maxi = None
    for i in range(0,len(GMData)):
        Ds.append(trapezoid(GMData[0:i]**2,dx=Dt)/Total)
        if min < Ds[i] and min > Ds[i-1]:
            mini = i
        if max < Ds[i] and max > Ds[i-1]:
            maxi = i
    DsMinMax = T[maxi]-T[mini]
    Ds = np.array(Ds)

    class Output:
        def __init__(self):
            self.Ds = DsMinMax
            self.MaxIndex = maxi
            self.MinIndex = mini

    O = Output()

    return O
//  [python]
def rf_quality(rfdata, delta, f0, tshift=0):
    """
    Calculate receiver function quality metric using the algorithm outlined in Burky et al. 2019

    :param rfdata: Array containing receiver function data
    :param delta: Sampling interval of receiver function data
    :param f0: Gaussian width factor used in iterative time domain deconvolution
    :param tshift: Time shift of receiver function in seconds (DEFAULT = 0)

    :return: quality: Float in [0, 1] representing the quality of receiver function data
    """
    # OLD METHOD
    # Take derivative of data
    # drf = np.diff(rfdata/delta)
    # pks = scipy.signal.find_peaks(rfdata[0:eidx], height=0)
    # Use start of receiver function (index 0) instead of finding idx1

    # NEW METHOD
    # Find largest peak in window from start time to time-shift plus 3 standard deviations
    if tshift != 0:
        bidx = int(round((tshift-(3/f0))/delta))
        eidx = int(round((tshift+(3/f0))/delta))
        p_int = scipy.integrate.trapz(np.abs(rfdata[bidx:eidx]), dx=delta)
    else:
        eidx = int(round((tshift+(3/f0))/delta))
        # Integral of initial gaussian pulse (P arrival)
        p_int = scipy.integrate.trapz(np.abs(rfdata[0:eidx]), dx=delta)
    # Integral of entire receiver function
    rf_int = scipy.integrate.trapz(np.abs(rfdata), dx=delta)
    # Ratio of integrals
    quality = p_int/rf_int
    # Check for negative first impulse
    p_sign = scipy.integrate.trapz(rfdata[0:eidx], dx=delta)
    if p_sign < 0:
        quality = -1*quality
    return quality
//  [python]
def rf_quality(rfdata, delta, f0, tshift=0):
    """
    Calculate receiver function quality metric using the algorithm outlined in Burky et al. 2019

    :param rfdata: Array containing receiver function data
    :param delta: Sampling interval of receiver function data
    :param f0: Gaussian width factor used in iterative time domain deconvolution
    :param tshift: Time shift of receiver function in seconds (DEFAULT = 0)

    :return: quality: Float in [0, 1] representing the quality of receiver function data
    """
    # OLD METHOD
    # Take derivative of data
    # drf = np.diff(rfdata/delta)
    # pks = scipy.signal.find_peaks(rfdata[0:eidx], height=0)
    # Use start of receiver function (index 0) instead of finding idx1

    # NEW METHOD
    # Find largest peak in window from start time to time-shift plus 3 standard deviations
    if tshift != 0:
        bidx = int(round((tshift-(3/f0))/delta))
        eidx = int(round((tshift+(3/f0))/delta))
        p_int = scipy.integrate.trapezoid(np.abs(rfdata[bidx:eidx]), dx=delta)
    else:
        eidx = int(round((tshift+(3/f0))/delta))
        # Integral of initial gaussian pulse (P arrival)
        p_int = scipy.integrate.trapezoid(np.abs(rfdata[0:eidx]), dx=delta)
    # Integral of entire receiver function
    rf_int = scipy.integrate.trapezoid(np.abs(rfdata), dx=delta)
    # Ratio of integrals
    quality = p_int/rf_int
    # Check for negative first impulse
    p_sign = scipy.integrate.trapezoid(rfdata[0:eidx], dx=delta)
    if p_sign < 0:
        quality = -1*quality
    return quality
//  [python]
def ComputeSSa(ResponseSpectrumPeriods, ResponseSpectrumSa, T1, T2):
    Sas = []
    T = []
    for i in range(len(ResponseSpectrumPeriods)):
        if T1 <= ResponseSpectrumPeriods[i] and T2 >= ResponseSpectrumPeriods[i]:
            T.append(ResponseSpectrumPeriods[i])
            Sas.append(ResponseSpectrumSa[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapz(Sas, T)
    if Sas[0]*(T2-T1) == 0.:
        SS = 1.
    else:
        SS = SS/(Sas[0]*(T2-T1))

    return SS
//  [python]
def ComputeSSa(ResponseSpectrumPeriods, ResponseSpectrumSa, T1, T2):
    Sas = []
    T = []
    for i in range(len(ResponseSpectrumPeriods)):
        if T1 <= ResponseSpectrumPeriods[i] and T2 >= ResponseSpectrumPeriods[i]:
            T.append(ResponseSpectrumPeriods[i])
            Sas.append(ResponseSpectrumSa[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(Sas, T)
    if Sas[0]*(T2-T1) == 0.:
        SS = 1.
    else:
        SS = SS/(Sas[0]*(T2-T1))

    return SS
//  [python]
def ComputeSSaVer2(ResponseSpectrumPeriods, ResponseSpectrumSa, T1, T2):

    import numpy as np
    dt = ResponseSpectrumPeriods[1]-ResponseSpectrumPeriods[0]
    T2 = min(np.max(ResponseSpectrumPeriods),T2)

    T = np.arange(T1,T2+dt,dt)
    Sas = np.interp(T, ResponseSpectrumPeriods, ResponseSpectrumSa)

    import scipy.integrate as scipyint
    SS = scipyint.trapz(Sas, T)
    SS = SS/(Sas[0]*(T2-T1))

    return SS
//  [python]
def ComputeSSaVer2(ResponseSpectrumPeriods, ResponseSpectrumSa, T1, T2):

    import numpy as np
    dt = ResponseSpectrumPeriods[1]-ResponseSpectrumPeriods[0]
    T2 = min(np.max(ResponseSpectrumPeriods),T2)

    T = np.arange(T1,T2+dt,dt)
    Sas = np.interp(T, ResponseSpectrumPeriods, ResponseSpectrumSa)

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(Sas, T)
    SS = SS/(Sas[0]*(T2-T1))

    return SS
//  [python]
def ComputeSaSSa(ResponseSpectrumPeriods, ResponseSpectrumSa, T1, T2):
    Sas = []
    T = []
    for i in range(len(ResponseSpectrumPeriods)):
        if T1 <= ResponseSpectrumPeriods[i] and T2 >= ResponseSpectrumPeriods[i]:
            T.append(ResponseSpectrumPeriods[i])
            Sas.append(ResponseSpectrumSa[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapz(Sas, T)
    if Sas[0]*(T2-T1) == 0.:
        SS = 1.
    else:
        SS = SS/(Sas[0]*(T2-T1))

    return SS*Sas[0]
//  [python]
def ComputeSaSSa(ResponseSpectrumPeriods, ResponseSpectrumSa, T1, T2):
    Sas = []
    T = []
    for i in range(len(ResponseSpectrumPeriods)):
        if T1 <= ResponseSpectrumPeriods[i] and T2 >= ResponseSpectrumPeriods[i]:
            T.append(ResponseSpectrumPeriods[i])
            Sas.append(ResponseSpectrumSa[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(Sas, T)
    if Sas[0]*(T2-T1) == 0.:
        SS = 1.
    else:
        SS = SS/(Sas[0]*(T2-T1))

    return SS*Sas[0]
//  [python]
def ComputeSSaFromGMid(GMFolder, GMid, T1, T2):
    O = GetResponseSpectrumDataPoints(GMFolder, GMid)
    ResponseSpectrumPeriods = O.Period
    ResponseSpectrumSa = O.Sa
    Sas = []
    T = []
    for i in range(len(ResponseSpectrumPeriods)):
        if T1 <= ResponseSpectrumPeriods[i] and T2 >= ResponseSpectrumPeriods[i]:
            T.append(ResponseSpectrumPeriods[i])
            Sas.append(ResponseSpectrumSa[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapz(Sas, T)
    SS = SS/(Sas[0]*(T2-T1))

    return SS
//  [python]
def ComputeSSaFromGMid(GMFolder, GMid, T1, T2):
    O = GetResponseSpectrumDataPoints(GMFolder, GMid)
    ResponseSpectrumPeriods = O.Period
    ResponseSpectrumSa = O.Sa
    Sas = []
    T = []
    for i in range(len(ResponseSpectrumPeriods)):
        if T1 <= ResponseSpectrumPeriods[i] and T2 >= ResponseSpectrumPeriods[i]:
            T.append(ResponseSpectrumPeriods[i])
            Sas.append(ResponseSpectrumSa[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(Sas, T)
    SS = SS/(Sas[0]*(T2-T1))

    return SS
//  [python]
def ComputeSSaFromGMDataQuick(GMData, Dt, T1, T2, SaDt = 0.01):
    import numpy as np
    ResponseSpectrumPeriods = np.arange(T1, T2+SaDt, SaDt)

    ResponseSpectrumSa = []
    Zeta = 0.05
    for t1 in ResponseSpectrumPeriods:
        SD, SV, SA = FindSa(GMData, Dt, t1, Zeta)
        ResponseSpectrumSa.append(SA)

    T = ResponseSpectrumPeriods
    Sas = ResponseSpectrumSa

    import scipy.integrate as scipyint
    SS = scipyint.trapz(Sas, T)
    SS = SS / (Sas[0] * (T2 - T1))

    return SS
//  [python]
def ComputeSSaFromGMDataQuick(GMData, Dt, T1, T2, SaDt = 0.01):
    import numpy as np
    ResponseSpectrumPeriods = np.arange(T1, T2+SaDt, SaDt)

    ResponseSpectrumSa = []
    Zeta = 0.05
    for t1 in ResponseSpectrumPeriods:
        SD, SV, SA = FindSa(GMData, Dt, t1, Zeta)
        ResponseSpectrumSa.append(SA)

    T = ResponseSpectrumPeriods
    Sas = ResponseSpectrumSa

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(Sas, T)
    SS = SS / (Sas[0] * (T2 - T1))

    return SS
//  [python]
def ComputeSSaFromGMidQuick(GMFolder, GMid, T1, T2):
    O = GetResponseSpectrumDataPointsQuick(GMFolder, GMid)
    ResponseSpectrumPeriods = O.Period
    ResponseSpectrumSa = O.Sa

    import numpy as np
    dt = ResponseSpectrumPeriods[1] - ResponseSpectrumPeriods[0]
    T2 = min(np.max(ResponseSpectrumPeriods), T2)

    T = np.arange(T1, T2 + dt, dt)
    Sas = np.interp(T, ResponseSpectrumPeriods, ResponseSpectrumSa)

    import scipy.integrate as scipyint
    SS = scipyint.trapz(Sas, T)
    SS = SS / (Sas[0] * (T2 - T1))

    return SS
//  [python]
def ComputeSSaFromGMidQuick(GMFolder, GMid, T1, T2):
    O = GetResponseSpectrumDataPointsQuick(GMFolder, GMid)
    ResponseSpectrumPeriods = O.Period
    ResponseSpectrumSa = O.Sa

    import numpy as np
    dt = ResponseSpectrumPeriods[1] - ResponseSpectrumPeriods[0]
    T2 = min(np.max(ResponseSpectrumPeriods), T2)

    T = np.arange(T1, T2 + dt, dt)
    Sas = np.interp(T, ResponseSpectrumPeriods, ResponseSpectrumSa)

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(Sas, T)
    SS = SS / (Sas[0] * (T2 - T1))

    return SS
//  [python]
def GetSSThroughSprectrum(Folder_Location, GMid, T1, T2):
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    AccTemp = []

    if T1 == T2:
        return 0.0

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            AccTemp.append(Acc[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapz(AccTemp, PeriodTemp)
    SS = SS/(AccTemp[0]*(T2-T1))

    return SS
//  [python]
def GetSSThroughSprectrum(Folder_Location, GMid, T1, T2):
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    AccTemp = []

    if T1 == T2:
        return 0.0

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            AccTemp.append(Acc[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(AccTemp, PeriodTemp)
    SS = SS/(AccTemp[0]*(T2-T1))

    return SS
//  [python]
def MethodNameGotDeleted(Folder_Location, GMid, T1, T2, Tnorm):
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    AccTemp = []

    if T1 == T2:
        return 0.0

    import numpy as np

    SaNorm = np.interp(Tnorm,Period,Acc)

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            AccTemp.append(Acc[i])



    import scipy.integrate as scipyint
    SS = scipyint.trapz(AccTemp, PeriodTemp)
    SS = SS/(SaNorm*(T2-T1))

    return SS
//  [python]
def MethodNameGotDeleted(Folder_Location, GMid, T1, T2, Tnorm):
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    AccTemp = []

    if T1 == T2:
        return 0.0

    import numpy as np

    SaNorm = np.interp(Tnorm,Period,Acc)

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            AccTemp.append(Acc[i])



    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(AccTemp, PeriodTemp)
    SS = SS/(SaNorm*(T2-T1))

    return SS
//  [python]
def GetSSLogLogThroughSprectrum(Folder_Location, GMid, T1, T2):
    import numpy as np
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    AccTemp = []

    if T1 == T2:
        return 0.0

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            AccTemp.append(Acc[i])

    PeriodTemp = np.log(PeriodTemp)
    AccTemp = np.log(AccTemp)

    import scipy.integrate as scipyint
    SS = scipyint.trapz(AccTemp, PeriodTemp)
    SS = SS/(AccTemp[0]*(T2-T1))

    return SS
//  [python]
def GetSSLogLogThroughSprectrum(Folder_Location, GMid, T1, T2):
    import numpy as np
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    AccTemp = []

    if T1 == T2:
        return 0.0

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            AccTemp.append(Acc[i])

    PeriodTemp = np.log(PeriodTemp)
    AccTemp = np.log(AccTemp)

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(AccTemp, PeriodTemp)
    SS = SS/(AccTemp[0]*(T2-T1))

    return SS
//  [python]
def GetSSDSemiLogThroughSprectrum(Folder_Location, GMid, T1, T2):
    import numpy as np
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    DispTemp = []

    if T1 == T2:
        return 0.0

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            DispTemp.append(Disp[i])

    PeriodTemp = np.log(PeriodTemp)

    import scipy.integrate as scipyint
    SS = scipyint.trapz(DispTemp, PeriodTemp)
    SS = SS/(DispTemp[0]*(T2-T1))

    return SS
//  [python]
def GetSSDSemiLogThroughSprectrum(Folder_Location, GMid, T1, T2):
    import numpy as np
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    DispTemp = []

    if T1 == T2:
        return 0.0

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            DispTemp.append(Disp[i])

    PeriodTemp = np.log(PeriodTemp)

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(DispTemp, PeriodTemp)
    SS = SS/(DispTemp[0]*(T2-T1))

    return SS
//  [python]
def GetSSVThroughVelocitySprectrum(Folder_Location, GMid, T1, T2):
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    VelTemp = []

    if T1 == T2:
        return 0.0

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            VelTemp.append(Vel[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapz(VelTemp, PeriodTemp)
    SS = SS/(VelTemp[0]*(T2-T1))

    return SS
//  [python]
def GetSSVThroughVelocitySprectrum(Folder_Location, GMid, T1, T2):
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    VelTemp = []

    if T1 == T2:
        return 0.0

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            VelTemp.append(Vel[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(VelTemp, PeriodTemp)
    SS = SS/(VelTemp[0]*(T2-T1))

    return SS
//  [python]
def GetSSDThroughDisplacementSprectrum(Folder_Location, GMid, T1, T2):
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    DispTemp = []

    if T1 == T2:
        return 0.0

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            DispTemp.append(Disp[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapz(DispTemp, PeriodTemp)
    SS = SS/(DispTemp[0]*(T2-T1))

    return SS
//  [python]
def GetSSDThroughDisplacementSprectrum(Folder_Location, GMid, T1, T2):
    O = GetResponseSpectrumDataPoints(Folder_Location,GMid)
    Period = O.Period
    Acc = O.Sa
    Vel = O.Sv
    Disp = O.Sd

    PeriodTemp = []
    DispTemp = []

    if T1 == T2:
        return 0.0

    for i in range(len(Period)):
        if Period[i] <= T2 and Period[i] >= T1:
            PeriodTemp.append(Period[i])
            DispTemp.append(Disp[i])

    import scipy.integrate as scipyint
    SS = scipyint.trapezoid(DispTemp, PeriodTemp)
    SS = SS/(DispTemp[0]*(T2-T1))

    return SS
//  [python]
def computeIncTheta(self, x0, x1, M):
        ''' Compute increment of rotation between x0 and x1.

        :param x0: interval beginning.
        :param x1: interval end.
        :param M: bending moment function.
        '''
        x= self.samplePoints(x0= x0, x1= x1)
        y= self.computeCurvature(xi= x, M=M)
        return scipy.integrate.trapz(y, x)