Exemple #1
0
def pdf_to_quantile(f,precision=0.00001):
    def tmp(x):
        return x*f(x)
    mn=integ(tmp,-10000,10000)[0]
    val=integ(f,-10000,mn)[0]
    max_iter=100
    def quantile(x,precision=precision):
        cur=mn
        quant=val
        incr=0
        while (abs(quant-x)>precision)&(incr<max_iter):
            past_cur=cur
            cur=(x-quant)/f(past_cur)+cur
            quant=quant+(integ(f,past_cur,cur)[0])
            incr+=1

        quant=integ(f,-10000,cur)[0]

        while (abs(quant-x)>precision)&(incr<max_iter):
            past_cur=cur
            cur=(x-quant)/f(past_cur)+cur
            quant=quant+integ(f,past_cur,cur)[0]
            incr+=1

        print('nb iteration; %d, quantile: %f'%(incr,quant))
        return float(cur)
    return quantile
Exemple #2
0
def main(lamm,flum,lamt,flut):
 	
 ##---------------------------------------------------------
 #Import packages
 import os
 #from scipy.interpolate import splprep, splev
 from scipy.interpolate import interp1d
 from scipy.integrate import trapz as  integ
 from numpy import loadtxt, arange #,pi, log, linspace, convolve
 
 ##---------------------------------------------------------

 ## define lambda vector = the same as transmission lambda
 ln=len(lamt)
 #-----------------------------------------------------------
 ## interpolate transmisison to cover same lambda intervals
 ## interpolate model to cover same lambda intervals
 ## Create interpolating function 
 #tti=interp1d(lamt,flut)
 mmi=interp1d(lamm,flum)
 
 moint=[]
 trint=[]
 for i in lamt:
 	moint.append(float(mmi(i))) 
 		
 ## length must be the same
 print 'length of interpolated model is ', len(moint)
 print 'length of transmission file is', len(lamt)
 
 print 'COMPUTE INTEGRAL'
 
 # filter characteristics:
 ltr=flut*lamt
 tint = integ(flut,lamt) # surface
 lef = integ(ltr,lamt) /tint # effective wavelength
 delta=flut*((lamt-lef)**2)
 dint = 2*(integ(delta,lamt) /tint)**(0.5)  # whole bandpass
 
 # Compute flux averaged in the transmission :
 ymt=moint*flut       
 imt = integ(ymt,lamt)  
 #flav=1
 flav=imt/tint# averaged flux
  
 # result
 res=[0*x for x in range (0,3)]
 res[0]=lef
 res[1]=dint
 res[2]=flav
 
 return res
Exemple #3
0
def extract_coefs(
    _x: np.ndarray,
    signal: np.ndarray,
    nb: int = 1,
    act: int = None,
    plot: bool = True,
    graph_len: int = 200,
):
    if plot:
        fig, ax = plt.subplots()
        ax.plot(signal[:graph_len], "+")
    if act is None:
        act = 1
    freqs: list = []
    amps: list = []
    for n in range(nb):
        freqs.append(signal.argmax() / end)
        mi = int(signal.argmax() - act)
        if mi < 0:
            mi = 0
        ma = int(signal.argmax() + act + 1)
        amps.append(integ(signal[mi:ma], _x[mi:ma]))
        signal[mi:ma] = np.zeros(ma - mi)
        if plot:
            ax.plot(signal[:graph_len])
    if plot:
        fig.show()
    return amps, freqs
Exemple #4
0
    def quantile(x,precision=precision):
        cur=mn
        quant=val
        incr=0
        while (abs(quant-x)>precision)&(incr<max_iter):
            past_cur=cur
            cur=(x-quant)/f(past_cur)+cur
            quant=quant+(integ(f,past_cur,cur)[0])
            incr+=1

        quant=integ(f,-10000,cur)[0]

        while (abs(quant-x)>precision)&(incr<max_iter):
            past_cur=cur
            cur=(x-quant)/f(past_cur)+cur
            quant=quant+integ(f,past_cur,cur)[0]
            incr+=1

        print('nb iteration; %d, quantile: %f'%(incr,quant))
        return float(cur)
Exemple #5
0
def trasm(lamt,flut):
 ##---------------------------------------------------------
 #Import packages
 import os
 #from scipy.interpolate import splprep, splev
 from scipy.interpolate import interp1d
 from scipy.integrate import trapz as  integ
 from numpy import loadtxt, arange #,pi, log, linspace, convolve
 
 
 ln=len(lamt)
 # filter characteristics:
 ltr=flut*lamt
 tint = integ(flut,lamt) # surface
 lef = integ(ltr,lamt) /tint # effective wavelength
 delta=flut*((lamt-lef)**2)
 dint = 2*(integ(delta,lamt) /tint)**(0.5)  # whole bandpass
 # result
 res=[0*x for x in range (0,3)]
 res[0]=lef
 res[1]=dint
 res[2]=tint
 return res
Exemple #6
0
    def calculate_pvalue_gev(original_score: float, scores: list) -> float:
        """Calculates a p-value to a target/query combination by int. with a given amount of shuffle iterations by
        fitting a generalized extreme value distribution and integrating from -inf to the original score

        >>> i = IntaRNApvalue(['-q', 'AGGAUG', '-t', 'UUUAUCGUU', '--scores', '10', '-m', 'b', '--threads', '3'])
        >>> i.calculate_pvalue_gev(-10.0, [-1.235, -1.435645, -6.234234, -12.999, -15.23, -6.98, -6.23, -2.78])
        0.17611816922560236
        """
        shape, loc, scale = gev.fit(scores)

        def f(x):
            return gev.pdf(x, shape, loc=loc, scale=scale)

        return integ(f, -np.inf, original_score)[0]
Exemple #7
0
    def calculate_pvalue_gumbel(original_score: float, scores: list) -> float:
        """Calculates a p-value to a target/query combination by int. with a given amount of shuffle iterations by
        fitting a gumbel distribution and integrating from -inf to the original score

        >>> i = IntaRNApvalue(['-q', 'AGGAUG', '-t', 'UUUAUCGUU', '--scores', '10', '-m', 'b', '--threads', '3'])
        >>> i.calculate_pvalue_gumbel(-10.0, [-1.235, -1.435645, -6.234234, -12.999, -15.23, -6.98, -6.23, -2.78])
        0.19721934073203196
        """
        loc, scale = gum.fit(scores)

        def f(x):
            return gum.pdf(x, loc=loc, scale=scale)

        return integ(f, -np.inf, original_score)[0]
Exemple #8
0
def ext_grf_steady(
    rad,
    r_ref,
    conductivity,
    dim=2,
    lat_ext=1.0,
    rate=-1e-4,
    h_ref=0.0,
    arg_dict=None,
    **kwargs
):
    """
    The extended "General radial flow" model for steady flow.

    The general radial flow (GRF) model by Barker introduces an arbitrary
    dimension for radial groundwater flow. We introduced the possibility to
    define radial dependet conductivity.

    This solution is based on the grf model presented in [Barker88]_.

    Parameters
    ----------
    rad : :class:`numpy.ndarray`
        Array with all radii where the function should be evaluated
    r_ref : :class:`float`
        Radius of the reference head.
    conductivity : :class:`float` or :any:`callable`
        Conductivity. Either callable function taking kwargs or float.
    dim : :class:`float`, optional
        Fractional dimension of the aquifer. Default: ``2.0``
    lat_ext : :class:`float`, optional
        Lateral extend of the aquifer. Default: ``1.0``
    rate : :class:`float`, optional
        Pumpingrate at the well. Default: -1e-4
    h_ref : :class:`float`, optional
        Reference head at the reference-radius `r_ref`. Default: ``0.0``
    arg_dict : :class:`dict` or :any:`None`, optional
        Keyword-arguments given as a dictionary that are forwarded to the
        conductivity function. Will be merged with ``**kwargs``.
        This is designed for overlapping keywords in ``grf_steady`` and
        ``conductivity``.
        Default: ``None``
    **kwargs
        Keyword-arguments that are forwarded to the conductivity function.
        Will be merged with ``arg_dict``

    Returns
    -------
    :class:`numpy.ndarray`
        Array with all heads at the given radii and time-points.

    References
    ----------
    .. [Barker88] Barker, J.
       ''A generalized radial flow model for hydraulic tests
       in fractured rock.'',
       Water Resources Research 24.10, 1796-1804, 1988
    """
    arg_dict = {} if arg_dict is None else arg_dict
    kwargs.update(arg_dict)
    Input = Shaper(rad=rad)
    q_fac = rate / (sph_surf(dim) * lat_ext ** (3.0 - dim))  # pumping factor
    if not r_ref > 0.0:
        raise ValueError("The reference radius needs to be positive.")
    if not Input.rad_min > 0.0:
        raise ValueError("The given radii need to be positive.")
    if not dim > 0.0 or dim > 3.0:
        raise ValueError("The dimension needs to be positiv and <= 3.")
    if not lat_ext > 0.0:
        raise ValueError("The lateral extend needs to be positiv.")

    if callable(conductivity):
        res = np.zeros(Input.rad_no)

        def integrand(val):
            """Integrand."""
            return val ** (1 - dim) / conductivity(val, **kwargs)

        for ri, re in enumerate(Input.rad):
            res[ri] = integ(integrand, re, r_ref)[0]
    else:
        con = float(conductivity)
        if not con > 0:
            raise ValueError("The Conductivity needs to be positive.")
        if np.isclose(dim, 2):
            res = np.log(r_ref / Input.rad) / con
        else:
            res = (
                (r_ref ** (2 - dim) - Input.rad ** (2 - dim)) / (2 - dim) / con
            )

    res = Input.reshape(res)
    # rescale by pumping rate
    res *= q_fac
    # add the reference head
    res += h_ref
    return res
Exemple #9
0
 def res(y):
     def g(x,y=y):
         return cost(y-x)*density(x)
     # ut.curve(g,inter=[-10,10])
     return integ(g,-10,10)[0]
Exemple #10
0
 def Compute(self):
     if self.log_active:
         print(
             '===========================================================')
         print('SOLVER INSIDE THE STAR')
         print(
             '===========================================================\n'
         )
         print('Initial density: ', self.initDensity, ' MeV/fm^3')
         print('Initial pressure: ', self.initPressure / 10**12, ' GPa')
         print('Initial mass: ', self.initMass / massSun, ' solar mass')
         print('Initial phi: ', self.initPhi)
         print('Initial psi: ', self.initPsi)
         print('Number of points: ', self.Npoint)
         print('Radius max: ', self.radiusMax_in / 1000, ' km')
     y0 = [self.initPressure, self.initMass, self.initPhi, self.initPsi]
     if self.log_active:
         print('y0 = ', y0, '\n')
     r_min = 0.000000001
     r = np.linspace(r_min, self.radiusMax_in, self.Npoint)
     if self.log_active:
         print('radius min ', r_min)
         print('radius max ', self.radiusMax_in)
     sol = solve_ivp(dy_dr, [r_min, self.radiusMax_in],
                     y0,
                     method='RK45',
                     t_eval=r,
                     args=(self.option, self.dilaton_active))
     # condition for Pressure = 0
     '''
     self.g_rr = b(sol.t, sol.y[1])
     a_dot_a = adota(sol.t, sol.y[0], sol.y[1], sol.y[3], sol.y[2])
     self.g_tt = np.exp(np.concatenate([[0.0], integcum(a_dot_a,sol.t)])-integ(a_dot_a,sol.t))
     plt.plot(self.g_tt/self.g_rr)
     plt.show()
     '''
     if sol.t[-1] < self.radiusMax_in:
         self.pressure = sol.y[0][0:-2]
         self.mass = sol.y[1][0:-2]
         self.Phi = sol.y[2][0:-2]
         self.Psi = sol.y[3][0:-2]
         self.radius = sol.t[0:-2]
         # Value at the radius of star
         self.massStar = sol.y[1][-1]
         self.radiusStar = sol.t[-1]
         self.pressureStar = sol.y[0][-1]
         self.phiStar = sol.y[2][-1]
         n_star = len(self.radius)
         if self.log_active:
             print('Star radius: ', self.radiusStar / 1000, ' km')
             print('Star Mass: ', self.massStar / massSun, ' solar mass')
             print('Star Mass: ', self.massStar, ' kg')
             print('Star pressure: ', self.pressureStar, ' Pa\n')
             print(
                 '==========================================================='
             )
             print('SOLVER OUTSIDE THE STAR')
             print(
                 '===========================================================\n'
             )
         y0 = [self.massStar, sol.y[2][-1], sol.y[3][-1]]
         if self.log_active:
             print('y0 = ', y0, '\n')
         r = np.logspace(
             np.log(self.radiusStar) / np.log(10),
             np.log(self.radiusMax_out) / np.log(10), self.Npoint)
         if self.log_active:
             print('radius min ', self.radiusStar)
             print('radius max ', self.radiusMax_out)
         sol = solve_ivp(dy_dr_out, [r[0], self.radiusMax_out],
                         y0,
                         method='DOP853',
                         t_eval=r,
                         args=(0, self.option, self.dilaton_active))
         self.pressure = np.concatenate(
             [self.pressure, np.zeros(self.Npoint)])
         self.mass = np.concatenate([self.mass, sol.y[0]])
         self.Phi = np.concatenate([self.Phi, sol.y[1]])
         self.Psi = np.concatenate([self.Psi, sol.y[2]])
         self.radius = np.concatenate([self.radius, r])
         self.phi_inf = self.Phi[-1]
         if self.log_active:
             print('Phi at infinity ', self.phi_inf)
         # Compute metrics
         self.g_rr = b(self.radius, self.mass)
         a_dot_a = adota(self.radius, self.pressure, self.mass, self.Psi,
                         self.Phi)
         b_dot_b = bdotb(self.radius, self.pressure, self.mass, self.Psi,
                         self.Phi, self.option)
         self.g_tt = np.exp(
             np.concatenate([[0.0], integcum(a_dot_a, self.radius)]) -
             integ(a_dot_a, self.radius))
         self.Lm = Lagrangian(self.pressure, self.option)
         #compute Ricci scalar
         a_dot = a_dot_a * self.g_tt
         a_2dot = (a_dot[1:-1] - a_dot[0:-2]) / (self.radius[1:-1] -
                                                 self.radius[0:-2])
         A = self.g_tt[0:-2]
         B = self.g_rr[0:-2]
         r = self.radius[0:-2]
         a_dot_a = a_dot_a[0:-2]
         b_dot_b = b_dot_b[0:-2]
         R = -(2 / B) * (a_2dot / (2 * A) - 0.5 * a_dot_a**2 + 0.5 *
                         (0.5 * a_dot_a + 2 / r) * (a_dot_a - b_dot_b) +
                         (1 - B) / (r**2))
         R_interpol = interp1d(self.radius[0:-2],
                               R,
                               fill_value="extrapolate")
         self.R = R_interpol(self.radius)
         self.massADM = self.mass[-1]
         self.g_tt_ext = np.array(self.g_tt[n_star:-1])
         self.g_rr_ext = np.array(self.g_rr[n_star:-1])
         self.r_ext = np.array(self.radius[n_star:-1])
         self.r_ext[0] = self.radiusStar
         if self.log_active:
             print('Star Mass ADM: ', self.massADM, ' kg')
             print(
                 '==========================================================='
             )
             print('END')
             print(
                 '===========================================================\n'
             )
     else:
         print('Pressure=0 not reached')
Exemple #11
0
 def Compute(self):
     if self.log_active:
         print(
             '===========================================================')
         print('SOLVER INSIDE THE STAR')
         print(
             '===========================================================\n'
         )
         print('Initial density: ', self.initDensity, ' MeV/fm^3')
         print('Initial pressure: ', self.initPressure / 10**12, ' GPa')
         print('Initial mass: ', self.initMass / massSun, ' solar mass')
         print('Initial phi: ', self.initPhi)
         print('Initial psi: ', self.initPsi)
         print('Number of points: ', self.Npoint)
         print('Radius max: ', self.radiusMax_in / 1000, ' km')
     y0 = [self.initPressure, self.initMass, self.initPhi, self.initPsi]
     if self.log_active:
         print('y0 = ', y0, '\n')
     r = np.linspace(0.01, self.radiusMax_in, self.Npoint)
     if self.log_active:
         print('radius min ', 0.01)
         print('radius max ', self.radiusMax_in)
     sol = solve_ivp(dy_dr, [0.01, self.radiusMax_in],
                     y0,
                     t_eval=r,
                     args=(self.option, self.dilaton_active))
     # condition for Pressure = 0
     if sol.t[-1] < self.radiusMax_in:
         self.pressure = sol.y[0]
         self.mass = sol.y[1]
         self.Phi = sol.y[2]
         self.Psi = sol.y[3]
         self.radius = sol.t
         # Value at the radius of star
         self.massStar = self.mass[-1]
         self.radiusStar = self.radius[-1]
         self.pressureStar = self.pressure[-1]
         if self.log_active:
             print('Star radius: ', self.radiusStar / 1000, ' km')
             print('Star Mass: ', self.massStar / massSun, ' solar mass')
             print('Star pressure: ', self.pressureStar, ' Pa\n')
             print(
                 '==========================================================='
             )
             print('SOLVER OUTSIDE THE STAR')
             print(
                 '===========================================================\n'
             )
         y0 = [self.massStar, self.Phi[-1], self.Psi[-1]]
         if self.log_active:
             print('y0 = ', y0, '\n')
         r = np.linspace(self.radiusStar, self.radiusMax_out, self.Npoint)
         if self.log_active:
             print('radius min ', self.radiusStar)
             print('radius max ', self.radiusMax_out)
         sol = solve_ivp(dy_dr_out, [self.radiusStar, self.radiusMax_out],
                         y0,
                         t_eval=r,
                         args=(0, self.option, self.dilaton_active))
         self.pressure = np.concatenate(
             [self.pressure, np.zeros(self.Npoint)])
         self.mass = np.concatenate([self.mass, sol.y[0]])
         self.Phi = np.concatenate([self.Phi, sol.y[1]])
         self.Psi = np.concatenate([self.Psi, sol.y[2]])
         self.radius = np.concatenate([self.radius, sol.t])
         self.phi_inf = self.Phi[-1]
         if self.log_active:
             print('Phi at infinity ', self.phi_inf)
         # Compute metrics
         self.g_rr = b(self.radius, self.mass)
         a_dot_a = adota(self.radius, self.pressure, self.mass, self.Psi,
                         self.Phi)
         self.g_tt = np.exp(
             np.concatenate([[0.0], integcum(a_dot_a, self.radius)]) -
             integ(a_dot_a, self.radius))
         self.massADM = self.mass[-1]
         if self.log_active:
             print(
                 '==========================================================='
             )
             print('END')
             print(
                 '===========================================================\n'
             )
     else:
         print('Pressure=0 not reached')
Exemple #12
0
def annular_fmean(func,
                  val_arr,
                  f_def,
                  f_inv,
                  ann_dim=2,
                  arg_dict=None,
                  **kwargs):
    r"""
    Calculating the annular generalized f-mean.

    Calculating the annular generalized f-mean of a radial symmetric function
    for given consecutive radii defining annuli by the following formula

    .. math::
       \varphi_i=f^{-1}\left(\frac{d}{r_{i+1}^d-r_i^d}
       \intop^{r_{i+1}}_{r_i} r^{d-1}\cdot f(\varphi(r))\, dr \right)

    Parameters
    ----------
    func : :any:`callable`
        Function that should be used (:math:`\varphi` in the formula).
        The first argument needs to be the radial variable:
        ``func(r, **kwargs)``
    val_arr : :class:`numpy.ndarray`
        Radii defining the annuli.
    ann_dim : :class:`float`, optional
        The dimension of the annuli.
        Default: ``2.0``
    f_def : :any:`callable`
        Function defining the f-mean.
    f_inv : :any:`callable`
        Inverse of the function defining the f-mean.
    arg_dict : :class:`dict` or :any:`None`, optional
        Keyword-arguments given as a dictionary that are forwarded to the
        function given in ``func``. Will be merged with ``**kwargs``.
        This is designed for overlapping keywords in ``annular_fmean`` and
        ``func``.
        Default: ``None``
    **kwargs
        Keyword-arguments that are forwarded to the function given in ``func``.
        Will be merged with ``arg_dict``

    Returns
    -------
    :class:`numpy.ndarray`
        Array with all calculated arithmetic means

    Raises
    ------
    ValueError
        If `func` is not callable.
    ValueError
        If `f_def` is not callable.
    ValueError
        If `f_inv` is not callable.
    ValueError
        If ``val_arr`` has less than 2 values.
    ValueError
        If ``val_arr`` is not sorted in incresing order.

    Notes
    -----
    If the last value in val_arr is "inf", the given function should provide
    a value for "inf" as input: ``func(float("inf"))``
    """
    arg_dict = {} if arg_dict is None else arg_dict
    kwargs.update(arg_dict)

    val_arr = np.array(val_arr, dtype=np.double).reshape(-1)
    parts = len(val_arr) - 1

    if not callable(func):
        raise ValueError("The given function needs to be callable")
    if not callable(f_def):
        raise ValueError("The f-mean function needs to be callable")
    if not callable(f_inv):
        raise ValueError("The inverse f-mean function needs to be callable")
    if not np.all(
            np.isclose(f_inv(f_def(func(val_arr, **kwargs))),
                       func(val_arr, **kwargs))):
        raise ValueError("f_def and f_inv need to be inverse to each other")
    if len(val_arr) < 2:
        raise ValueError("To few input values in val_arr. Need at least 2.")
    if not all(val_arr[i] < val_arr[i + 1] for i in range(len(val_arr) - 1)):
        raise ValueError("The input values need to be sorted")

    def integrand(val):
        """Integrand for the f-mean ``r^(d-1)*f(phi(r))``."""
        return val**(ann_dim - 1) * f_def(func(val, **kwargs))

    # creating the output array
    func_arr = np.zeros_like(val_arr[:-1], dtype=np.double)

    # iterating over the input values
    for i in range(parts):
        # if one side is infinity, the function is evaluated at infinity
        if val_arr[i + 1] == np.inf:
            func_arr[i] = func(np.inf, **kwargs)
        else:
            func_arr[i] = f_inv(
                ann_dim * integ(integrand, val_arr[i], val_arr[i + 1])[0] /
                (val_arr[i + 1]**ann_dim - val_arr[i]**ann_dim))

    return func_arr
Exemple #13
0
def rad_amean_func(func, val_arr, arg_dict=None, **kwargs):
    '''
    Calculating the arithmetic mean of a radial symmetric function
    for given consecutive radii defining 2D disks by the following formula

    .. math::
       f_i=\\frac{2}{r_{i+1}^2-r_i^2}
       \\intop^{r_{i+1}}_{r_i} r\\cdot f(r)\\, dr

    Parameters
    ----------
    func : :any:`callable`
        function that should be used
        The first argument needs to be the radial variable:
        ``func(r, **kwargs)``
    val_arr : :class:`numpy.ndarray`
        given radii defining the disks
    arg_dict : :class:`dict` or :any:`None`, optional
        Keyword-arguments given as a dictionary that are forwarded to the
        function given in ``func``. Will be merged with ``**kwargs``.
        This is designed for overlapping keywords in ``rad_amean_func`` and
        ``func``.
        Default: ``None``
    **kwargs
        Keyword-arguments that are forwarded to the function given in ``func``.
        Will be merged with ``arg_dict``

    Returns
    -------
    :class:`numpy.ndarray`
        Array with all calculated arithmetic means

    Raises
    ------
    ValueError
        If `func` is not callable.
    ValueError
        If ``val_arr`` has less than 2 values.
    ValueError
        If ``val_arr`` is not sorted in incresing order.

    Notes
    -----
    If the last value in val_arr is "inf", the given function should provide
    a value for "inf" as input: ``func(float("inf"))``

    Example
    -------
    >>> f = lambda x: x**2
    >>> rad_amean_func(f, [1,2,3])
    array([ 2.33588885,  6.33423311])
    '''

    if arg_dict is None:
        arg_dict = {}
    kwargs.update(arg_dict)

    val_arr = np.array(val_arr, dtype=float).reshape(-1)
    parts = len(val_arr) - 1

    if not callable(func):
        raise ValueError("The given function needs to be callable")
    if len(val_arr) < 2:
        raise ValueError("To few input values in val_arr. Need at least 2.")
    if not all(val_arr[i] < val_arr[i + 1] for i in range(len(val_arr) - 1)):
        raise ValueError("The input values need to be sorted")

    # dummy function defining the needed integrand
    def _step(func, kwargs):
        """
        dummy function providing the integrand
        """
        def integrand(val):
            '''
            Integrand for the geometric mean ``r*log(f(r))``
            '''
            return 2 * val * func(val, **kwargs)

        return integrand

    # creating the output array
    func_arr = np.zeros_like(val_arr[:-1], dtype=float)

    # iterating over the input values
    for i in range(parts):
        # if one side is infinity, the function is evaluated at infinity
        if val_arr[i + 1] == np.inf:
            func_arr[i] = func(np.inf, **kwargs)
        else:
            func_arr[i] = integ(_step(func, kwargs), val_arr[i],
                                val_arr[i + 1])[0]
            func_arr[i] = func_arr[i] / (val_arr[i + 1]**2 - val_arr[i]**2)

    return func_arr
Exemple #14
0
 def Compute(self):
     if self.log_active:
         print(
             '===========================================================')
         print('SOLVER INSIDE THE STAR')
         print(
             '===========================================================\n'
         )
         print('Initial density: ', self.initDensity, ' MeV/fm^3')
         print('Initial pressure: ', self.initPressure / 10**12, ' GPa')
         print('Initial mass: ', self.initMass / massSun, ' solar mass')
         print('Initial phi: ', self.initPhi)
         print('Initial psi: ', self.initPsi)
         print('Number of points: ', self.Npoint)
         print('Radius max: ', self.radiusMax_in / 1000, ' km')
     y0 = [self.initPressure, self.initMass, self.initPhi, self.initPsi]
     if self.log_active:
         print('y0 = ', y0, '\n')
     r = np.linspace(0.01, self.radiusMax_in, self.Npoint)
     if self.log_active:
         print('radius min ', 0.01)
         print('radius max ', self.radiusMax_in)
     sol = solve_ivp(dy_dr, [0.01, self.radiusMax_in],
                     y0,
                     method='RK45',
                     t_eval=r,
                     args=(self.option, self.dilaton_active))
     # condition for Pressure = 0
     '''
     self.g_rr = b(sol.t, sol.y[1])
     a_dot_a = adota(sol.t, sol.y[0], sol.y[1], sol.y[3], sol.y[2])
     self.g_tt = np.exp(np.concatenate([[0.0], integcum(a_dot_a,sol.t)])-integ(a_dot_a,sol.t))
     plt.plot(self.g_tt/self.g_rr)
     plt.show()
     '''
     if sol.t[-1] < self.radiusMax_in:
         self.pressure = sol.y[0][0:-2]
         self.mass = sol.y[1][0:-2]
         self.Phi = sol.y[2][0:-2]
         self.Psi = sol.y[3][0:-2]
         self.radius = sol.t[0:-2]
         # Value at the radius of star
         self.massStar = sol.y[1][-1]
         self.radiusStar = sol.t[-1]
         self.pressureStar = sol.y[0][-1]
         self.phiStar = sol.y[2][-1]
         n_star = len(self.radius)
         if self.log_active:
             print('Star radius: ', self.radiusStar / 1000, ' km')
             print('Star Mass: ', self.massStar / massSun, ' solar mass')
             print('Star Mass: ', self.massStar, ' kg')
             print('Star pressure: ', self.pressureStar, ' Pa\n')
             print(
                 '==========================================================='
             )
             print('SOLVER OUTSIDE THE STAR')
             print(
                 '===========================================================\n'
             )
         y0 = [self.massStar, sol.y[2][-1], sol.y[3][-1]]
         if self.log_active:
             print('y0 = ', y0, '\n')
         r = np.logspace(
             np.log(self.radiusStar) / np.log(10),
             np.log(self.radiusMax_out) / np.log(10), self.Npoint)
         if self.log_active:
             print('radius min ', self.radiusStar)
             print('radius max ', self.radiusMax_out)
         sol = solve_ivp(dy_dr_out, [r[0], self.radiusMax_out],
                         y0,
                         method='DOP853',
                         t_eval=r,
                         args=(0, self.option, self.dilaton_active))
         self.pressure = np.concatenate(
             [self.pressure, np.zeros(self.Npoint)])
         self.mass = np.concatenate([self.mass, sol.y[0]])
         self.Phi = np.concatenate([self.Phi, sol.y[1]])
         self.Psi = np.concatenate([self.Psi, sol.y[2]])
         self.radius = np.concatenate([self.radius, r])
         self.phi_inf = self.Phi[-1]
         if self.log_active:
             print('Phi at infinity ', self.phi_inf)
         # Compute metrics
         self.g_rr = b(self.radius, self.mass)
         a_dot_a = adota(self.radius, self.pressure, self.mass, self.Psi,
                         self.Phi)
         #plt.plot(self.radius, np.concatenate([[0.0], integcum(a_dot_a,self.radius)]))
         #plt.show()
         self.g_tt = np.exp(
             np.concatenate([[0.0], integcum(a_dot_a, self.radius)]) -
             integ(a_dot_a, self.radius))
         self.massADM = self.mass[-1]
         self.g_tt_ext = np.array(self.g_tt[n_star:-1])
         self.g_rr_ext = np.array(self.g_rr[n_star:-1])
         self.r_ext = np.array(self.radius[n_star:-1])
         self.r_ext[0] = self.radiusStar
         if self.log_active:
             print('Star Mass ADM: ', self.massADM, ' kg')
             print(
                 '==========================================================='
             )
             print('END')
             print(
                 '===========================================================\n'
             )
     else:
         print('Pressure=0 not reached')