
    \ciE                     
   d dl Z d dlZd dlZd dlZd dlmZ d dlmZ ddl	m
Z
 d dlmc mZ d dlmZ d dlmZmZ ddlmZmZ d	gZd
 Z edddg           G d d	                      Zd Zej        fdZdej        ddZdS )    N)prod)GenericAlias   )_dierckx)	csr_array)array_namespacexp_capabilities)_not_a_knotBSpline	NdBSplinec                 p    t          j        | t           j                  rt           j        S t           j        S )z>Return np.complex128 for complex dtypes, np.float64 otherwise.)np
issubdtypecomplexfloating
complex128float64dtypes    l/var/www/html/mdtn/previsions/meteo_cartes/venv/lib/python3.11/site-packages/scipy/interpolate/_ndbspline.py
_get_dtyper      s)    	}UB.// }z    TF)z
dask.arrayz7https://github.com/data-apis/array-api-extra/issues/488)cpu_onlyjax_jitskip_backendsc                       e Zd ZdZ ee          ZdddZed             Z	ed             Z
ed             Zdddd	Zedd            ZddZd ZdS )r   a  Tensor product spline object.

    The value at point ``xp = (x1, x2, ..., xN)`` is evaluated as a linear
    combination of products of one-dimensional b-splines in each of the ``N``
    dimensions::

       c[i1, i2, ..., iN] * B(x1; i1, t1) * B(x2; i2, t2) * ... * B(xN; iN, tN)


    Here ``B(x; i, t)`` is the ``i``-th b-spline defined by the knot vector
    ``t`` evaluated at ``x``.

    Parameters
    ----------
    t : tuple of 1D ndarrays
        knot vectors in directions 1, 2, ... N,
        ``len(t[i]) == n[i] + k + 1``
    c : ndarray, shape (n1, n2, ..., nN, ...)
        b-spline coefficients
    k : int or length-d tuple of integers
        spline degrees.
        A single integer is interpreted as having this degree for
        all dimensions.
    extrapolate : bool, optional
        Whether to extrapolate out-of-bounds inputs, or return `nan`.
        Default is to extrapolate.

    Attributes
    ----------
    t : tuple of ndarrays
        Knots vectors.
    c : ndarray
        Coefficients of the tensor-product spline.
    k : tuple of integers
        Degrees for each dimension.
    extrapolate : bool, optional
        Whether to extrapolate or return nans for out-of-bounds inputs.
        Defaults to true.

    Methods
    -------
    __call__
    derivative
    design_matrix

    See Also
    --------
    BSpline : a one-dimensional B-spline object
    NdPPoly : an N-dimensional piecewise tensor product polynomial

    Nextrapolatec                   t          ||          \  | _        | _        \  | _        | _        t          |g|R  j        | _        |d}t          |          | _	        t          j        |          | _        | j        j        d         }| j        j        |k     rt          d| d          t          |          D ]}| j        |         }| j        |         }|j        d         |z
  dz
  }	| j        j        |         |	k    r<t          d| d| j        j        |          dt%          |           d	|	 d
| d          t'          | j        j                  }
t          j        | j        |
          | _        d S )NTr   zCoefficients must be at least z-dimensional.r   z,Knots, coefficients and degree in dimension z are inconsistent: got z coefficients for z knots, need at least z for k=.r   )_preprocess_inputs_k_indices_k1d_t_len_tr   asarray_asarrayboolr   r   _cshapendim
ValueErrorrangetklenr   r   ascontiguousarray)selfr-   cr.   r   r*   dtdkdndts              r   __init__zNdBSpline.__init__[   s   =OPQST=U=U:"$:TWdk'.A...6K,,*Q--w}Q7<$QdQQQRRRt 
	- 
	-ABBb 1$Aw}Q1$$  ",%&", ",)-q)9", ", &)WW", ", EF", ", ()	", ", ", - - - % &&&twb999r   c                 *    t          | j                  S N)tupler!   r1   s    r   r.   zNdBSpline.ky   s    TW~~r   c                 t     t           fdt           j        j        d                   D                       S )Nc              3   v   K   | ]3}                     j        |d j        |         f                   V  4d S r:   )r&   r#   r$   .0r3   r1   s     r   	<genexpr>zNdBSpline.t.<locals>.<genexpr>   sV       
 
;<DMM$'!_dk!n_"4566
 
 
 
 
 
r   r   )r;   r,   r#   r)   r<   s   `r   r-   zNdBSpline.t}   sO      
 
 
 
@EdgmTUFV@W@W
 
 
 
 
 	
r   c                 6    |                      | j                  S r:   )r&   r(   r<   s    r   r2   zNdBSpline.c   s    }}TW%%%r   )nur   c                ^   | j         j        d         }|| j        }t          |          }|"t	          j        |ft          j                  }nt	          j        |t          j                  }|j        dk    s|j        d         |k    r(t          d|dt          | j                   d          t          |dk               rt          d|          t	          j        |t                    }|j        }|                    d	|d	                   }t	          j        |          }|d	         |k    rt          d
| d|           | j        j        j        dk    }| j        }|r| j        j        |k    r| j        d         }|                    t                    }|                    |j        d|         dz                                             }t	          j        fdj        D             t          j                  }	j        d	         }
t-          j        || j         | j        | j        ||||
|	| j        
  
        }|                    | j        j                  }|                    |dd	         | j        j        |d         z             }|                     |          S )aB  Evaluate the tensor product b-spline at ``xi``.

        Parameters
        ----------
        xi : array_like, shape(..., ndim)
            The coordinates to evaluate the interpolator at.
            This can be a list or tuple of ndim-dimensional points
            or an array with the shape (num_points, ndim).
        nu : sequence of length ``ndim``, optional
            Orders of derivatives to evaluate. Each must be non-negative.
            Defaults to the zeroth derivivative.
        extrapolate : bool, optional
            Whether to exrapolate based on first and last intervals in each
            dimension, or return `nan`. Default is to ``self.extrapolate``.

        Returns
        -------
        values : ndarray, shape ``xi.shape[:-1] + self.c.shape[ndim:]``
            Interpolated values at ``xi``
        r   Nr   r   )invalid number of derivative orders nu =  for ndim = r   z'derivatives must be positive, got nu = zShapes: xi.shape=z
 and ndim=r2   ).N)rG   c                 .    g | ]}|j         j        z  S  )r   itemsize)r@   sc1s     r   
<listcomp>z&NdBSpline.__call__.<locals>.<listcomp>   s3     "7 "7 "7&' #$rx'8"8 "7 "7 "7r   )r#   r)   r   r'   r   zerosint64r%   r*   r+   r/   r-   anyfloatreshaper0   r(   r   kindviewravelstridesr   evaluate_ndbspliner$   r!   r"   r&   )r1   xirC   r   r*   xi_shapewas_complexccc1r_strides_c1num_c_troutrL   s               @r   __call__zNdBSpline.__call__   s   * w}Q*K;'':4'222BBBbh///Bw!||rx{d22 -2 - -!$&kk- - -. . . 26{{ O !Mb!M!MNNN Z%(((8ZZHRL))!"%%B<4KKKTKKLLL gm(C/W 	$47<4// #BWWU^^ ZZ$%/00hhjj j "7 "7 "7 "7+-:"7 "7 "7>@hH H H 8B<)"!%!%!%!#!,!$!)!,!%!2

 

 hhtw}%%kk(3B3-$'-*>>??}}S!!!r   Tc                 B   t          j        |t                    }|j        d         }t	          |          |k    r#t          dt	          |           d|d          t          |          \  }\  }t          fdt          |          D                       }|dd         d	z   }	t          j	        |	ddd         t           j
                  ddd                                         }
t          j        ||||
          \  }}}t          |||f          S )
a  Construct the design matrix as a CSR format sparse array.

        Parameters
        ----------
        xvals :  ndarray, shape(npts, ndim)
            Data points. ``xvals[j, :]`` gives the ``j``-th data point as an
            ``ndim``-dimensional array.
        t : tuple of 1D ndarrays, length-ndim
            Knot vectors in directions 1, 2, ... ndim,
        k : int
            B-spline degree.
        extrapolate : bool, optional
            Whether to extrapolate out-of-bounds values of raise a `ValueError`

        Returns
        -------
        design_matrix : a CSR array
            Each row of the design matrix corresponds to a value in `xvals` and
            contains values of b-spline basis elements which are non-zero
            at this value.

        r   rG   z*Data and knots are inconsistent: len(t) = z for  ndim = r   c              3   @   K   | ]}|         |         z
  d z
  V  dS r   NrI   )r@   r3   r.   len_ts     r   rA   z*NdBSpline.design_matrix.<locals>.<genexpr>   s4      AAa1Q4!+AAAAAAr   r   Nr   )r   r%   rQ   r)   r/   r+   r    r;   r,   cumprodrO   copyr   	_coloc_ndr   )clsxvalsr-   r.   r   r*   r"   r#   c_shapecscstridesdataindicesindptrrd   s      `          @r   design_matrixzNdBSpline.design_matrix   sB   0 
5...{2q66T>>SVV       (:!Q'?'?$<"e
 AAAAAU4[[AAAAA QRR[4:b2hbh777"=BBDD !) 25E1lH!6 !6gv $0111r   r   c           	         t          j        ||d          }|j        d         }|j        dd          }|                    |d          }g }	d }
t	          |j        d                   D ]}||k    rgt          j        ||d d |f         |          }|                    |          }|j        d t          |j
                  |j        z
  dz
           |_        n8t          j        |t          j        t          |          dz
            d          }|
|j
        }
|	                    |j                   t          j        |	d                              t          |	d                   f|z             }t          j        |d|          }||
fS )Nr   r   rG   )axis)r   moveaxisr)   rR   r,   r   construct_fast
derivativer2   r/   r-   r.   rN   appendstack)r1   r2   r-   r.   rs   rC   r6   trailing_shapec_flat
new_c_listnew_tibdbnew_cs                  r   _bspline_derivative_along_axisz(NdBSpline._bspline_derivative_along_axis  sr   K4##GAJ1b!!
v|A'' 	$ 	$ABww*1fQQQTlA>>\\"%%t1SYY-112+ArxA
/C/CQGG}bd####!,,,44A!N24 4E1d++e|r   c                 X    t          j        |t           j                  }t           j                  }|j        dk    s|j        d         |k    r(t          d|dt           j                   d          t          |dk               rt          d|           fdt           j
        j        d                   D             }t           j                  } j                                        }t          |          D ]T\  }}|dk    r                     |||         ||         ||	          \  }||<   t#          ||         |z
  d          ||<   Ut%          t'           fd
|D                                            |          t'          |           j                  S )a{  
        Construct a new NdBSpline representing the partial derivative.

        Parameters
        ----------
        nu : array_like of shape (ndim,)
            Orders of the partial derivatives to compute along each dimension.

        Returns
        -------
        NdBSpline
            A new NdBSpline representing the partial derivative of the original spline.

        r   r   r   rE   rF   r   z-derivative orders must be positive, got nu = c                 H    g | ]}j         |d j        |         f         S r:   )r#   r$   r?   s     r   rM   z(NdBSpline.derivative.<locals>.<listcomp>D  s/    NNNOT[^O+,NNNr   )rC   c              3   B   K   | ]}                     |          V  d S r:   )r&   )r@   r-   r1   s     r   rA   z'NdBSpline.derivative.<locals>.<genexpr>Q  s/      ??At}}Q//??????r   r   )r   r%   rO   r/   r-   r*   r)   r+   rP   r,   r#   listr.   r(   rg   	enumerater   maxr   r;   r&   r   )	r1   rC   nu_arrr*   t_newk_newc_newrs   r6   s	   `        r   rv   zNdBSpline.derivative)  s    Bbh///46{{;!v|A$66)r ) )df++) ) )* * * vz?? 	QOOOPPP ONNNeDGM!<L6M6MNNNTV (( 	2 	2GD!Avv!%!D!DuT{E$K! "E " "E5; eDkAoq11E$KK?????????u--u%)%5
 
 
 	
r   )Tre   )__name__
__module____qualname____doc__classmethodr   __class_getitem__r8   propertyr.   r-   r2   r`   rq   r   rv   rI   r   r   r   r      s       2 2j $L11/3 : : : : :<   X 
 
 X
 & & X& "&4 N" N" N" N" N"` 02 02 02 [02d   <,
 ,
 ,
 ,
 ,
r   c           
         t          |t                    st          d| d          t          |          }	 t          |            n# t          $ r	 | f|z  } Y nw xY wt          j        d | D             t
          j                  } t          |           |k    r0t          dt          |           dt          |           d          t          |          }t          |          D ]P}t          j        ||                   }| |         }|j	        d         |z
  d	z
  }|dk     rt          d
| d          |j
        d	k    rt          d| d          ||d	z   k     rt          dd|z  dz    d| d| d          t          j        |          dk                                     rt          d| d          t          t          j        |||d	z                                dk     rt          d| d          t          j        |                                          st          d| d          Rt          d | D                       }t          j        t          j        t%          |                    |          }t          j        |t
          j                  j                                        }	d |D             }t          |          }d |D             }
t          j        |t-          |
          ft.                    }|                    t
          j                   t          |          D ]$}||         ||dt          ||                   f<   %t          j        |
t
          j                  }
| |	||
ffS )zHelpers: validate and preprocess NdBSpline inputs.

       Parameters
       ----------
       k : int or tuple
          Spline orders
       t_tpl : tuple or array-likes
          Knots.
    z-Expect `t` to be a tuple of array-likes. Got z	 instead.c                 6    g | ]}t          j        |          S rI   )operatorindex)r@   kis     r   rM   z&_preprocess_inputs.<locals>.<listcomp>o  s"    3332HN2&&333r   r   z	len(t) = z != len(k) = r   r   r   zSpline degree in dimension z cannot be negative.zKnot vector in dimension z must be one-dimensional.zNeed at least    z knots for degree z in dimension zKnots in dimension z# must be in a non-decreasing order.z.Need at least two internal knots in dimension z should not have nans or infs.c              3       K   | ]	}|d z   V  
dS rc   rI   )r@   r5   s     r   rA   z%_preprocess_inputs.<locals>.<genexpr>  s&      %%R"q&%%%%%%r   c                 6    g | ]}t          j        |          S rI   )r   r%   )r@   r-   s     r   rM   z&_preprocess_inputs.<locals>.<listcomp>  s     ***qRZ]]***r   c                 ,    g | ]}t          |          S rI   r/   )r@   tis     r   rM   z&_preprocess_inputs.<locals>.<listcomp>  s    %%%SWW%%%r   N)
isinstancer;   r+   r/   	TypeErrorr   r%   rO   r,   r)   r*   diffrP   uniqueisfiniteallunravel_indexaranger   Trg   emptyr   rQ   fillnan)r.   t_tplr*   r3   r4   r5   r6   r)   ro   r"   rd   r#   s               r   r    r    W  s    eU## 
 1 %1 1 1 
 
 	

 u::DA   DI 	
3333328DDDA
1vv~~ASZZAASVVAAABBB u::D4[[ 0 0Za!!qTHQK"q 66 +1 + + + , , ,7a<< 2 2 2 2 3 3 3rAv:: 8adQh 8 8!#8 8348 8 8 9 9 9GBKK!O  "" 	8 71 7 7 7 8 8 8ryBq1uH&&''!++ 0+,0 0 0 1 1 1{2""$$ 	0 /1 / / / 0 0 0	0 %%1%%%%%Erye55u==G:gRX6668==??L +*E***Eu::D%%u%%%E	4U$E	2	2	2BGGBFOOO4[[ ) ) %a1ns58}}nJuBH---ElRK''s   A	 	AAc           
         t          j        |j        t           j                  r0t	          | |j        |fi |}t	          | |j        |fi |}|d|z  z   S |j        dk    r|j        d         dk    rpt          j	        |          }t          |j        d                   D ]?} || |d d |f         fi |\  |d d |f<   }|dk    rt          d|d|d| d          @|S  || |fi |\  }}|dk    rt          d|d	|d          |S )
Ny              ?r   r   r   z	solver = z returns info =z for column r   z returns info = )r   r   r   r   _iter_solverealimagr*   r)   
empty_liker,   r+   )	ar~   solversolver_argsr   r   resjinfos	            r   r   r     sg   
 
}QWb011 1aff<<<<1aff<<<<bg~v{{qwqzA~~mAqwqz"" 	R 	RA$fQ!!!Q$??;??OC1Itqyy !PF!P!P!P!PA!P!P!PQQQ 
F1a//;//	T199>>>D>>>???
r      r   c                    t                     }t          d  D                       }	 t                     n# t          $ r	 f|z  Y nw xY wt                     D ]]\  }}t          t	          j        |                    }	|	|         k    r+t          d|	 d| d|          d|         dz    d	          ^t           fdt          |          D                       }
t	          j        d	 t          j
          D             t          
          }t                              ||
          }d         dk    r|                                 |j        }t!          |d|                   t!          ||d                   f}|                    |          }|t$          j        k    r$t)          j        t,          |          }d|vrd|d<    |||fi |}|                    |||d         z             }t          |
|          S )a  Construct an interpolating NdBspline.

    Parameters
    ----------
    points : tuple of ndarrays of float, with shapes (m1,), ... (mN,)
        The points defining the regular grid in N dimensions. The points in
        each dimension (i.e. every element of the `points` tuple) must be
        strictly ascending or descending.
    values : ndarray of float, shape (m1, ..., mN, ...)
        The data on the regular grid in n dimensions.
    k : int, optional
        The spline degree. Must be odd. Default is cubic, k=3
    solver : a `scipy.sparse.linalg` solver (iterative or direct), optional.
        An iterative solver from `scipy.sparse.linalg` or a direct one,
        `sparse.sparse.linalg.spsolve`.
        Used to solve the sparse linear system
        ``design_matrix @ coefficients = rhs`` for the coefficients.
        Default is `scipy.sparse.linalg.gcrotmk`
    solver_args : dict, optional
        Additional arguments for the solver. The call signature is
        ``solver(csr_array, rhs_vector, **solver_args)``

    Returns
    -------
    spl : NdBSpline object

    Notes
    -----
    Boundary conditions are not-a-knot in all dimensions.
    c              3   4   K   | ]}t          |          V  d S r:   r   )r@   xs     r   rA   zmake_ndbspl.<locals>.<genexpr>  s(      ,,SVV,,,,,,r   z
There are z points in dimension z, but order z requires at least  r   z points per dimension.c              3      K   | ]9}t          t          j        |         t                     |                   V  :dS )r   N)r
   r   r%   rQ   )r@   r3   r.   pointss     r   rA   zmake_ndbspl.<locals>.<genexpr>  sX       $ $ "*VAYe<<<adCC $ $ $ $ $ $r   c                     g | ]}|S rI   rI   )r@   xvs     r   rM   zmake_ndbspl.<locals>.<listcomp>  s    @@@r@@@r   r   r   r   Nr   atolgư>)r/   r;   r   r   r   
atleast_1dr+   r,   r%   	itertoolsproductrQ   r   rq   eliminate_zerosr)   r   rR   sslspsolve	functoolspartialr   )r   valuesr.   r   r   r*   rY   r3   pointnumptsr-   rj   matrv_shape
vals_shapevalscoefs   ` `              r   make_ndbsplr     s   > v;;D,,V,,,,,HA   DI f%% A A5R]5))**QqT>> @& @ @q @ @+,Q4@ @!"1a@ @ @ A A A 
 	 $ $ $ $ $T{{$ $ $ 	$ 	$AJ@@Y%6%?@@@NNNE ""5!Q//D 	tqyy
 lGwuu~&&WTUU^(<(<=J>>*%%D";v>>>$$"&K6$,,,,D<<7455>122DQa   s   < AA)r   )r   r   r   numpyr   mathr   typesr    r   scipy.sparse.linalgsparselinalgr   scipy.sparser   scipy._lib._array_apir   r	   	_bsplinesr
   r   __all__r   r   r    gcrotmkr   r   rI   r   r   <module>r      s                                  ! ! ! ! ! ! ! ! ! " " " " " " B B B B B B B B + + + + + + + +-   5	D  r
 r
 r
 r
 r
 r
 r
 r
h	J( J( J(Z ![    0J!s{ J! J! J! J! J! J! J!r   