
    doi                        S r SSKrSSKrSSKrSSKJrJrJr  SSK	J
r
JrJrJrJrJrJr  SSKJr  SrSrS(S
 jrS rS rS(S jr\" SS	SS9SSSSSSSS.S j5       r\4S jrS rS r " S S5      r " S S5      rS r " S S5      r Sr!\!S-   \!S-   S S!.r"S" r#\4S# jr$\" SS	SS9SSSSSSSSS$.S% j5       r%\" SS	SS9SSSSSSSSSS&.	S' j5       r&g))a  Replicate FITPACK's logic for constructing smoothing spline functions and curves.

Currently provides analogs of splrep and splprep python routines, i.e.
curfit.f and parcur.f routines (the drivers are fpcurf.f and fppara.f, respectively)

The Fortran sources are from
https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/

.. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
    parametric splines, Computer Graphics and Image Processing",
    20 (1982) 171-184.
    :doi:`10.1016/0146-664X(82)90043-0`.
.. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
     Numerical Analysis, Oxford University Press, 1993.
.. [3] P. Dierckx, "An algorithm for smoothing, differentiation and integration
     of experimental data using spline functions",
     Journal of Computational and Applied Mathematics, vol. I, no 3, p. 165 (1975).
     https://doi.org/10.1016/0771-050X(75)90034-0
    N)array_namespace	concat_1dxp_capabilities   )_not_a_knotmake_interp_splineBSplinefpcheck_lsq_solve_qr$_lsq_solve_qr_for_root_rati_periodic_periodic_knots)_dierckxgMbP?   Fc           	          [        XX#XES9u      pgn[        R                  " UR                  5       5      (       a  [	        [
        S   5      eX4$ )Nperiodicr   )r   npisnansum
ValueError_iermesg)	xytkwr   _fp	residualss	            \/var/www/html/land-ocr/venv/lib/python3.13/site-packages/scipy/interpolate/_fitpack_repro.py_get_residualsr!   -   sG     +1qLAq!	xx	  !%%=    c                 6    U c  gU S;  a  [        SU  35      eU $ )N
not-a-knot)r$   r   zKOnly 'not-a-knot' and 'periodic' boundary conditions are recognised, found )r   )bc_types    r    _validate_bc_typer&   >   s6    00 ""), - 	- Nr"   c                     [         R                  " XX#5      n[        R                  " X5      n[        R                  USU XAUS 4   nU$ )aF  Add a new knot.

(Approximately) replicate FITPACK's logic:
  1. split the `x` array into knot intervals, ``t(j+k) <= x(i) <= t(j+k+1)``
  2. find the interval with the maximum sum of residuals
  3. insert a new knot into the middle of that interval.

NB: a new knot is in fact an `x` value at the middle of the interval.
So *the knots are a subset of `x`*.

This routine is an analog of
https://github.com/scipy/scipy/blob/v1.11.4/scipy/interpolate/fitpack/fpcurf.f#L190-L215
(cf _split function)

and https://github.com/scipy/scipy/blob/v1.11.4/scipy/interpolate/fitpack/fpknot.f
N)r   fpknotr   searchsortedr_)r   r   r   r   new_knotidx_tt_news          r    add_knotr.   J   sF    " qQ2HOOA(EEE!FU)Xy01ELr"   c	                    [         R                  " U [        S9n [         R                  " U[        S9nU R                  R                  (       d  U R                  5       n UR                  R                  (       d  UR                  5       nUc  [         R                  " U [        S9nO[         R                  " U[        S9nUR                  R                  (       d  UR                  5       nUR                  S:w  a  [        SUR                  < S35      eUS:  R                  5       (       a  [        S5      eUR                  5       S:X  a  [        S5      eUR                  S:X  d  UR                  S	:  a  [        S
UR                  < S35      e[        U5      nU(       a/  UR                  S	:w  a  [        S
UR                  < SU< S35      eO7UR                  S:w  a  [        S
UR                  < SU< S35      eUSS2S4   nUR                  S   U R                  S   :w  a'  [        SUR                  < SU R                   S35      eU R                  S   UR                  S   :w  a(  [        SU R                  < SUR                  < S35      eU R                  S:w  d  U SS U SS :  R                  5       (       a  [        S5      e[        R                  " U5      nUS:  a  [        SU< 35      eUc  [        U 5      nUc  [!        U 5      nU(       a,  [         R"                  " US   US   SS9(       d  [        S5      eXX#XEU4$ )zACommon input validations for generate_knots and make_splrep.
    dtypeNr   	w.ndim = z not implemented yet.r   zWeights must be non-negativezAll weights are zero.   z	y.ndim = z  not supported (must be 1 or 2.)z% != 2 not supported with parametric =.z% != 1 not supported with parametric =z"Weights is incompatible: w.shape =z != z Data is incompatible: x.shape = z and y.shape = z(Expect `x` to be an ordered 1D sequence.z"`s` must be non-negative. Got s = gV瞯<)atolzPFirst and last points does not match which is required for `bc_type='periodic'`.)r   asarrayfloatflagsc_contiguouscopy	ones_likendimr   anyr   boolshapeoperatorindexminmaxallclose)	r   r   r   r   sxbxe
parametricr   s	            r    _validate_inputsrJ   b   s    	

1E"A


1E"A77FFH77FFHyLL%(JJq&ww##A66Q;	{*?@AAE;;==;<<557a<455 	vv{affqjIAFF;&FGHHj!J66Q;	{*PJ>QRSTT  66Q;	{*PJ>QRSTTagJwwqzQWWQZ>QWWKtAGG9ANOOwwqzQWWQZ<!''=M177,aPQQvv{quq"v~**,,CDDqA1u>!@AA	zV	zVAaD!B%e< 5 6 	6 qb  r"   T)cpu_onlyjax_jitallow_dask_compute   )r   rG   rH   r   rF   nestr%   c             #   d  #    [        XU5      n	[        U5      nUS:H  n
US:X  aI  Uc  Ub  [        S5      eU
(       a  US:  a  [        X5      nO[	        X5      nU	R                  U5      v   g[        XX%XcU[        R                  " U5      S:H  U
S9	u  pp%pcn[        XX#XEXgXS9
 Sh  vN   g N7f)	a  Generate knot vectors until the Least SQuares (LSQ) criterion is satified.

Parameters
----------
x, y : array_like
    The data points defining the curve ``y = f(x)``.
w : array_like, optional
    Weights.
xb : float, optional
    The boundary of the approximation interval. If None (default),
    is set to ``x[0]``.
xe : float, optional
    The boundary of the approximation interval. If None (default),
    is set to ``x[-1]``.
k : int, optional
    The spline degree. Default is cubic, ``k = 3``.
s : float, optional
    The smoothing factor. Default is ``s = 0``.
nest : int, optional
    Stop when at least this many knots are placed.
      ends are equivalent.
bc_type : str, optional
    Boundary conditions.
    Default is `"not-a-knot"`.
    The following boundary conditions are recognized:

    * ``"not-a-knot"`` (default): The first and second segments are the
      same polynomial. This is equivalent to having ``bc_type=None``.
    * ``"periodic"``: The values and the first ``k-1`` derivatives at the
      ends are equivalent.

Yields
------
t : ndarray
    Knot vectors with an increasing number of knots.
    The generator is finite: it stops when the smoothing critetion is
    satisfied, or when then number of knots exceeds the maximum value:
    the user-provided `nest` or `x.size + k + 1` --- which is the knot vector
    for the interpolating spline.

Examples
--------
Generate some noisy data and fit a sequence of LSQ splines:

>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy.interpolate import make_lsq_spline, generate_knots
>>> rng = np.random.default_rng(12345)
>>> x = np.linspace(-3, 3, 50)
>>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(size=50)

>>> knots = list(generate_knots(x, y, s=1e-10))
>>> for t in knots[::3]:
...     spl = make_lsq_spline(x, y, t)
...     xs = xs = np.linspace(-3, 3, 201)
...     plt.plot(xs, spl(xs), '-', label=f'n = {len(t)}', lw=3, alpha=0.7)
>>> plt.plot(x, y, 'o', label='data')
>>> plt.plot(xs, np.exp(-xs**2), '--')
>>> plt.legend()

Note that increasing the number of knots make the result follow the data
more and more closely.

Also note that a step of the generator may add multiple knots:

>>> [len(t) for t in knots]
[8, 9, 10, 12, 16, 24, 40, 48, 52, 54]

Notes
-----
The routine generates successive knots vectors of increasing length, starting
from ``2*(k+1)`` to ``len(x) + k + 1``, trying to make knots more dense
in the regions where the deviation of the LSQ spline from data is large.

When the maximum number of knots, ``len(x) + k + 1`` is reached
(this happens when ``s`` is small and ``nest`` is large), the generator
stops, and the last output is the knots for the interpolation with the
not-a-knot boundary condition.

Knots are located at data sites, unless ``k`` is even and the number of knots
is ``len(x) + k + 1``. In that case, the last output of the generator
has internal knots at Greville sites, ``(x[1:] + x[:-1]) / 2``.

.. versionadded:: 1.15.0

r   r   Nzs == 0 is interpolation onlyr   r3   rI   r   xp)
r   r&   r   r   r   r7   rJ   r   r=   _generate_knots_impl)r   r   r   rG   rH   r   rF   rO   r%   rS   r   r   s               r    generate_knotsrU      s     r 
q	!B(G*$HAvq};<< A%AA!Ajjm,	aA2"''!*/A!r
 $A!QQQs   B&B0(B.)B0c
              #   v  #    U[         -  n
U R                  nUc8  U(       a  [        USU-  -   SU-  S-   5      nO=[        X-   S-   SU-  S-   5      nO%USUS-   -  :  a  [        SU< SSUS-   -   S35      eU(       d  SUS-   -  nX-   S-   nOSUS-   -  nUSU-  -   nXC-
  nU(       ax  [        R
                  " U[        S9n[        SUS-   5       H*  nU S   UU-
  U-  -
  UU'   XS-
     UU-  -   UUU-   S-   '   M,     [        XXX(S	9u  nnUU-
  U
:  d  X:X  a  Uv   g OS
nS
nU(       d+  [        R                  " U/US-   -  U/US-   -  -   [        S9nO3[        R
                  " SU-  S-   [        S9nXS-   S-  S-
     XS-   '   SnUR                  S   n[        U5       GH  nU(       a_  UR                  S   nX?U'   XOUU-
  S-
  '   [        SUS-   5       H/  nUUU-
  U-
  S-
     U-
  XU-
  '   XU-      U-   UUU-
  U-   S-
  '   M1     U	R                  U5      v   Un[        XXUUS9u  nnUU-
  n[        U5      U
:  d  US:  a    g UU:X  a  SnO>UU-
  nUU
:  a  [        WU-  U-  5      OWS-  n[        US-  [        UUS-  S5      5      n[        U5       H  n[        XUU5      nUR                  S   nUU:  a4  U(       d  [        X5      nO[!        X5      nU	R                  U5      v       g UU:  a  U	R                  U5      v       g UUS-
  :  d  M  [        XXX(S9u  nnM     GM     g 7f)Nr3   rN   r   `nest` too small: nest =  < 2*(k+1) = r4   r0   r   r           )r   r   )TOLsizerD   r   r   zerosr8   ranger!   r7   r@   absintrC   r.   r   r   )r   r   r   rG   rH   r   rF   rO   r   rS   accmnminnmaxperr   ir   r   fpoldnplusniterjr   fpmsdeltanpl1s                               r    rT   rT     s    
c'C	A| q1Q3w!a(Dquqy!A#'*D!QU)9$-1Q3yPQRSS!a%yuqy !a%y1Q3w
'C HHT'q!a%AQ41q5C-'AaDU8a#g-Aa!eaiL ! qQ1@2 6C<4<G (  JJtQqSzRD!A#J.e< HHQqS1WE*!eaZ!^$a%	
A a
AaDa!eaiL1a!e_QUQY]+c1a%#$U8c>!a%!)a-  % jjm &qQQ19;	2Av IO
 9EBJE053ut|e+,qDaT5!8Q!78E uAq),A 
A Dy#A)A'-Ajjm# Dyjjm# 519}-aAAQ	11 E z s   LL9!L9c                 f    Sn[        US-   5       H  nX-   U:w  d  M  X@U   XU-      -
  -  nM     U$ )Ng      ?r3   )r]   )r   re   rj   r   resrF   s         r    proddrp     s?    
C1Q3Z5A:aD1qS6M"C  Jr"   c           	         U R                   S   nXU-
  S-
     X   -
  nUSU-  -
  S-
  n[        R                  " US-
  US-   4[        S9n[	        US-
  5       HC  nXa-   S-   n[	        US-   5       H'  nXh-   n	X	U-   S-      X	   -
  [        X	Xq5      -  XVU4'   M)     ME     XSU-  U-  -  n[        R                  " [	        US-
  5       V	s/ s H  oPM     sn	[        R                  S9n
X!-
  S-
  nXZU4$ s  sn	f )a  Discontinuity matrix: jumps of k-th derivatives of b-splines at internal knots.

See Eqs. (9)-(10) of Ref. [1], or, equivalently, Eq. (3.43) of Ref. [2].

This routine assumes internal knots are all simple (have multiplicity =1).

Parameters
----------
t : ndarray, 1D, shape(n,)
    Knots.
k : int
    The spline degree

Returns
-------
disc : ndarray, shape(n-2*k-1, k+2)
    The jumps of the k-th derivatives of b-splines at internal knots,
    ``t[k+1], ...., t[n-k-1]``.
offset : ndarray, shape(2-2*k-1,)
    Offsets
nc : int

Notes
-----

The normalization here follows FITPACK:
(https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpdisc.f#L36)

The k-th derivative jumps are multiplied by a factor::

    (delta / nrint)**k / k!

where ``delta`` is the length of the interval spanned by internal knots, and
``nrint`` is one less the number of internal knots (i.e., the number of
subintervals between them).

References
----------
.. [1] Paul Dierckx, Algorithms for smoothing data with periodic and parametric
       splines, Computer Graphics and Image Processing, vol. 20, p. 171 (1982).
       :doi:`10.1016/0146-664X(82)90043-0`

.. [2] Tom Lyche and Knut Morken, Spline methods,
    http://www.uio.no/studier/emner/matnat/ifi/INF-MAT5340/v05/undervisningsmateriale/

r   r   r3   r0   )r@   r   emptyr8   r]   rp   arrayint64)r   r   rh   rl   nrintmatrjjrj   iire   offsetncs               r    discr{     s   ^ 	

A !eaiL14E!GaKE88UQYA&e4DEAIFQJA,BA!eaiL14/5q3DDDRL   	E\AD XX%a.1.Qq.1BF	
B 2s   
C4c                   2    \ rS rSrSrSSSS.S jjrS rSrg)	Fi   aH  The r.h.s. of ``f(p) = s``.

Given scalar `p`, we solve the system of equations in the LSQ sense:

    | A     |  @ | c | = | y |
    | B / p |    | 0 |   | 0 |

where `A` is the matrix of b-splines and `b` is the discontinuity matrix
(the jumps of the k-th derivatives of b-spline basis elements at knots).

Since we do that repeatedly while minimizing over `p`, we QR-factorize
`A` only once and update the QR factorization only of the `B` rows of the
augmented matrix |A, B/p|.

The system of equations is Eq. (15) Ref. [1]_, the strategy and implementation
follows that of FITPACK, see specific links below.

References
----------
[1] P. Dierckx, Algorithms for Smoothing Data with Periodic and Parametric Splines,
    COMPUTER GRAPHICS AND IMAGE PROCESSING vol. 20, pp 171-184 (1982.)
    https://doi.org/10.1016/0146-664X(82)90043-0

N)RYc                   Xl         X l        X0l        X@l        Uc  [        R
                  " U[        S9OUnUR                  S:w  a  [        SUR                  < S35      eX`l	        XPl
        UR                  S:w  a  [        SUR                  < S35      e[        X45      u  pnUc  Uc  [        XX4U5      u  px    nUR                  S   U-
  S-
  nUS-   nUR                  S   U:w  a$  [        S	UR                  S   < S
US-   < S35      e[        R                  " U	R                  S   UR                  S   4[        S9n[        R                  US U U4   U l        [        R                  " XR                  S   -   U R                  S-   4[        S9nUS U2S S 24   US U2S U24'   UU l        [        R                  [        R$                  " U[        R&                  S9U
4   U l        Xl        Xl        g )Nr0   r   r2    != 1.r3   &F: expected y.ndim == 2, got y.ndim = 	 instead.r   zInternal error: R.shape[1] =z	 != k+1 =r4   )r   r   r   r   r   r<   r8   r=   r   r   rF   r{   r   r@   r\   r*   YYAAarangert   ry   rz   b)selfr   r   r   r   rF   r   r~   r   r   b_offsetb_ncr   rz   nzzr   s                    r    __init__
F.__init__  s   ,-IBLL%(166Q;	{&12266Q;FQVVKyQRR !JT 9)!a8MA!Q WWQZ!^aU771:<
~Z!A#JKK HHaggaj!''!*-U;%%#2	" XXrGGAJq1?"ay3B38eeBIIb98CDr"   c           
         U R                   R                  5       nU R                  R                  5       nU R                  nU R                  U-  X$S 2S S 24'   U R
                  R                  5       n[        R                  " X#XEUS9  [        R                  " X$U R                  U R                  U R                  U R                  U R                  U5      u  pgn[        U R                  X`R                  5      n	Xl        XR                   -
  $ )N)startrow)r   r;   ry   rz   r   r   r   	qr_reducefpbackr   r   r   r   r   r	   splrF   )
r   pABry   rz   QYcr   r   r   s
             r    __call__
F.__call__J  s     WW\\^!!#WWVVaZ36
WW\\^ 	2r; ??2466466466466466SUVbdffa(FF{r"   )r   r   r   r   rz   ry   rF   r   r   r   r   r   N__name__
__module____qualname____firstlineno____doc__r   r   __static_attributes__ r"   r    r}   r}      s    0/44 /br"   r}   c                   8    \ rS rSrSrSSSSSSS.S jjrS rSrg)		Fperiodicib  a	  
Fit a smooth periodic B-spline curve to given data points.

This class fits a periodic B-spline curve S(t) of degree k through data points
(x, y) with knots t. The spline is smooth and repeats itself at the start and
end, meaning the function and its derivatives up to order k-1 are equal
at the boundaries.

We want to find spline coefficients c that minimize the difference between
the spline and the data, while also keeping the spline smooth. This is done
by solving:

    minimize || W^{1/2} (Y - B c) ||^2 + s * c^T @ R @ c
    subject to periodic constraints on c.

where:
  - Y is the data values,
  - B is the matrix of B-spline basis functions at points x,
  - W is a weighting matrix for the data points,
  - s is the smoothing parameter (larger s means smoother curve),
  - R is a matrix that penalizes wiggliness of the spline,
  - c spline coefficients to be solved for
  - periodic constraints ensure the spline repeats smoothly.

The solution is obtained by forming augmented matrices and performing
a QR factorization that incorporates these constraints, following the
approach in FITPACK's `fpperi.f`.

Parameters:
-----------
x : array_like, shape (n,)
y : array_like, shape (n, m)
t : array_like, shape (nt,)
    Knot vector for the spline
k : int
    Degree of the spline.
s : float
    Controls smoothness: bigger s means smoother curve, smaller s fits data closer.
w : array_like, shape (n,), optional
    Weights for data points. Defaults to all ones.
R, Y, A1, A2, Z : arrays, optional
    Precomputed matrices from least squares and QR factorization steps to speed up
    repeated fits with the same knots and data.

Attributes:
-----------
G1, G2 : arrays
    Augmented matrices combining the original QR factors and constraints related to
    the spline basis and data. G1 is roughly the "upper-triangular" part;
    G2 contains additional constraint information for periodicity.

H1, H2 : arrays
    Matrices associated with the discontinuity jump constraints of the k-th
    derivative of B-splines at the knots. These encode the periodicity
    conditions and are scaled by the smoothing parameter.

offset : array
    Offset indices used for efficient indexing during QR reduction.

Methods:
--------
__call__(p):
    Perform QR reduction of augmented matrices scaled by 1/p, solve for spline
    coefficients, and return residual difference fp - s.

References:
-----------
- FITPACK's fpperi.f and fpcurf.f Fortran routines for periodic spline fitting.
N)r~   r   A1A2Zc                4   Xl         X l        X0l        X@l        Uc  [        R
                  " U[        S9OUnUR                  S:w  a  [        SUR                  < S35      eX`l	        XPl
        UR                  S:w  a  [        SUR                  < S35      e[        X45      u  pnU	b  U
b	  Ub  Uc  Uc  [        XX4U5      u  pyp      n[        R                  " XU[        U5      U5      u  nnnnnUU l        UU l        UU l        UU l        Xl        UU l        g )Nr0   r   r2   r   r3   r   r   )r   r   r   r   r   r<   r8   r=   r   r   rF   r{   r   r   init_augmented_matriceslenG1_G2_H1_H2_Z_offset_)r   r   r   r   r   rF   r   r~   r   r   r   r   r   r   r   r   G1G2H1H2ry   s                        r    r   Fperiodic.__init__  s   
  -.IBLL%(166Q;	{&12266Q;FQVVKyQRR !JT
 Z2:Y19 (LaA($A2!Q1 "*!A!A"!SQRVUV!WBB r"   c                 H   U R                   R                  5       nU R                  R                  5       nU R                  R                  5       nU R                  R                  5       nU R
                  R                  5       nSU-  nXG-  nXW-  n[        R                  " [        U R                  5      U R                  -
  S-
  UR                  S   4UR                  S9nUS [        U R                  5      SU R                  -  -
  S-
  2S S 24   US [        U R                  5      SU R                  -  -
  S-
  2S S 24'   [        R                  " X#XEXR                  [        U R                  5      U R                  5        [        R                   " X#UU R                  U R                  S-   U R"                  S S U R$                  S S2S S 24   U R                  U R&                  S S 5	      u  pn
[)        U R                  XR                  5      nXl        XR,                  -
  $ )Nr   r0   r3   r5   )r   r;   r   r   r   r   r   rr   r   r   r   r@   r1   r   qr_reduce_augmented_matricesr   fpbacpr   r   r   r	   r   rF   )r   r   r   r   r   r   r   pinvr   r   r   r   s               r    r   Fperiodic.__call__  s   XX]]_XX]]_XX]]_XX]]_GGLLN sYY HHc$&&kDFF*Q.
;177K,-.Is466{QtvvX/E/I.I1.L,M
%3tvv;466!A%
%q
() 	--BA||S[$&&	B
 ??AFFDFFQJsTVVCRCF^FFDFF3BK!b dffa( FF{r"   )r   r   r   r   r   r   r   rF   r   r   r   r   r   r   r   r   r"   r    r   r   b  s$    DJ64DTT6p(r"   r   c                     XU-
  -  nX5U-
  -  nXQU-
  -  nU[         R                  :X  a  X&-  X-  -   * U-  $ X-  U-  X$-  U-  -   X-  U-  -   * X-  X'-  -   XH-  -   -  $ )a  The root of r(p) = (u*p + v) / (p + w) given three points and values,
(p1, f2), (p2, f2) and (p3, f3).

The FITPACK analog adjusts the bounds, and we do not
https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fprati.f

NB: FITPACK uses p < 0 to encode p=infinity. We just use the infinity itself.
Since the bracket is ``p1 <= p2 <= p3``, ``p3`` can be infinite (in fact,
this is what the minimizer starts with, ``p3=inf``).
)r   inf)	p1f1p2f2p3f3h1h2h3s	            r    fpratir     s     
BwB	BwB	BwB	RVV|"$$U2Xb 258+,0EFFr"   c                       \ rS rSrS rSrg)Bunchi  c                 <    U R                   R                  " S0 UD6  g )Nr   )__dict__update)r   kwargss     r    r   Bunch.__init__  s    &v&r"   r   N)r   r   r   r   r   r   r   r"   r    r   r     s    'r"   r   zerror. a theoretically impossible result was found during
the iteration process for finding a smoothing spline with
fp = s. probably causes : s too small.
z6the weighted sum of squared residuals is becoming NaN
zthere is an approximation returned but the corresponding
weighted sum of squared residuals does not satisfy the
condition abs(fp-s)/s < tol.
a7  error. the maximal number of iterations maxit (set to 20
by the program) allowed for finding a smoothing spline
with fp=s has been reached. probably causes : s too small
there is an approximation returned but the corresponding
weighted sum of squared residuals does not satisfy the
condition abs(fp-s)/s < tol.
)r   r3   rN   c           	      P   SnSnSnSu  pxUu  u  pu  pUn[        [        5       H  nX" U5      nn[        U5      U:  a  Su  nn  OUS:X  a)  UU-
  U::  a  UnUnX-  nX::  a	  X-  X-  -   nMI  US:  a  SnUS:X  a=  U
U-
  U::  a,  Un	Un
X-  nU[        R                  :w  a  X::  a	  X-  X-  -   nM  US:  a  SnU
U::  d  UU::  a  Su  nn  O%[        XUUX5      nUS:  a  UUpM  UUpM     S	u  nnUS:w  a%  [        R                  " [        [        U   5      S
S9  [        UUWUS9$ )a  Solve `f(p) = 0` using a rational function approximation.

In a nutshell, since the function f(p) is known to be monotonically decreasing, we
   - maintain the bracket (p1, f1), (p2, f2) and (p3, f3)
   - at each iteration step, approximate f(p) by a rational function
     r(p) = (u*p + v) / (p + w)
     and make a step to p_new to the root of f(p): r(p_new) = 0.
     The coefficients u, v and w are found from the bracket values p1..3 and f1...3

The algorithm and implementation follows
https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fpcurf.f#L229
and
https://github.com/scipy/scipy/blob/maintenance/1.11.x/scipy/interpolate/fitpack/fppara.f#L290

Note that the latter is for parametric splines and the former is for 1D spline
functions. The minimization is indentical though [modulo a summation over the
dimensions in the computation of f(p)], so we reuse the minimizer for both
d=1 and d>1.
g?g?g{Gz?)r   r   )r   Tr   r   )r3   F)rN   Fr3   )
stacklevel)	convergedroot
iterationsier)r]   MAXITr^   r   r   r   warningswarnRuntimeWarningr   r   )fp0bracketr`   con1con9con4ich1ich3r   r   r   r   r   itr   r   r   r   s                      r    	root_ratir   9  sy   , DDD JD!HRhr
AElAaDB r7S=$NC 19Bw#~F727*Q6D19Bw#~F<AG27*Q6D 8rRx%NC 22r2* 6a h "Y
axnXc]3B91EEr"   c                    U[         -  nU R                  nUc8  U	(       a  [        USU-  -   SU-  S-   5      nOK[        X-   S-   SU-  S-   5      nO3USUS-   -  :  a  [        SU< SSUS-   -   S35      eUb  [        S5      eUc  [	        XX#XEXhU	5	      n[        U5      S	   nO
[        XXYS
9  UR                  S   SUS-   -  :X  a=  [        XXuX)S
9u    p  nU
R                  U5      U
R                  U5      p[        XU5      $ U	(       a  [        XXuU5      u  nnnnnnnnO[        XXuX)S
9u  nn    nUR                  S   U-
  S-
  nU	(       d  UUSS2S4   R                  5       -  n[        XXuX)S
9u  nnUU-
  nU	(       d;  [        X[        R                  " U/US-   -  U/US-   -  -   5      XR5      u  nnUU-
  nOtXC-
  n[        R                   " SUS-   -  ["        S9n[%        SUS-   5       H*  nU S   UU-
  U-  -
  UU'   XS-
     UU-  -   UUU-   S-   '   M,     [        XUXRU	S
9u  nnUU-
  nSU4[        R&                  U44nU	(       d  [)        XXuXbUUS9nO[+        XXuXbUUWWWS9n[-        UWUU5      nUR.                  R0                  u  pnUR.                  R2                  UR.                  R4                  n nU
R                  U5      U
R                  U5      p[        R6                  " XUUU S9n!U!$ )z3Shared infra for make_splrep and make_splprep.
    Nr3   rN   r   rW   rX   r4   zEither supply `t` or `nest`.r5   r   r   r0   )r   rF   r   r~   r   )r   rF   r   r~   r   r   r   r   )axisextrapolate)rZ   r[   rD   r   rT   listr
   r@   r   r7   r	   r   r   r!   r   rs   r\   r8   r]   r   r}   r   r   r   tckr   r   construct_fast)"r   r   r   rG   rH   r   rF   r   rO   r   rS   r`   ra   genr   r   r~   r   r   r   r   r   rz   r   fpinffp0rd   tcre   r   r   r   extrapr   s"                                     r    _make_splrep_implr     s.    c'C	A| q1Q3w!a(Dquqy!A#'*D!QU)9$-1Q3yPQRSS=;<<y"1qIIbMa+wwqzQ!a%[ %aA!G1Azz!}bjjm1qQ  $HaTU#V 2r1aAq%aA!G1aA	
Q	B1a4 1q<EArFE bhhtQqSzRD!A#J/F&GN3Ag gXXaQiu-q!a%AaDAES=(BqE!eHq3w.Bq1uqyM !  b!B3Ag #h'GaAaQ/aAaQ2"J!Q%A eeiiGA!55::quu00&D::a="**Q-q

 
 qt
HCJr"   )r   rG   rH   r   rF   r   rO   r%   c                    [        XX'5      n
Ub  U
R                  U5      n[        U	5      n	US:X  a  Uc  Uc  Ub  [        S5      e[	        XXYS9$ U	S:H  n[        XX%XcUSUS9	u  pp%pcn[        XX#XEXgXU
S9nUR                  SS2S4   Ul        U$ )	a2  Create a smoothing B-spline function with bounded error, minimizing derivative jumps.

Given the set of data points ``(x[i], y[i])``, determine a smooth spline
approximation of degree ``k`` on the interval ``xb <= x <= xe``.

Parameters
----------
x, y : array_like, shape (m,)
    The data points defining a curve ``y = f(x)``.
w : array_like, shape (m,), optional
    Strictly positive 1D array of weights, of the same length as `x` and `y`.
    The weights are used in computing the weighted least-squares spline
    fit. If the errors in the y values have standard-deviation given by the
    vector ``d``, then `w` should be ``1/d``.
    Default is ``np.ones(m)``.
xb, xe : float, optional
    The interval to fit.  If None, these default to ``x[0]`` and ``x[-1]``,
    respectively.
k : int, optional
    The degree of the spline fit. It is recommended to use cubic splines,
    ``k=3``, which is the default. Even values of `k` should be avoided,
    especially with small `s` values.
s : float, optional
    The smoothing condition. The amount of smoothness is determined by
    satisfying the LSQ (least-squares) constraint::

        sum((w * (g(x)  - y))**2 ) <= s

    where ``g(x)`` is the smoothed fit to ``(x, y)``. The user can use `s`
    to control the tradeoff between closeness to data and smoothness of fit.
    Larger `s` means more smoothing while smaller values of `s` indicate less
    smoothing.
    Recommended values of `s` depend on the weights, `w`. If the weights
    represent the inverse of the standard deviation of `y`, then a good `s`
    value should be found in the range ``(m-sqrt(2*m), m+sqrt(2*m))`` where
    ``m`` is the number of datapoints in `x`, `y`, and `w`.
    Default is ``s = 0.0``, i.e. interpolation.
t : array_like, optional
    The spline knots. If None (default), the knots will be constructed
    automatically.
    There must be at least ``2*k + 2`` and at most ``m + k + 1`` knots.
nest : int, optional
    The target length of the knot vector. Should be between ``2*(k + 1)``
    (the minimum number of knots for a degree-``k`` spline), and
    ``m + k + 1`` (the number of knots of the interpolating spline).
    The actual number of knots returned by this routine may be slightly
    larger than `nest`.
    Default is None (no limit, add up to ``m + k + 1`` knots).
periodic : bool, optional
    If True, data points are considered periodic with period ``x[m-1]`` -
    ``x[0]`` and a smooth periodic spline approximation is returned. Values of
    ``y[m-1]`` and ``w[m-1]`` are not used.
    The default is False, corresponding to boundary condition 'not-a-knot'.
bc_type : str, optional
    Boundary conditions.
    Default is `"not-a-knot"`.
    The following boundary conditions are recognized:

    * ``"not-a-knot"`` (default): The first and second segments are the
      same polynomial. This is equivalent to having ``bc_type=None``.
    * ``"periodic"``: The values and the first ``k-1`` derivatives at the
      ends are equivalent.

Returns
-------
spl : a `BSpline` instance
    For `s=0`,  ``spl(x) == y``.
    For non-zero values of `s` the `spl` represents the smoothed approximation
    to `(x, y)`, generally with fewer knots.

See Also
--------
generate_knots : is used under the hood for generating the knots
make_splprep : the analog of this routine for parametric curves
make_interp_spline : construct an interpolating spline (``s = 0``)
make_lsq_spline : construct the least-squares spline given the knot vector
splrep : a FITPACK analog of this routine

References
----------
.. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
    parametric splines, Computer Graphics and Image Processing",
    20 (1982) 171-184.
.. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
    Numerical Analysis, Oxford University Press, 1993.

Notes
-----
This routine constructs the smoothing spline function, :math:`g(x)`, to
minimize the sum of jumps, :math:`D_j`, of the ``k``-th derivative at the
internal knots (:math:`x_b < t_i < x_e`), where

.. math::

    D_i = g^{(k)}(t_i + 0) - g^{(k)}(t_i - 0)

Specifically, the routine constructs the spline function :math:`g(x)` which
minimizes

.. math::

        \sum_i | D_i |^2 \to \mathrm{min}

provided that

.. math::

       \sum_{j=1}^m (w_j \times (g(x_j) - y_j))^2 \leqslant s ,

where :math:`s > 0` is the input parameter.

In other words, we balance maximizing the smoothness (measured as the jumps
of the derivative, the first criterion), and the deviation of :math:`g(x_j)`
from the data :math:`y_j` (the second criterion).

Note that the summation in the second criterion is over all data points,
and in the first criterion it is over the internal spline knots (i.e.
those with ``xb < t[i] < xe``). The spline knots are in general a subset
of data, see `generate_knots` for details.

Also note the difference of this routine to `make_lsq_spline`: the latter
routine does not consider smoothness and simply solves a least-squares
problem

.. math::

    \sum w_j \times (g(x_j) - y_j)^2 \to \mathrm{min}

for a spline function :math:`g(x)` with a _fixed_ knot vector ``t``.

.. versionadded:: 1.15.0
Nr   s==0 is for interpolation only)r   r%   r   FrQ   rR   )r   r7   r&   r   r   rJ   r   r   )r   r   r   rG   rH   r   rF   r   rO   r%   rS   r   r   s                r    make_splrepr     s    N 
q	$B}JJqM(GAv=AMT-==>>!!!==:%H,Q18=RA!r A!d
LC EE!Q$KCEJr"   )	r   uubuer   rF   r   rO   r%   c       	            [        U	5      n	U	S:H  n
[        U [        5      (       a  [        / U QUPUPUP76 nO[        XX'5      nUR	                  U SS9n UcZ  U SS2SS24   U SS2SS24   -
  S-  nUR                  UR                  UR                  USS95      5      n[        USX"S   -  5      nUS:X  a+  Uc  Uc  Ub  [        S	5      e[        X R                  USS
9U4$ [        X XXcUSU
S9	u  p ppcnUb  UR                  U5      n[        X XXEXgXUS9nUR                  R                  n[!        UR"                  XR$                  SS9nXR                  U5      4$ )aT  
Create a smoothing parametric B-spline curve with bounded error, minimizing derivative jumps.

Given a list of N 1D arrays, `x`, which represent a curve in
N-dimensional space parametrized by `u`, find a smooth approximating
spline curve ``g(u)``.

Parameters
----------
x : array_like, shape (ndim, m)
    Sampled data points representing the curve in ``ndim`` dimensions.
    The typical use is a list of 1D arrays, each of length ``m``.
w : array_like, shape(m,), optional
    Strictly positive 1D array of weights.
    The weights are used in computing the weighted least-squares spline
    fit. If the errors in the `x` values have standard deviation given by
    the vector d, then `w` should be 1/d. Default is ``np.ones(m)``.
u : array_like, optional
    An array of parameter values for the curve in the parametric form.
    If not given, these values are calculated automatically, according to::

        v[0] = 0
        v[i] = v[i-1] + distance(x[i], x[i-1])
        u[i] = v[i] / v[-1]

ub, ue : float, optional
    The end-points of the parameters interval. Default to ``u[0]`` and ``u[-1]``.
k : int, optional
    Degree of the spline. Cubic splines, ``k=3``, are recommended.
    Even values of `k` should be avoided especially with a small ``s`` value.
    Default is ``k=3``
s : float, optional
    A smoothing condition.  The amount of smoothness is determined by
    satisfying the conditions::

        sum((w * (g(u) - x))**2) <= s,

    where ``g(u)`` is the smoothed approximation to ``x``.  The user can
    use `s` to control the trade-off between closeness and smoothness
    of fit.  Larger ``s`` means more smoothing while smaller values of ``s``
    indicate less smoothing.
    Recommended values of ``s`` depend on the weights, ``w``.  If the weights
    represent the inverse of the standard deviation of ``x``, then a good
    ``s`` value should be found in the range ``(m - sqrt(2*m), m + sqrt(2*m))``,
    where ``m`` is the number of data points in ``x`` and ``w``.
t : array_like, optional
    The spline knots. If None (default), the knots will be constructed
    automatically.
    There must be at least ``2*k + 2`` and at most ``m + k + 1`` knots.
nest : int, optional
    The target length of the knot vector. Should be between ``2*(k + 1)``
    (the minimum number of knots for a degree-``k`` spline), and
    ``m + k + 1`` (the number of knots of the interpolating spline).
    The actual number of knots returned by this routine may be slightly
    larger than `nest`.
    Default is None (no limit, add up to ``m + k + 1`` knots).
bc_type : str, optional
    Boundary conditions.
    Default is `"not-a-knot"`.
    The following boundary conditions are recognized:

    * ``"not-a-knot"`` (default): The first and second segments are the
      same polynomial. This is equivalent to having ``bc_type=None``.
    * ``"periodic"``: The values and the first ``k-1`` derivatives at the
      ends are equivalent.

Returns
-------
spl : a `BSpline` instance
    For `s=0`,  ``spl(u) == x``.
    For non-zero values of ``s``, `spl` represents the smoothed approximation
    to ``x``, generally with fewer knots.
u : ndarray
    The values of the parameters

See Also
--------
generate_knots : is used under the hood for generating the knots
make_splrep : the analog of this routine 1D functions
make_interp_spline : construct an interpolating spline (``s = 0``)
make_lsq_spline : construct the least-squares spline given the knot vector
splprep : a FITPACK analog of this routine

Notes
-----
Given a set of :math:`m` data points in :math:`D` dimensions, :math:`\vec{x}_j`,
with :math:`j=1, ..., m` and :math:`\vec{x}_j = (x_{j; 1}, ..., x_{j; D})`,
this routine constructs the parametric spline curve :math:`g_a(u)` with
:math:`a=1, ..., D`, to minimize the sum of jumps, :math:`D_{i; a}`, of the
``k``-th derivative at the internal knots (:math:`u_b < t_i < u_e`), where

.. math::

    D_{i; a} = g_a^{(k)}(t_i + 0) - g_a^{(k)}(t_i - 0)

Specifically, the routine constructs the spline function :math:`g(u)` which
minimizes

.. math::

        \sum_i \sum_{a=1}^D | D_{i; a} |^2 \to \mathrm{min}

provided that

.. math::

    \sum_{j=1}^m \sum_{a=1}^D (w_j \times (g_a(u_j) - x_{j; a}))^2 \leqslant s

where :math:`u_j` is the value of the parameter corresponding to the data point
:math:`(x_{j; 1}, ..., x_{j; D})`, and :math:`s > 0` is the input parameter.

In other words, we balance maximizing the smoothness (measured as the jumps
of the derivative, the first criterion), and the deviation of :math:`g(u_j)`
from the data :math:`x_j` (the second criterion).

Note that the summation in the second criterion is over all data points,
and in the first criterion it is over the internal spline knots (i.e.
those with ``ub < t[i] < ue``). The spline knots are in general a subset
of data, see `generate_knots` for details.

.. versionadded:: 1.15.0

References
----------
.. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
    parametric splines, Computer Graphics and Image Processing",
    20 (1982) 171-184.
.. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs on
    Numerical Analysis, Oxford University Press, 1993.
r   r   )r   Nr5   r3   rY   r   r   )r   r   TrQ   )r   rS   )r&   
isinstancer   r   stackcumulative_sumsqrtr   r   r   r   TrJ   r7   r   r   r	   r   r   )r   r   r   r   r   r   rF   r   rO   r%   r   rS   dpr   ccspl1s                   r    make_splprepr     s   L  (G:%H !T)a))A)q)Q1(
A 	yAh3B36"Q&rwwrvvbqv'9:<b"aB%i(Av=AMT-==>>!!SSAA699,Q18<xQA!r 	}JJqM
A! <C
 
B355"ee!,DAr"   )F)'r   r   rA   numpyr   scipy._lib._array_apir   r   r   	_bsplinesr   r   r	   r
   r   r   r    r   rZ   r   r!   r&   r.   rJ   rU   rT   rp   r{   r}   r   r   r   	_iermesg1r   r   r   r   r   r   r"   r    <module>r     ss  &    M M    
"	0<!~ $$G"t!$mR HmR` DF CzFR` `Df fRG&' '
	     "ZFx DF [| $$GDTqDtTY HYx $$G$4Tdj Hjr"   