Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve setting explanation in the guide #2403

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 17 additions & 3 deletions doc/apidoc/classes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Classes
.. _classes-qobj:

Qobj
--------------
----

.. autoclass:: qutip.core.qobj.Qobj
:members:
Expand All @@ -16,17 +16,25 @@ Qobj
.. _classes-qobjevo:

QobjEvo
--------------
-------

.. autoclass:: qutip.core.cy.qobjevo.QobjEvo
:members:
:special-members: __call__

.. _classes-coreoptions:

CoreOptions
-----------

.. autoclass:: qutip.core.options.CoreOptions
:members:


.. _classes-bloch:

Bloch sphere
---------------
------------

.. autoclass:: qutip.bloch.Bloch
:members:
Expand Down Expand Up @@ -265,6 +273,12 @@ Distribution functions
.. autoclass:: qutip.distributions.Distribution
:members:

CompilationOptions
------------------

.. autoclass:: qutip.core.coefficient.CompilationOptions


..
Docstrings are empty...

Expand Down
1 change: 1 addition & 0 deletions doc/changes/2403.doc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve guide-settings page.
179 changes: 164 additions & 15 deletions doc/guide/guide-settings.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,66 @@
.. _settings:

**************
QuTiP settings
**************

QuTiP has multiple settings that control it's behaviour:

* ``qutip.settings`` contain installation and runtime information.
Most of these parameters are readonly. But systems paths used by QuTiP are
also included here and could need updating in none standard environment.
* ``qutip.settings.core`` contains options for operations with ``Qobj`` and
other qutip's class. All options are writable.
* ``qutip.settings.compile`` has options that control compilation of string
coefficients to cython modules. All options are writable.

.. _settings-install:

********************
Environment settings
********************

``qutip.settings`` has information about the run time environment:

.. tabularcolumns:: | p{3cm} | p{2cm} | p{10cm} |

.. cssclass:: table-striped

+-------------------+-----------+----------------------------------------------------------+
| Setting | Read Only | Description |
+===================+===========+==========================================================+
| `has_mkl` | True | Whether qutip can find mkl libraries. |
| | | mkl sparse linear equation solver can be used when True. |
+-------------------+-----------+----------------------------------------------------------+
| `mkl_lib` | True | Path of the mkl libraries found. |
+-------------------+-----------+----------------------------------------------------------+
| `ipython` | True | Whether running in ipython. |
+-------------------+-----------+----------------------------------------------------------+
| `eigh_unsafe` | True | Whether to use eig for hermitian matrix since it can |
| | | segfault in some conditions. |
+-------------------+-----------+----------------------------------------------------------+
| `coeffroot` | False | Directory in which QuTiP creates cython module for |
| | | string coefficient. |
+-------------------+-----------+----------------------------------------------------------+
| `coeff_write_ok` | True | Whether QuTiP has write permission for `coeffroot`. |
+-------------------+-----------+----------------------------------------------------------+
| `idxint_size` | True | Whether QuTiP's sparse matrix indices use 32 or 64 bits. |
| | | Sparse matrices' size are limited to 2**(idxint_size-1). |
+-------------------+-----------+----------------------------------------------------------+
| `num_cpus` | True | Detected number of cpus. |
+-------------------+-----------+----------------------------------------------------------+
| `colorblind_safe` | False | Control the default cmap in visualization functions. |
+-------------------+-----------+----------------------------------------------------------+


It may be needed to update ``coeffroot`` if the default HOME is not writable. It can be done with:

>>> qutip.settings.coeffroot = "path/to/string/coeff/directory"

New to version 5, string compiled in a session are kept for future sessions.
As long as the same ``coeffroot`` is used, each string will only be compiled once.


*********************************
Modifying Internal QuTiP Settings
*********************************
Expand All @@ -9,33 +70,42 @@ Modifying Internal QuTiP Settings
User Accessible Parameters
==========================

In this section we show how to modify a few of the internal parameters used by QuTiP.
In this section we show how to modify a few of the internal parameters used by ``Qobj``.
The settings that can be modified are given in the following table:

.. tabularcolumns:: | p{3cm} | p{5cm} | p{5cm} |

.. cssclass:: table-striped

+------------------------------+----------------------------------------------+------------------------------+
| Setting | Description | Options |
+==============================+==============================================+==============================+
| `auto_tidyup` | Automatically tidyup sparse quantum objects. | True / False |
+------------------------------+----------------------------------------------+------------------------------+
| `auto_tidyup_atol` | Tolerance used by tidyup. (sparse only) | float {1e-14} |
+------------------------------+----------------------------------------------+------------------------------+
| `atol` | General absolute tolerance. | float {1e-12} |
+------------------------------+----------------------------------------------+------------------------------+
| `rtol` | General relative tolerance. | float {1e-12} |
+------------------------------+----------------------------------------------+------------------------------+
| `function_coefficient_style` | Signature expected by function coefficients. | {"auto", "pythonic", "dict"} |
+------------------------------+----------------------------------------------+------------------------------+
+------------------------------+----------------------------------------------+--------------------------------+
| Options | Description | type [default] |
+==============================+==============================================+================================+
| `auto_tidyup` | Automatically tidyup sparse quantum objects. | bool [True] |
+------------------------------+----------------------------------------------+--------------------------------+
| `auto_tidyup_atol` | Tolerance used by tidyup. (sparse only) | float [1e-14] |
+------------------------------+----------------------------------------------+--------------------------------+
| `auto_tidyup_dims` | Whether the scalar dimension are contracted | bool [False] |
+------------------------------+----------------------------------------------+--------------------------------+
| `atol` | General absolute tolerance. | float [1e-12] |
+------------------------------+----------------------------------------------+--------------------------------+
| `rtol` | General relative tolerance. | float [1e-12] |
+------------------------------+----------------------------------------------+--------------------------------+
| `function_coefficient_style` | Signature expected by function coefficients. | {["auto"], "pythonic", "dict"} |
+------------------------------+----------------------------------------------+--------------------------------+
| `default_dtype` | Data format used when creating Qobj from | {[None], "CSR", "Dense", |
| | QuTiP functions, such as ``qeye``. | "Dia"} + other from plugins |
+------------------------------+----------------------------------------------+--------------------------------+

See also :class:`.CoreOptions`.

.. _settings-usage:

Example: Changing Settings
==========================

The two most important settings are ``auto_tidyup`` and ``auto_tidyup_atol`` as they control whether the small elements of a quantum object should be removed, and what number should be considered as the cut-off tolerance.
The two most important settings are ``auto_tidyup`` and ``auto_tidyup_atol`` as
they control whether the small elements of a quantum object should be removed,
and what number should be considered as the cut-off tolerance.
Modifying these, or any other parameters, is quite simple::

>>> qutip.settings.core["auto_tidyup"] = False
Expand All @@ -44,3 +114,82 @@ The settings can also be changed for a code block::

>>> with qutip.CoreOptions(atol=1e-5):
>>> assert qutip.qeye(2) * 1e-9 == qutip.qzero(2)



.. _settings-compile:

String Coefficient Parameters
=============================

String based coefficient used for time dependent system are compiled using Cython when available.
Speeding the simulations, it tries to set c types to passed variables.
``qutip.settings.compile`` has multiple options for compilation.

There are options are about to whether to compile.

.. tabularcolumns:: | p{3cm} | p{10cm} |

.. cssclass:: table-striped

+--------------------------+-----------------------------------------------------------+
| Options | Description |
+==========================+===========================================================+
| `use_cython` | Whether to compile string using cython or using ``eval``. |
+--------------------------+-----------------------------------------------------------+
| `recompile` | Whether to force recompilation or use a previously |
| | constructed coefficient if available. |
+--------------------------+-----------------------------------------------------------+


Some options passed to cython and the compiler (for advanced user).

.. tabularcolumns:: | p{3cm} | p{10cm} |

.. cssclass:: table-striped

+--------------------------+-----------------------------------------------------------+
| Options | Description |
+==========================+===========================================================+
| `compiler_flags` | C++ compiler flags. |
+--------------------------+-----------------------------------------------------------+
| `link_flags` | C++ linker flags. |
+--------------------------+-----------------------------------------------------------+
| `build_dir` | cythonize's build_dir. |
+--------------------------+-----------------------------------------------------------+
| `extra_import` | import or cimport line of code to add to the cython file. |
+--------------------------+-----------------------------------------------------------+
| `clean_on_error` | Whether to erase the created file if compilation failed. |
+--------------------------+-----------------------------------------------------------+


Lastly some options control how qutip tries to detect C types (for advanced user).

.. tabularcolumns:: | p{3cm} | p{10cm} |

.. cssclass:: table-striped

+--------------------------+-----------------------------------------------------------------------------------------+
| Options | Description |
+==========================+=========================================================================================+
| `try_parse` | Whether qutip parse the string to detect common patterns. |
| | |
| | When True, "cos(w * t)" and "cos(a * t)" will use the same compiled coefficient. |
+--------------------------+-----------------------------------------------------------------------------------------+
| `static_types` | If False, every variable will be typed as ``object``, (except ``t`` which is double). |
| | |
| | If True, scalar (int, float, complex), string and Data types are detected. |
+--------------------------+-----------------------------------------------------------------------------------------+
| `accept_int` | Whether to type ``args`` values which are python int as int or float/complex. |
| | |
| | Per default it is True when subscription (``a[i]``) is used. |
+--------------------------+-----------------------------------------------------------------------------------------+
| `accept_float` | Whether to type ``args`` values which are python float as int or float/complex. |
| | |
| | Per default it is True when comparison (``a > b``) is used. |
+--------------------------+-----------------------------------------------------------------------------------------+


These options can be set at a global level in ``qutip.settings.compile`` or by passing a :class:`.CompilationOptions` instance to the :func:`.coefficient` functions.

>>> qutip.coefficient("cos(t)", compile_opt=CompilationOptions(recompile=True))
44 changes: 33 additions & 11 deletions qutip/core/coefficient.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,11 +209,30 @@ def const(value):

class CompilationOptions(QutipOptions):
"""
Options that control compilation of string based coefficient to Cython.

These options can be set globaly:

``settings.compile["compiler_flags"] = "-O1"``

In a ``with`` block:

``with CompilationOptions(use_cython=False):``

Or as an instance:

``coefficient(coeff, compile_opt=CompilationOptions(recompile=True))``

********************
Compilation options:
********************

use_cython: bool
Whether to compile strings as cython code or use python's ``exec``.

recompile : bool
Do not use previously made files but build a new one.

try_parse: bool [True]
Whether to try parsing the string for reuse and static typing.

Expand All @@ -229,9 +248,6 @@ class CompilationOptions(QutipOptions):
accept_float : bool
Whether to use the type ``float`` or upgrade them to ``complex``.

recompile : bool
Do not use previously made files but build a new one.

compiler_flags : str
Flags to pass to the compiler, ex: "-Wall -O3"...
Flags not matching your comiler and OS may cause compilation to fail.
Expand Down Expand Up @@ -267,6 +283,7 @@ class CompilationOptions(QutipOptions):
try:
import cython
import filelock
import setuptools
_use_cython = True
except ImportError:
_use_cython = False
Expand All @@ -277,7 +294,7 @@ class CompilationOptions(QutipOptions):
"try_parse": True,
"static_types": True,
"accept_int": None,
"accept_float": True,
"accept_float": None,
"recompile": False,
"compiler_flags": _compiler_flags,
"link_flags": _link_flags,
Expand All @@ -293,7 +310,7 @@ class CompilationOptions(QutipOptions):


# Version number of the Coefficient
COEFF_VERSION = "1.1"
COEFF_VERSION = "1.2"

try:
root = os.path.join(qset.tmproot, f"qutip_coeffs_{COEFF_VERSION}")
Expand All @@ -309,15 +326,17 @@ def clean_compiled_coefficient(all=False):
Parameter:
----------
all: bool
If not `all` will remove only previous version.
If not `all`, it will remove only previous version.
"""
import glob
import shutil
tmproot = qset.tmproot
root = os.path.join(tmproot, f'qutip_coeffs_{COEFF_VERSION}')
active = qset.coeffroot
folders = glob.glob(os.path.join(tmproot, 'qutip_coeffs_') + "*")
if all:
shutil.rmtree(active)
for folder in folders:
if all or folder != root:
if folder != active:
shutil.rmtree(folder)
# Recreate the empty folder.
qset.coeffroot = qset.coeffroot
Expand Down Expand Up @@ -384,8 +403,8 @@ def coeff_from_str(base, args, args_ctypes, compile_opt=None, **_):
if not compile_opt['use_cython']:
if WARN_MISSING_MODULE[0]:
warnings.warn(
"Both `cython` and `filelock` are required for compilation of "
"string coefficents. Falling back on `eval`.")
"`cython` `setuptools` and `filelock` are required for "
"compilation of string coefficents. Falling back on `eval`.")
# Only warns once.
WARN_MISSING_MODULE[0] = 0
return StrFunctionCoefficient(base, args)
Expand Down Expand Up @@ -711,8 +730,11 @@ def parse(code, args, compile_opt):
accept_float = compile_opt['accept_float']
if accept_int is None:
# If there is a subscript: a[b] int are always accepted to be safe
# with TypeError
# with TypeError.
# Also comparison is not supported for complex.
accept_int = "SUBSCR" in dis.Bytecode(code).dis()
if accept_float is None:
accept_float = "COMPARE_OP" in dis.Bytecode(code).dis()
for word in code.split():
if word not in names:
# syntax
Expand Down