a
    š¥»a%  ã                   @   sì   d dl Z d dlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZmZmZ dd	lmZmZ dd
lmZ ddlmZ ddlmZmZ eeee
eeeeeeeedœZddddddœdd„Zdedœdd„ZG dd„ de jjƒZdS )é    N)Úvjpé   )ÚDopri5Solver)ÚBosh3Solver)ÚAdaptiveHeunSolver)Ú	Fehlberg2)ÚEulerÚMidpointÚRK4)ÚAdamsBashforthÚAdamsBashforthMoulton)ÚDopri8Solver)ÚScipyWrapperODESolver)Ú_check_inputsÚ_flat_to_shape)Údopri8Údopri5Úbosh3Ú	fehlberg2Úadaptive_heunZeulerZmidpointZrk4Zexplicit_adamsZimplicit_adamsÚfixed_adamsZscipy_solvergH¯¼šò×z>g•Ö&è.>)ÚrtolÚatolÚmethodÚoptionsÚevent_fnc             
   C   s¶   t | |||||||tƒ	\
}} }}}}}}}}	t| f | |||dœ|¤Ž}
|du r\|
 |¡}n(|
 |d |¡\}}| |¡}|	r„| }|duržt|t|ƒf|ƒ}|du rª|S ||fS dS )a¦  Integrate a system of ordinary differential equations.

    Solves the initial value problem for a non-stiff system of first order ODEs:
        ```
        dy/dt = func(t, y), y(t[0]) = y0
        ```
    where y is a Tensor or tuple of Tensors of any shape.

    Output dtypes and numerical precision are based on the dtypes of the inputs `y0`.

    Args:
        func: Function that maps a scalar Tensor `t` and a Tensor holding the state `y`
            into a Tensor of state derivatives with respect to time. Optionally, `y`
            can also be a tuple of Tensors.
        y0: N-D Tensor giving starting value of `y` at time point `t[0]`. Optionally, `y0`
            can also be a tuple of Tensors.
        t: 1-D Tensor holding a sequence of time points for which to solve for
            `y`, in either increasing or decreasing order. The first element of
            this sequence is taken to be the initial time point.
        rtol: optional float64 Tensor specifying an upper bound on relative error,
            per element of `y`.
        atol: optional float64 Tensor specifying an upper bound on absolute error,
            per element of `y`.
        method: optional string indicating the integration method to use.
        options: optional dict of configuring options for the indicated integration
            method. Can only be provided if a `method` is explicitly set.
        event_fn: Function that maps the state `y` to a Tensor. The solve terminates when
            event_fn evaluates to zero. If this is not None, all but the first elements of
            `t` are ignored.

    Returns:
        y: Tensor, where the first dimension corresponds to different
            time points. Contains the solved value of y for each desired time point in
            `t`, with the initial value `y0` being the first element along the first
            dimension.

    Raises:
        ValueError: if an invalid `method` is provided.
    )ÚfuncÚy0r   r   Nr   )r   ÚSOLVERSZ	integrateZintegrate_until_eventÚtor   Úlen)r   r   Útr   r   r   r   r   ÚshapesZt_is_reversedZsolverÚsolutionÚevent_t© r%   úR/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torchdiffeq/_impl/odeint.pyÚodeint   s    ),
r'   F)Úreverse_timeÚodeint_interfacec             
   K   s6  |r(t  | d¡| d¡ ¡ d g¡}n"t  | d¡| d¡ ¡ d g¡}|| ||fd|i|¤Ž\}}	t| ||dddd|tƒ	\
}
}}}}}}}}}|
dur°t  dd„ |	D ƒ¡}n|	d }|rÂ| }t ||||¡\}}|rà| }|
du�rt|d|
ƒ}t	d	d
„ t
|	|ƒD ƒƒ}	nt j|	dd… |d gdd�}	||	fS )z8Automatically links up the gradient from the event time.éÿÿÿÿg      ð?r   g        Nc                 S   s   g | ]}|d    d ¡‘qS )r*   )Úreshape)Ú.0Úsr%   r%   r&   Ú
<listcomp>k   ó    z odeint_event.<locals>.<listcomp>r%   c                 s   s0   | ](\}}t j|d d… |d  gdd�V  qd S )Nr*   r   ©Zdim)ÚtorchÚcat)r,   r-   Zs_tr%   r%   r&   Ú	<genexpr>{   r/   zodeint_event.<locals>.<genexpr>r   r0   )r1   r2   r+   Údetachr   r   ÚImplicitFnGradientReroutingÚapplyr   ÚtupleÚzip)r   r   Út0r   r(   r)   Úkwargsr!   r$   r#   r"   Z_funcÚ_Ústate_tr%   r%   r&   Úodeint_event]   s$    $",
r=   c                   @   s$   e Zd Zedd„ ƒZedd„ ƒZdS )r5   c                 C   s(   || _ || _|  ||¡ | ¡ | ¡ fS )z% event_t is the solution to event_fn )r   r   Zsave_for_backwardr4   )Úctxr   r   r$   r<   r%   r%   r&   Úforward„   s    z#ImplicitFnGradientRerouting.forwardc                 C   sÒ   | j }| j}| j\}}| ¡  ¡  d¡}| ¡  ¡  d¡}|||ƒ}t ¡ �& t|||fƒ\}\}	}
W d   ƒ n1 sx0    Y  |	t 	|
| ¡ }|t 	|| ¡ }|
| |d   
|¡ }
||
 }d d d |fS )NTgê-�™—q=)r   r   Zsaved_tensorsr4   ÚcloneZrequires_grad_r1   Zenable_gradr   ÚsumZ
reshape_as)r>   Zgrad_tZ
grad_stater   r   r$   r<   Zf_valÚcZpar_dtZdstateZdcdtr%   r%   r&   ÚbackwardŒ   s    


4z$ImplicitFnGradientRerouting.backwardN)Ú__name__Ú
__module__Ú__qualname__Ústaticmethodr?   rC   r%   r%   r%   r&   r5   ‚   s   
r5   )r1   Ztorch.autograd.functionalr   r   r   r   r   r   r   r   r   Z
fixed_gridr   r	   r
   r   r   r   r   r   Zscipy_wrapperr   Úmiscr   r   r   r'   r=   ZautogradZFunctionr5   r%   r%   r%   r&   Ú<module>   s4   ò>%