.. _derivatives:

DERIVATIVES
############

An optional :term:`verbatim` section that defines an |ode| model in a |popy| script. 

The |derivatives| section computes |sx| state amounts at multiple time points using |odes| given initial |sx| from the |states| section and previously compute |mx| and |cx| parameters for each row in the |data_file|.

Note the |derivatives| section is optional. It is possible to |not| have a compartment model in your script. For example you can just directly use individual |mx| variables in the |predictions| section instead of generating |sx| values. 

The |derivatives| section is available in the following scripts:-

* :ref:`tut_script`
* :ref:`gen_script`
* :ref:`fit_script`
* :ref:`sim_script`
* :ref:`mtut_script`
* :ref:`mgen_script`
* :ref:`mfit_script`
* :ref:`msim_script`

|ie| Any script that processes |pkpd| models.

.. _example_derivatives_pk:

Example DERIVATIVES for PK Model
===========================================

The example below is used in :ref:`builtin_fit_example`.

.. literalinclude:: 
    /_autogen/quick_start/builtin_fit_example/fit_sections/DERIVATIVES.pyml
    :language: pyml

The example above defines a two compartment |pk| model with a |depot| compartment. The same model can be expressed as:-    

.. code-block:: pyml

    DERIVATIVES: |
        s[DEPOT,CENTRAL,PERI] = @dep_two_cmp_cl{
            dose:@bolus{amt:c[AMT]},
            KA: m[KA],
            CL: m[CL],
            V1: m[V1],
            Q: m[Q],
            V2: m[V2],
        }
  
Where :ref:`@dep_two_cmp_cl` is a |cmp_func|. That uses the analytic solution to the |ode| instead of using a numerical |ode_solver|. 

Note you can also write:-
   
.. code-block:: pyml

    DERIVATIVES: |
        s[DEPOT,CENTRAL,PERI] = @dep_two_cmp_cl{ dose:@bolus{amt:c[AMT]} }
   
As the default values for 'KA', 'CL' etc are the equivalent |mx| variables. You still need to have all the appropriate |mx| variables defined in |model_params| and |camt| defined in your |data_file|.

|popy| also provides multiple alternative ways of formulating the |dx| equations as follows:-

.. literalinclude:: 
    DERIVATIVES_pk_split.pyml
    :language: pyml
    
The syntax above is standard |python|, but makes the inputs and outputs of each compartment clear. You can also use this **flow** based syntax:-

.. literalinclude:: 
    DERIVATIVES_pk_flow.pyml
    :language: pyml

This expresses the flows between compartments explicitly and avoids having to manually pair up the positive and negative flows. Note an unintentional mis-match between inputs and outputs in compartment models usually leads to :term:`mass balance` issues and models that are difficult to interpret and fit.
    
Note a sanity check on the |derivatives| section is to view the compartment diagram that is automatically created by |popy|, see :numref:`fig_two_comp_depot_diagram_derivatives`.

.. _fig_two_comp_depot_diagram_derivatives:

.. figure:: /_autogen/quick_start/builtin_fit_example/compartment_diagram.*
    :width: 50%
    :align: center
    
    Two compartment model with depot dosing, computed automatically from |derivatives| section.
    
All the example |derivatives| sections presented here generate the same diagram. If you make a :term:`mass balance` error your diagram may well |not| look like you expect. This is a useful safety feature built into |popy|. 
    
.. _example_derivatives_pd:

Example DERIVATIVES for PD Model
============================================

See :ref:`sum_link_direct_pd_tut` for example :ref:`tut_script`, using the following |derivatives| section for a |pd| model:-

.. literalinclude:: 
    /_autogen/indiv_examples/pd_models/direct_pd/fit_sections/DERIVATIVES.pyml
    :language: pyml

As discussed in :ref:`example_states_pd`. The following |states| section is required to initialise the derivative model in an equilibrium state:-
    
.. literalinclude:: 
    /_autogen/indiv_examples/pd_models/direct_pd/fit_sections/STATES.pyml
    :language: pyml
    
Note it's possible to split this |derivatives| model up into separate flows:-

.. literalinclude:: 
    DERIVATIVES_pd_split.pyml
    :language: pyml
    
It's also possible to mix and match |sx| and |dx| variables, by using a |cmp_func| for the |pk| compartment:-

.. literalinclude:: 
    DERIVATIVES_pd_cmp.pyml
    :language: pyml

Note in the above if you use a |cmp_func| then you need |sx| on the |lhs| (see |central| compartment). If you use numerical equations then you need |dx| on the |lhs| and |sx| variables on the |rhs| (see |marker| compartment).
    
All of the above |derivatives| sections should result in the same compartment diagram as shown in :numref:`fig_direct_pd_diagram_derivatives`.
    
.. _fig_direct_pd_diagram_derivatives:

.. figure:: /_autogen/indiv_examples/pd_models/direct_pd/compartment_diagram.*
    :width: 70%
    :align: center
    
    direct |pd| model, computed automatically from |derivatives| section.


.. _example_derivatives_circ:

Example DERIVATIVES using x[TIME]
======================================

See :ref:`sum_link_circ_sin_tut` for example :ref:`tut_script`, using the following |derivatives| section:-

.. literalinclude:: 
    /_autogen/indiv_examples/pd_models/circ_sin/fit_sections/DERIVATIVES.pyml
    :language: pyml

This |pk| model has a circadian input to the 'MARKER' compartment, so is in a equilibrium oscillating about a mean value, until a dose is administered in the |pk| compartment, which then causes an effect in the |pd| compartment through the 'conc_central' variable.

The main point of interest in this model is that the variable |xtime| is used within the |derivatives| section. |xtime| is a special variable that uses the continuous time when solving the |odes|. This is distinct from using |ctime|, which is constant at time points between data rows.

Note you can use |ctime| as an approximation if you have lots of data rows, but generally it's better to use |xtime| to model explicit time dependent components such as circadian variation within the |derivatives| section.


.. comment
    STATES section here is too complex to talk about
    .. literalinclude:: 
        /_autogen/indiv_examples/pd_models/circ_sin/fit_sections/STATES.pyml
        :language: pyml

The compartment diagram for this |pkpd| model is as shown in :numref:`fig_circ_pd_diagram_derivatives`.
    
.. _fig_circ_pd_diagram_derivatives:

.. figure:: /_autogen/indiv_examples/pd_models/circ_sin/compartment_diagram.*
    :width: 70%
    :align: center
    
    circadian |pd| model, computed automatically from |derivatives| section.

.. _rules_derivatives:
    
Rules for DERIVATIVES section
=======================================

Like all :term:`verbatim` sections the |derivatives| section of the config file accepts free form |python| :term:`pseudocode`, but there are some rules regarding which variables are allowed in a |derivatives| section as follows:- 

* **Only** |dx| and local variables can be defined on the |lhs| without using :ref:`cmp_funcs`.
* |sx| variables are usually on the |rhs| and **must** have a corresponding |dx| variable
* |sx| variables can only be defined on the |lhs| if you use a |cmp_func| 
* |sx| variables present in |derivatives| but |not| in |states| are initialised to zero.
* |cx| and |mx| are only allowed on the |rhs| of expressions
* |cx| must be defined in the |data_file| or |preprocess| section in a :ref:`fit_script` 
* |cx| must be defined within the |effects| section in a :ref:`gen_script` or |gen_effects| section in a :ref:`tut_script`.
* |mx| must be defined in the |model_params|
* |xtime| can be used to model continuous time, as opposed to discrete |ctime|

You can |not| use |px|, |rx|, |fx| or |tx| |etc| variables at all in this section. 

Like all :term:`verbatim` sections it is possible to introduce syntax errors by writing malformed |python|. Any coding errors will be reported when |popy| attempts to compile or run the |derivatives| function as a temporary .py file.

