Esempio n. 1
0
def hyperrectangle_integration(mean,
                               covariance,
                               lower=None,
                               upper=None,
                               info=False):
    # parallel batch version of scipy.stats.mvn
    # no pytorch here
    # default: integration over the first orthant (for all i, Y_i<0)
    ms = mean.shape
    batch_shape = ms[:-1]
    d = ms[-1]

    N = prod(batch_shape)
    m = mean.reshape(N, d)
    l = full_like(m, -Inf) if lower is None else lower.reshape(N, d)
    u = zeros_like(m) if upper is None else upper.reshape(N, d)
    c = covariance.reshape(N, d, d)

    v, i = parallel_integration(l, u, m, c)
    values = array(v).reshape(batch_shape)
    if info:
        infos = array(i, dtype=int32).reshape(batch_shape)
        return (values, infos)
    else:
        return values
Esempio n. 2
0
 def __init__(self, *shape):
     if len(shape) == 1 and isinstance(shape[0], tuple):
         shape = shape[0]
     x = as_strided(_nx.zeros(1), shape=shape,
                    strides=_nx.zeros_like(shape))
     self._it = _nx.nditer(x, flags=['multi_index', 'zerosize_ok'],
                           order='C')
Esempio n. 3
0
def easy():
    numbers, boards = read()
    hits = lmap(lambda i: zeros_like(i), boards)
    for number in numbers:
        for (i, board) in enumerate(boards):
            if detect(board, hits[i], number) != 0:
                return print(score(board, hits[i], number))
Esempio n. 4
0
 def __init__(self, *shape):
     if len(shape) == 1 and isinstance(shape[0], tuple):
         shape = shape[0]
     x = as_strided(_nx.zeros(1), shape=shape,
                    strides=_nx.zeros_like(shape))
     self._it = _nx.nditer(x, flags=['multi_index', 'zerosize_ok'],
                           order='C')
def find_y2(a,x):
    p = NX.asarray(a)

    x = NX.asarray(x)
    y = NX.zeros_like(x)
    for i in range(len(p)):
        y = y * x + p[i]
    return y
Esempio n. 6
0
def polyval(p, x):
    """
    Evaluate a polynomial at specific values.

    If p is of length N, this function returns the value:

        p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1]

    If x is a sequence then p(x) will be returned for all elements of x.
    If x is another polynomial then the composite polynomial p(x) will
    be returned.

    Parameters
    ----------
    p : {array_like, poly1d}
       1D array of polynomial coefficients from highest degree to zero or an
       instance of poly1d.
    x : {array_like, poly1d}
       A number, a 1D array of numbers, or an instance of poly1d.

    Returns
    -------
    values : {ndarray, poly1d}
       If either p or x is an instance of poly1d, then an instance of poly1d
       is returned, otherwise a 1D array is returned. In the case where x is
       a poly1d, the result is the composition of the two polynomials, i.e.,
       substitution is used.

    See Also
    --------
    poly1d: A polynomial class.

    Notes
    -----
    Horner's method is used to evaluate the polynomial. Even so, for
    polynomials of high degree the values may be inaccurate due to
    rounding errors. Use carefully.


    Examples
    --------
    >>> np.polyval([3,0,1], 5)  # 3 * 5**2 + 0 * 5**1 + 1
    76

    """
    p = NX.asarray(p)
    if isinstance(x, poly1d):
        y = 0
    else:
        x = NX.asarray(x)
        y = NX.zeros_like(x)
    for i in range(len(p)):
        y = x * y + p[i]
    return y
Esempio n. 7
0
def polyval(p, x):
    """
    Evaluate a polynomial at specific values.

    If p is of length N, this function returns the value:

        p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1]

    If x is a sequence then p(x) will be returned for all elements of x.
    If x is another polynomial then the composite polynomial p(x) will
    be returned.

    Parameters
    ----------
    p : {array_like, poly1d}
       1D array of polynomial coefficients from highest degree to zero or an
       instance of poly1d.
    x : {array_like, poly1d}
       A number, a 1D array of numbers, or an instance of poly1d.

    Returns
    -------
    values : {ndarray, poly1d}
       If either p or x is an instance of poly1d, then an instance of poly1d
       is returned, otherwise a 1D array is returned. In the case where x is
       a poly1d, the result is the composition of the two polynomials, i.e.,
       substitution is used.

    See Also
    --------
    poly1d: A polynomial class.

    Notes
    -----
    Horner's method is used to evaluate the polynomial. Even so, for
    polynomials of high degree the values may be inaccurate due to
    rounding errors. Use carefully.


    Examples
    --------
    >>> np.polyval([3,0,1], 5)  # 3 * 5**2 + 0 * 5**1 + 1
    76

    """
    p = NX.asarray(p)
    if isinstance(x, poly1d):
        y = 0
    else:
        x = NX.asarray(x)
        y = NX.zeros_like(x)
    for i in range(len(p)):
        y = x * y + p[i]
    return y
Esempio n. 8
0
def hard():
    numbers, boards = read()
    hits = lmap(lambda i: zeros_like(i), boards)
    done = set()
    for number in numbers:
        for (i, board) in enumerate(boards):
            if i in done:
                continue
            if detect(board, hits[i], number) != 0:
                done |= {i}
                if len(done) == len(boards):
                    return print(score(board, hits[i], number))
Esempio n. 9
0
    def _set_selection(self, val):
        oldval = self._selection
        self._selection = val

        datasource = getattr(self.plot, self.axis, None)

        if datasource is not None:

            mdname = self.metadata_name

            # Set the selection range on the datasource
            datasource.metadata[mdname] = val
            datasource.metadata_changed = {mdname: val}

            # Set the selection mask on the datasource
            selection_masks = \
                datasource.metadata.setdefault(self.mask_metadata_name, [])
            for index in range(len(selection_masks)):
#                if id(selection_masks[index]) == id(self._selection_mask):
                if True:
                    del selection_masks[index]
                    break

            # Set the selection mode on the datasource
            datasource.metadata[self.selection_mode_metadata_name] = \
                      self.selection_mode

            if val is not None:
                low, high = val
                data_pts = datasource.get_data()
                new_mask = (data_pts >= low) & (data_pts <= high)
                selection_masks.append(new_mask)
                self._selection_mask = new_mask
            else:
                # Set the selection mask to false.
                data_pts = datasource.get_data()
                new_mask = zeros_like(data_pts,dtype=bool)
                selection_masks.append(new_mask)
                self._selection_mask = new_mask

                
            datasource.metadata_changed = {self.mask_metadata_name: val}
        

        self.trait_property_changed("selection", oldval, val)

        for l in self.listeners:
            if hasattr(l, "set_value_selection"):
                l.set_value_selection(val)

        return
Esempio n. 10
0
 def calculate(self,
               atoms=None,
               properties=None,
               system_changes=all_changes):
     Calculator.calculate(self, atoms, properties, system_changes)
     image = atoms
     natoms = len(image)
     energy = 0.0
     forces = np.zeros((natoms, 3))
     self.results["energy"] = energy
     self.results["forces"] = forces
     self.results["stress"] = -np.array([0, 0, 0, 0, 0, 0])
     self.results["force_stds"] = zeros_like(forces)
     atoms.info["max_force_stds"] = np.nanmax(self.results["force_stds"])
Esempio n. 11
0
    def recommend(self, evidences, n):

        #Array of item bought
        evidencesVec = zeros_like(self.ItemPrior)
        evidencesVec[evidences] = 1

        p_z_newUser = self.pLSAmodel.folding_in(evidencesVec)

        p_item_z = self.pLSAmodel.p_w_z

        p_item_newUser = zeros((p_item_z.shape[0]))
        for i in range(p_item_z.shape[1]):
            p_item_newUser += p_item_z[:, i] * p_z_newUser[0]

        ind = argsort(p_item_newUser)

        if n == -1:
            return ind
        else:
            return ind[-n:]
Esempio n. 12
0
def fix(x, y=None):
    """
    Round to nearest integer towards zero.

    Round an array of floats element-wise to nearest integer towards zero.
    The rounded values are returned as floats.

    Parameters
    ----------
    x : array_like
        An array of floats to be rounded
    y : ndarray, optional
        Output array

    Returns
    -------
    out : ndarray of floats
        The array of rounded numbers

    See Also
    --------
    trunc, floor, ceil
    around : Round to given number of decimals

    Examples
    --------
    >>> np.fix(3.14)
    3.0
    >>> np.fix(3)
    3.0
    >>> np.fix([2.1, 2.9, -2.1, -2.9])
    array([ 2.,  2., -2., -2.])

    """
    x = nx.asanyarray(x)
    if y is None:
        y = nx.zeros_like(x)
    y1 = nx.floor(x)
    y2 = nx.ceil(x)
    y[...] = nx.where(x >= 0, y1, y2)
    return y
Esempio n. 13
0
def fix(x, y=None):
    """
    Round to nearest integer towards zero.

    Round an array of floats element-wise to nearest integer towards zero.
    The rounded values are returned as floats.

    Parameters
    ----------
    x : array_like
        An array of floats to be rounded
    y : ndarray, optional
        Output array

    Returns
    -------
    out : ndarray of floats
        The array of rounded numbers

    See Also
    --------
    trunc, floor, ceil
    around : Round to given number of decimals

    Examples
    --------
    >>> np.fix(3.14)
    3.0
    >>> np.fix(3)
    3.0
    >>> np.fix([2.1, 2.9, -2.1, -2.9])
    array([ 2.,  2., -2., -2.])

    """
    x = nx.asanyarray(x)
    if y is None:
        y = nx.zeros_like(x)
    y1 = nx.floor(x)
    y2 = nx.ceil(x)
    y[...] = nx.where(x >= 0, y1, y2)
    return y
Esempio n. 14
0
	def recommend(self, evidences, n):
		
		#Array of item bought
		evidencesVec = zeros_like(self.ItemPrior)
		evidencesVec[evidences] = 1
		
		p_z_newUser = self.pLSAmodel.folding_in(evidencesVec)
		
		p_item_z = self.pLSAmodel.p_w_z
		
		p_item_newUser = zeros((p_item_z.shape[0]))
		for i in range(p_item_z.shape[1]):
			p_item_newUser+=p_item_z[:,i] * p_z_newUser[0]
		
		
		ind = argsort(p_item_newUser)
		
		if n == -1:
			return ind
		else:
			return ind[-n:]		
Esempio n. 15
0
def polyval(p, x):
    """Evaluate the polynomial p at x.  If x is a polynomial then composition.

    Description:

      If p is of length N, this function returns the value:
      p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1]

      x can be a sequence and p(x) will be returned for all elements of x.
      or x can be another polynomial and the composite polynomial p(x) will be
      returned.

      Notice:  This can produce inaccurate results for polynomials with
      significant variability. Use carefully.
    """
    p = NX.asarray(p)
    if isinstance(x, poly1d):
        y = 0
    else:
        x = NX.asarray(x)
        y = NX.zeros_like(x)
    for i in range(len(p)):
        y = x * y + p[i]
    return y
Esempio n. 16
0
def polyval(p, x):
    """Evaluate the polynomial p at x.  If x is a polynomial then composition.

    Description:

      If p is of length N, this function returns the value:
      p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1]

      x can be a sequence and p(x) will be returned for all elements of x.
      or x can be another polynomial and the composite polynomial p(x) will be
      returned.

      Notice:  This can produce inaccurate results for polynomials with
      significant variability. Use carefully.
    """
    p = NX.asarray(p)
    if isinstance(x, poly1d):
        y = 0
    else:
        x = NX.asarray(x)
        y = NX.zeros_like(x)
    for i in range(len(p)):
        y = x * y + p[i]
    return y
Esempio n. 17
0
 def laplace(self,u,h):
     ret = zeros_like(u)
     ret[1:-1] = (u[0:-2] - 2.0*u[1:-1] + u[2:])/h**2
     ret[0] = (-u[0] + u[1])/h**2
     ret[-1] = (u[-2] - u[-1])/h**2
     return ret
Esempio n. 18
0
def main():
    Omega = 1
    bz = BelousovZhabotinskii(Omega)
    
    #u0 = bz.max_u()
    u0 = bz.u_stationary()*2
    v0 = bz.v_stationary()
    
    y0 = [u0,v0]
    
    max_t = 10.0
    t = np.arange(0,max_t,0.0001)
    u_nullcline = np.logspace(-4, 0, 100000)*Omega
    v_nullclines = bz.nullcline(u_nullcline)
    
    y = odeint(bz.dy_dt,y0,t)
    
    plt.Figure()
    plt.plot(u_nullcline, v_nullclines[0])
    plt.plot(u_nullcline, v_nullclines[1])
    plt.plot(y[:,0],y[:,1])
    plt.loglog()
    plt.xlim([5e-5*Omega,2e0*Omega])
    #plt.show()
    plt.savefig("bz_wave_phase_plot.png")
    
    plt.clf()
    plt.plot(t,y[:,0])
    plt.plot(t,y[:,1])
    plt.plot(t,bz.w(y[:,0],y[:,1]))
    plt.yscale('log')
    plt.xlim((0,5))
    #plt.show()
    plt.savefig("bz_wave_concen_versus_time.png")
    
    plt.clf()
    h = 0.001
    x = np.arange(0,20,h)
    u0 = zeros_like(x) + bz.u_stationary()
    v0 = zeros_like(x) + bz.v_stationary()
    u0[x<1] = bz.u_stationary()*2
    y = np.vstack((u0,v0))
    
    if 1:
        dt = 0.0000001
        iterations = int(max_t/dt)
        out_every = iterations/1000
        #out_every = 1000
        #plt.ion()
        plot_u, = plt.plot(x,u0)
        plot_v, = plt.plot(x,v0)
        plt.yscale('log')
        plt.ylim((bz.u_stationary()/10,bz.max_u()))
        #plt.show()
        dydt_old = bz.dy_dt_diffuse(y, t, h)
        for i in range(0,iterations):
            t = i*dt
        
            if (i%out_every == 0):
                plot_u.set_ydata(y[0,:])
                plot_v.set_ydata(y[1,:])
                #plt.draw()
                plt.savefig("bz_wave_" + '%04d'%i + ".png")
            
            dydt = bz.dy_dt_diffuse(y, t, h)
            #y = y + dt*dydt
            y = y + 3.0/2.0*dt*dydt - 0.5*dt*dydt_old
            dydt_old = dydt
Esempio n. 19
0
def isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False):
    """
    Returns a boolean array where two arrays are element-wise equal within a
    tolerance.

    The tolerance values are positive, typically very small numbers.  The
    relative difference (`rtol` * abs(`b`)) and the absolute difference
    `atol` are added together to compare against the absolute difference
    between `a` and `b`.

    Parameters
    ----------
    a, b : array_like
        Input arrays to compare.
    rtol : float
        The relative tolerance parameter (see Notes).
    atol : float
        The absolute tolerance parameter (see Notes).
    equal_nan : bool
        Whether to compare NaN's as equal.  If True, NaN's in `a` will be
        considered equal to NaN's in `b` in the output array.

    Returns
    -------
    y : array_like
        Returns a boolean array of where `a` and `b` are equal within the
        given tolerance. If both `a` and `b` are scalars, returns a single
        boolean value.

    See Also
    --------
    allclose

    Notes
    -----
    .. versionadded:: 1.7.0

    For finite values, isclose uses the following equation to test whether
    two floating point values are equivalent.

     absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))

    The above equation is not symmetric in `a` and `b`, so that
    `isclose(a, b)` might be different from `isclose(b, a)` in
    some rare cases.

    Examples
    --------
    >>> np.isclose([1e10,1e-7], [1.00001e10,1e-8])
    array([True, False])
    >>> np.isclose([1e10,1e-8], [1.00001e10,1e-9])
    array([True, True])
    >>> np.isclose([1e10,1e-8], [1.0001e10,1e-9])
    array([False, True])
    >>> np.isclose([1.0, np.nan], [1.0, np.nan])
    array([True, False])
    >>> np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
    array([True, True])
    """
    def within_tol(x, y, atol, rtol):
        with errstate(invalid='ignore'):
            result = less_equal(abs(x - y), atol + rtol * abs(y))
        if isscalar(a) and isscalar(b):
            result = bool(result)
        return result

    x = array(a, copy=False, subok=True, ndmin=1)
    y = array(b, copy=False, subok=True, ndmin=1)

    # Make sure y is an inexact type to avoid bad behavior on abs(MIN_INT).
    # This will cause casting of x later. Also, make sure to allow subclasses
    # (e.g., for numpy.ma).
    dt = multiarray.result_type(y, 1.)
    y = array(y, dtype=dt, copy=False, subok=True)

    xfin = isfinite(x)
    yfin = isfinite(y)
    if all(xfin) and all(yfin):
        return within_tol(x, y, atol, rtol)
    else:
        finite = xfin & yfin
        cond = zeros_like(finite, subok=True)
        # Because we're using boolean indexing, x & y must be the same shape.
        # Ideally, we'd just do x, y = broadcast_arrays(x, y). It's in
        # lib.stride_tricks, though, so we can't import it here.
        x = x * ones_like(cond)
        y = y * ones_like(cond)
        # Avoid subtraction with infinite/nan values...
        cond[finite] = within_tol(x[finite], y[finite], atol, rtol)
        # Check for equality of infinite values...
        cond[~finite] = (x[~finite] == y[~finite])
        if equal_nan:
            # Make NaN == NaN
            both_nan = isnan(x) & isnan(y)
            cond[both_nan] = both_nan[both_nan]

        if isscalar(a) and isscalar(b):
            return bool(cond)
        else:
            return cond
Esempio n. 20
0
    def calc_ionisation_balance_matrix(
        self,
        Ne: DataArray,
        Nh: DataArray = None,
    ):
        """Calculates the ionisation balance matrix that defines the differential equation
        that defines the time evolution of the fractional abundance of all of the
        ionisation charges.

        Ne
            xarray.DataArray of electron density as a profile of a user-chosen
            coordinate.
        Nh
            xarray.DataArray of thermal hydrogen as a profile of a user-chosen
            coordinate. (Optional)

        Returns
        -------
        ionisation_balance_matrix
            Matrix representing coefficients of the differential equation governing
            the time evolution of the ionisation balance.
        """
        inputted_data = {}

        input_check("Ne", Ne, DataArray, greater_than_or_equal_zero=True)
        inputted_data["Ne"] = Ne

        if Nh is not None:
            if self.CCD is None:
                raise ValueError(
                    "Nh (Thermal hydrogen density) cannot be given when \
                    CCD (effective charge exchange recombination) at initialisation \
                    is None."
                )
            input_check("Nh", Nh, DataArray, greater_than_or_equal_zero=True)
            inputted_data["Nh"] = Nh
        elif self.CCD is not None:
            Nh = cast(DataArray, zeros_like(Ne))
            inputted_data["Nh"] = cast(DataArray, Nh)

        shape_check(inputted_data)

        if self.Ne is not None:
            if np.logical_not(np.all(Ne == self.Ne)):
                warnings.warn(
                    "Ne given to calc_ionisation_balance_matrix is different from \
                        the internal Ne known to FractionalAbundance object."
                )

        self.Ne, self.Nh = Ne, Nh  # type: ignore

        num_of_ion_charges = self.num_of_ion_charges
        SCD, ACD, CCD = self.SCD_spec, self.ACD_spec, self.CCD_spec

        x1_coord = SCD.coords[[k for k in SCD.dims if k != "ion_charges"][0]]
        self.x1_coord = x1_coord

        dims = (
            num_of_ion_charges,
            num_of_ion_charges,
            *x1_coord.shape,
        )

        ionisation_balance_matrix = np.zeros(dims)

        icharge = 0
        ionisation_balance_matrix[icharge, icharge : icharge + 2] = np.array(
            [
                -Ne * SCD[icharge],  # type: ignore
                Ne * ACD[icharge]
                + (Nh * CCD[icharge] if Nh is not None and CCD is not None else 0.0),
            ]
        )
        for icharge in range(1, num_of_ion_charges - 1):
            ionisation_balance_matrix[icharge, icharge - 1 : icharge + 2] = np.array(
                [
                    Ne * SCD[icharge - 1],
                    -Ne * (SCD[icharge] + ACD[icharge - 1])  # type: ignore
                    - (
                        Nh * CCD[icharge - 1]
                        if Nh is not None and CCD is not None
                        else 0.0
                    ),
                    Ne * ACD[icharge]
                    + (
                        Nh * CCD[icharge] if Nh is not None and CCD is not None else 0.0
                    ),
                ]
            )
        icharge = num_of_ion_charges - 1
        ionisation_balance_matrix[icharge, icharge - 1 : icharge + 1] = np.array(
            [
                Ne * SCD[icharge - 1],
                -Ne * (ACD[icharge - 1])  # type: ignore
                - (
                    Nh * CCD[icharge - 1] if Nh is not None and CCD is not None else 0.0
                ),
            ]
        )

        ionisation_balance_matrix = np.squeeze(ionisation_balance_matrix)
        self.ionisation_balance_matrix = ionisation_balance_matrix

        return ionisation_balance_matrix
Esempio n. 21
0
 def __init__(self, *shape):
     x = as_strided(_nx.zeros(1),
                    shape=shape,
                    strides=_nx.zeros_like(shape))
     self._it = _nx.nditer(x, flags=['multi_index'], order='C')
Esempio n. 22
0
def polyval(p, x):
    """
    Evaluate a polynomial at specific values.

    If `p` is of length N, this function returns the value:

        ``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]``

    If `x` is a sequence, then `p(x)` is returned for each element of `x`.
    If `x` is another polynomial then the composite polynomial `p(x(t))`
    is returned.

    Parameters
    ----------
    p : array_like or poly1d object
       1D array of polynomial coefficients (including coefficients equal
       to zero) from highest degree to the constant term, or an
       instance of poly1d.
    x : array_like or poly1d object
       A number, a 1D array of numbers, or an instance of poly1d, "at"
       which to evaluate `p`.

    Returns
    -------
    values : ndarray or poly1d
       If `x` is a poly1d instance, the result is the composition of the two
       polynomials, i.e., `x` is "substituted" in `p` and the simplified
       result is returned. In addition, the type of `x` - array_like or
       poly1d - governs the type of the output: `x` array_like => `values`
       array_like, `x` a poly1d object => `values` is also.

    See Also
    --------
    poly1d: A polynomial class.

    Notes
    -----
    Horner's scheme [1]_ is used to evaluate the polynomial. Even so,
    for polynomials of high degree the values may be inaccurate due to
    rounding errors. Use carefully.

    References
    ----------
    .. [1] I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng.
       trans. Ed.), *Handbook of Mathematics*, New York, Van Nostrand
       Reinhold Co., 1985, pg. 720.

    Examples
    --------
    >>> np.polyval([3,0,1], 5)  # 3 * 5**2 + 0 * 5**1 + 1
    76
    >>> np.polyval([3,0,1], np.poly1d(5))
    poly1d([ 76.])
    >>> np.polyval(np.poly1d([3,0,1]), 5)
    76
    >>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
    poly1d([ 76.])

    """
    p = NX.asarray(p)
    if isinstance(x, poly1d):
        y = 0
    else:
        x = NX.asarray(x)
        y = NX.zeros_like(x)
    for i in range(len(p)):
        y = x * y + p[i]
    return y
Esempio n. 23
0
    def calculate_power_loss(
        self, Ne: DataArray, F_z_t: DataArray, Nh: DataArray = None
    ):
        """Calculates total radiated power of all ionisation charges of a given
        impurity element.

        Parameters
        ----------
        Ne
            xarray.DataArray of electron density as a profile of a user-chosen
            coordinate.
        F_z_t
            xarray.DataArray of fractional abundance of all ionisation charges of given
            impurity element.
        Nh
            xarray.DataArray of thermal hydrogen number density as a profile of a
            user-chosen coordinate. (Optional)

        Returns
        -------
        cooling_factor
            Total radiated power of all ionisation charges.
        """
        inputted_data = {}
        inputted_data["Ne"] = Ne

        if Nh is not None:
            if self.PRC is None:
                raise ValueError(
                    "Nh (Thermal hydrogen density) cannot be given when \
                    PRC (effective charge exchange power) at initialisation \
                    is None."
                )
            input_check("Nh", Nh, DataArray, greater_than_or_equal_zero=True)
            inputted_data["Nh"] = Nh
        elif self.PRC is not None:
            Nh = cast(DataArray, zeros_like(Ne))
            inputted_data["Nh"] = cast(DataArray, Nh)

        if self.Ne is not None:
            if np.logical_not(np.all(Ne == self.Ne)):
                warnings.warn(
                    "Ne given to calc_ionisation_balance_matrix is different from \
                        the internal Ne known to FractionalAbundance object."
                )

        self.Ne, self.Nh = Ne, Nh  # type: ignore

        if len(inputted_data) > 1:
            shape_check(inputted_data)

        if F_z_t is not None:
            input_check("F_z_t", F_z_t, DataArray, greater_than_or_equal_zero=True)
            try:
                assert not np.iscomplexobj(F_z_t)
            except AssertionError:
                raise ValueError(
                    "Inputted F_z_t is a complex type or array of complex numbers, \
                        must be real"
                )
            self.F_z_t = F_z_t  # type: ignore
        elif self.F_z_t is None:
            raise ValueError("Please provide a valid F_z_t (Fractional Abundance).")

        self.x1_coord = self.PLT_spec.coords[
            [k for k in self.PLT_spec.dims if k != "ion_charges"][0]
        ]

        x1_coord = self.x1_coord

        PLT, PRB, PRC = self.PLT_spec, self.PRB_spec, self.PRC_spec

        # Mypy complaints about F_z_t not being subscriptable since it thinks
        # it's a NoneType have been suppresed. This is because F_z_t is tested
        # to be a DataArray with elements greater than zero.
        # (in the input_check() above)

        cooling_factor = xr.zeros_like(self.F_z_t)
        for ix1 in range(x1_coord.size):
            icharge = 0
            cooling_factor[icharge, ix1] = (
                PLT[icharge, ix1] * self.F_z_t[icharge, ix1]  # type: ignore
            )
            for icharge in range(1, self.num_of_ion_charges - 1):
                cooling_factor[icharge, ix1] = (
                    PLT[icharge, ix1]
                    + (
                        (Nh[ix1] / Ne[ix1]) * PRC[icharge - 1, ix1]
                        if (PRC is not None) and (Nh is not None)
                        else 0.0
                    )
                    + PRB[icharge - 1, ix1]
                ) * self.F_z_t[
                    icharge, ix1
                ]  # type: ignore

            icharge = self.num_of_ion_charges - 1
            cooling_factor[icharge, ix1] = (
                (
                    (Nh[ix1] / Ne[ix1]) * PRC[icharge - 1, ix1]
                    if (PRC is not None) and (Nh is not None)
                    else 0.0
                )
                + PRB[icharge - 1, ix1]
            ) * self.F_z_t[
                icharge, ix1
            ]  # type: ignore

        self.cooling_factor = cooling_factor

        return cooling_factor
Esempio n. 24
0
def polyval(p, x):
    """
    Evaluate a polynomial at specific values.

    If `p` is of length N, this function returns the value:

        ``p[0]*x**(N-1) + p[1]*x**(N-2) + ... + p[N-2]*x + p[N-1]``

    If `x` is a sequence, then `p(x)` is returned for each element of `x`.
    If `x` is another polynomial then the composite polynomial `p(x(t))`
    is returned.

    Parameters
    ----------
    p : array_like or poly1d object
       1D array of polynomial coefficients (including coefficients equal
       to zero) from highest degree to the constant term, or an
       instance of poly1d.
    x : array_like or poly1d object
       A number, a 1D array of numbers, or an instance of poly1d, "at"
       which to evaluate `p`.

    Returns
    -------
    values : ndarray or poly1d
       If `x` is a poly1d instance, the result is the composition of the two
       polynomials, i.e., `x` is "substituted" in `p` and the simplified
       result is returned. In addition, the type of `x` - array_like or
       poly1d - governs the type of the output: `x` array_like => `values`
       array_like, `x` a poly1d object => `values` is also.

    See Also
    --------
    poly1d: A polynomial class.

    Notes
    -----
    Horner's scheme [1]_ is used to evaluate the polynomial. Even so,
    for polynomials of high degree the values may be inaccurate due to
    rounding errors. Use carefully.

    References
    ----------
    .. [1] I. N. Bronshtein, K. A. Semendyayev, and K. A. Hirsch (Eng.
       trans. Ed.), *Handbook of Mathematics*, New York, Van Nostrand
       Reinhold Co., 1985, pg. 720.

    Examples
    --------
    >>> np.polyval([3,0,1], 5)  # 3 * 5**2 + 0 * 5**1 + 1
    76
    >>> np.polyval([3,0,1], np.poly1d(5))
    poly1d([ 76.])
    >>> np.polyval(np.poly1d([3,0,1]), 5)
    76
    >>> np.polyval(np.poly1d([3,0,1]), np.poly1d(5))
    poly1d([ 76.])

    """
    p = NX.asarray(p)
    if isinstance(x, poly1d):
        y = 0
    else:
        x = NX.asarray(x)
        y = NX.zeros_like(x)
    for i in range(len(p)):
        y = y * x + p[i]
    return y
Esempio n. 25
0
 def __init__(self, *shape):
     x = as_strided(_nx.zeros(1), shape=shape, strides=_nx.zeros_like(shape))
     self._it = _nx.nditer(x, flags=['multi_index'], order='C')