.. _observations:

************
Observations
************

An observation is a value associated with a specific parameter or a physical observable, and a set of metadata.
Observations are generated by the :meth:`~exa.core.experiment.experiment.Experiment.analyze` method of EXA experiments.
The user of the experiment can inspect the potential observations and optionally save them to the database.
Once saved, subsequent experiment runs can load the saved values to generate updated settings for the experiment.
Which observations are loaded is governed by specific observation loading rules that the user can change.

Any Setting in the EXA setting tree can be saved as an observation,
and loaded back to update the corresponding Setting. However, there are also
observations that do not correspond to EXA settings.

The main source of new observations is the automatic calibration service of IQM QCCSW.


Loading observations
--------------------

When an experiment needs an observation value for its computation, it retrieves the value
based on specific rules. The loaded values override default settings and will be used when running
the experiment.


To see the status of the loaded values, use

.. code-block:: python

    experiment.observation_handler.print_observations()

Each observation has a rule according to which it is loaded, as displayed by ``print_observations``.


Global default loading rules
*****************************

It is possible to change the rules according to which observations are loaded with
:func:`~exa.core.observation.observation_loading_rules.set_global_default_observation_loading_rules`

.. code-block:: python


    import exa.core as ec
    ec.set_global_default_observation_loading_rules(rules=[ec.GetCalibrationSet("default")])

where ``rules`` can be an empty list, or a list of valid rules.
For a list of available rules, see classes on :mod:`~exa.core.observation.observation_loading_rules`. 
The exa-core file contains now just backwards compatibility imports.
Note: :func:`~exa.core.observation.observation_loading_rules.set_global_default_observation_loading_rules`
should be called before initiating any experiment instances, as the global default rules are applied in the experiment
constructor.

When the global default rules are an empty list, the observation loading is turned off globally.
This is the starting behavior if no rules are set.

When a list of rules is used, for example ``[GetLatest()]``,
all experiments will load observations based on these rules,
which effectively turns on the observation loading globally.

.. admonition:: Customized loading
    :class: dropdown

    The loading is handled by the
    :class:`observation_handler <iqm.cpc.core.observation.observation_handler.ObservationHandler>`
    attribute of the experiment instance.
    The handler provides a way to manage which observations will be loaded and how.
    It contains rules that are used to resolve which observations to load, and also contains the loaded values.

    You can manage the rules by
    :meth:`~iqm.cpc.core.observation.observation_handler.ObservationHandler.set_load_rules`.
    For example, the following lines set rules such that for ``'QB2'``, the latest observations will be loaded,
    and for ``'QB3'`` nothing is loaded.

    .. code-block:: python

        experiment.observation_handler.set_load_rules(load_rules=[GetLatest()], component_names=['QB2'])
        experiment.observation_handler.set_load_rules(load_rules=[], component_names=['QB3'])



Observation stash
*******************

Most observation loading rules query their data from the database every time experiment settings need to be resolved.
To prevent unnecessary overhead and abruptly changing calibration values, it is recommended to use the
:class:`~exa.core.observation.observation_stash.ObservationStash`.

The stash provides a way to load observations from the database once, and after that refer to the content of
the local stash only.

The stash can hold both
:class:`exa.core.observation.observation.LocalObservation` and :class:`.ObservationData`
instances. Creating the stash object with a set of local and DB observations can be done by just providing the
observations mapped to their ``dut_fields``

.. code-block:: python

    db_observations = {
        "QB1.readout.frequency": readout_frequency_obs,
        "QB1.drive.frequency": drive_frequency_obs,
    }

    local_observations = {
        "QB1.drive.amplitude": drive_amplitude_local_obs
    }

    obs_stash = ObservationStash(local_observations, db_observations)

In typical notebook use, however, what the user usually wants is to initialize the stash using a list of loading rules,
similarly to initialising an :class:`~iqm.cpc.core.observation.observation_handler.ObservationHandler`. For this
purpose, one may use
:func:`~exa.core.observation.observation_stash.get_loaded_stash_from_rules()`. For each observation,
it will go through the provided list of rules and try to load the observation, and once the DB returns a value,
it will stop. As a result, an :class:`~exa.core.observation.observation_stash.ObservationStash` instance
that contains a single DB observation per ``dut_field`` is initiated (in case one of the provided rules actually returned
a value for this ``dut_field``).

.. code-block:: python

    import exa.core as ec
    rules = [
        ec.GetLatestForTags(["calibration_new"]),
        ec.GetCalibrationSet("default"),
    ]
    obs_stash = ec.get_loaded_stash_from_rules(rules)

Loading from the stash is done by using the observation loading rule
:class:`~exa.core.observation.observation_loading_rules.LatestFromStash`, which takes
as its arguments the stash object and optionally tags used for filtering when loading from the stash:

.. code-block:: python

    ec.set_global_default_observation_loading_rules([ec.LatestFromStash(obs_stash)])
    # or in short:
    ec.set_global_observation_stash(rules)

Then observations can be saved into the stash so the next experiment loads them from there with
:class:`~exa.core.observation.observation_loading_rules.LatestFromStash` instead of accessing the database.

.. code-block:: python

    result.observations.tag(your_tags).validate().stash(obs_stash)

Once you have a final set of observations you are satisfied with, you may save them into the DB in one go:

.. code-block:: python

    obs_stash.save()

See the API docs of the above functions for more info and optional arguments.

Saving observations
-------------------

As mentioned above, the main source of new observations is the automatic calibration service of IQM QCCSW.
The sections below describe how to save and manage observations manually.

The analyze method of Experiments has the ability to summarize the analysis as one or more key observations, which
are returned in :class:`~exa.core.analyze_result.analyze_result.AnalyzeResult` instance's
:class:`LocalObservations <exa.core.observation.observation.LocalObservation>`.
LocalObservations have a parameter, associated component, and a value, and some other metadata.
They can be inspected, validated, and tagged before saving:

.. code-block:: python

   print(result.observations)
   result.observations.validate().tag(tags=["calibration trial 3"]).save()

.. note::

    Saving observations to the backend is not yet supported when connected through IQM Server.
    `example_local_storage.ipynb` demonstrates how to save observations locally. 

:meth:`~exa.core.observation.observation.LocalObservation.validate` runs any validation rules set for the
observations.
:meth:`~exa.core.observation.observation.LocalObservation.tag` attaches a list of arbitrary strings to the
observation, such that the observation can be later found by the tag or a set of tags.

One way to create and save an observation manually is to create a local observation.
This is the same class that analysis outputs.

.. code-block:: python

    from exa.core.observation import LocalObservation

    obs = LocalObservation.create(
        dut_field="QB2.flux.voltage",
        value=0.1,
        unit="V",
        configurator="John"
    )
    obs.tag(["my-manual-fix"])
    obs.save()

Or from a Setting:


.. code-block:: python

    obs = LocalObservation.from_setting(
        settings.QB2.flux.voltage.update(0.1), # settings from get_settings()
        configurator="John"
    )

Managing calibration state with tags
**************************************

Users can add their own string tags to observations to denote a specific purpose for a group of observations.

Use cases for tagging include:

- Keeping observations personal by using a unique tag, e.g. a username,
- Marking checkpoints for good calibration,
- Jumping between two groups of observations (operating points),
- Reverting to an earlier calibration state.

The workflow with tags begins by setting the loading rules such that only the latest observations with given
tags are loaded:

.. code-block:: python

    my_tags = ["Joane Doe", "trying random things", "2023-03-17"]
    ec.set_global_default_observation_loading_rules(rules=[ec.GetLatestForTags(my_tags)])


And using the same tags when saving:

.. code-block:: python

   result.observations.validate().tag(my_tags).save()


This way, all observations are saved with ``my_tags`` and only those containing ``my_tags`` will be loaded.
Thus whatever observations are saved, effectively stay in the namespace defined by ``my_tags``.
Other users using their own tags will be unaffected by the changes in this tag space.

On the other hand, if users want to share and work with the same set of observations,
they can simply use the same set of tags (or two sets that have some intersection).

It is a common situation that there is some known, good calibration set shared by many users.
A user who wants to use the known set as a starting point but not change it,
can make a copy of the known set and only change the tags with
:func:`~exa.core.database_wrapper.save_observations_with_new_tags`.

For example, let's say a good calibration has been tagged with ``known_calibration``:

.. code-block:: python

    import exa.core.database_wrapper as database
    known_calibration = ["good calibration", "2023-01-01"]
    database.save_observations_with_new_tags(tags=known_calibration, add_tags=my_tags, remove_tags=known_calibration)

After the command, observations identical to ``known_calibration`` have been created,
except they are now tagged with ``my_tags``.
Then, the user can freely save and load in their own tagspace without changing the known calibration
that others use.
