===================
Measurement Classes
===================

The Time Tagger library includes several classes that implement various measurements. All measurements are derived from a base class called :class:`IteratorBase` that is described further down. As the name suggests, it uses the `iterator` programming concept.

All measurements provide a set of methods to start and stop the execution and to access the accumulated data. In a typical application, the following steps are performed (see :ref:`example <api-example-crosscorr-measurement>`):

#. Create an instance of a measurement
#. Wait for some time
#. Retrieve the data accumulated by the measurement by calling a :code:`.getData()` method.


Available measurement classes
--------------------------------------------------------------------------------

.. note::

    In MATLAB, the Measurement names have common prefix ``TT*``. For example: ``Correlation`` is named as ``TTCorrelation``. This prevents possible name collisions with existing MATLAB or user functions.

`Correlation`_
    Computes auto- and cross-correlations between channels.
`CountBetweenMarkers`_
    Counts events on a channel within gates defined by one or two marker channels.
`Counter`_
    Counts events on one or more channels using fixed-width bins and a circular buffer output.
`Countrate`_
    Measures the average event rate on one or more channels.
`Dump`_
    Deprecated - please use :cpp:class:`FileWriter` instead. Writes raw time-tags to file in an uncompressed binary format.
`FileReader`_
    Reads time-tags from a compressed file written by the :cpp:class:`FileWriter` measurement.
`FileWriter`_
    Writes time-tags into a file with a lossless compression. It replaces the :cpp:class:`Dump` class.
`Flim`_
    Measures time histograms for fluorescence lifetime imaging.
`FrequencyCounter`_
    Measures frequency and phase evolution of periodic signals at periodic sampling intervals.
`FrequencyStability`_
    Analyzes the frequency stability of periodic signals at different time scales.
`Histogram`_
    Accumulates a histogram of time differences between two channels.
`Histogram2D`_
    Accumulates a 2D histogram of correlated time differences.
`HistogramLogBins`_
    Accumulates a histogram of time differences using logarithmic binning.
`HistogramND`_
    Accumulates an N-dimensional histogram of time differences.
`IteratorBase`
    Provides a base class for implementing custom measurements.
`PulsePerSecondMonitor`_
    Monitors the timing and stability of 1 pulse-per-second (PPS) signals.
`Sampler`_
    Samples the digital state of channels triggered by another channel.
`Scope`_
    Detects signal edges for visualization, similar to a ultrafast logic analyzer.
`StartStop`_
    Accumulates a histogram of start-stop time differences between two channels.
`SynchronizedMeasurements`_
    Synchronizes multiple measurement instances for parallel acquisition and control.
`TimeDifferences`_
    Accumulates histograms of time differences between two channels, optionally swept using one or two trigger channels.
`TimeDifferencesND`_
    Accumulates multi-dimensional histograms of asynchronous time differences.
`TimeTagStream`_
    Provides low-level access to the raw time-tag stream for custom processing.
    See :doc:`/InDepthGuides/RawTimeTagStreamAccess` to get on overview about the possibilities for the raw time-tag-stream access.


.. |common methods| replace:: :ref:`See all common methods<common-methods>`

.. _common-methods:

Common methods
--------------

.. py:class:: IteratorBase

    .. doxygenclass:: IteratorBase
        :members-only:

Event counting
--------------------------------------------------------------------------------

.. _api.Countrate:

Countrate
^^^^^^^^^

.. doxygenclass:: Countrate

.. _api.Counter:

Counter
^^^^^^^

.. doxygenclass:: Counter

.. doxygenclass:: CounterData

.. _api.CountBetweenMarkers:

CountBetweenMarkers
^^^^^^^^^^^^^^^^^^^

.. doxygenclass:: CountBetweenMarkers


Time histograms
--------------------------------------------------------------------------------

This section describes various measurements that calculate time differences between events and accumulate the results into a histogram.

.. _api.StartStop:

StartStop
^^^^^^^^^

.. doxygenclass:: StartStop

.. _api.Histogram:

Histogram
^^^^^^^^^

.. doxygenclass:: Histogram

.. _api.HistogramLogBins:

HistogramLogBins
^^^^^^^^^^^^^^^^

.. doxygenclass:: HistogramLogBins

.. doxygenclass:: HistogramLogBinsData

.. _api.Histogram2D:

Histogram2D
^^^^^^^^^^^

.. doxygenclass:: Histogram2D

.. _api.HistogramND:

HistogramND
^^^^^^^^^^^

.. doxygenclass:: HistogramND

.. _api.Correlation:

Correlation
^^^^^^^^^^^

.. doxygenclass:: Correlation

.. _api.TimeDifferences:

TimeDifferences
^^^^^^^^^^^^^^^

.. doxygenclass:: TimeDifferences

.. _api.TimeDifferencesND:

TimeDifferencesND
^^^^^^^^^^^^^^^^^

.. doxygenclass:: TimeDifferencesND

Fluorescence-lifetime imaging (FLIM)
------------------------------------

This section describes the FLIM related measurements classes of the Time Tagger API.

.. _api.FlimAbstract:

FlimAbstract
^^^^^^^^^^^^

.. doxygenclass:: FlimAbstract

.. _api.FLIM:

Flim
^^^^

.. versionchanged:: 2.7.2

.. note::

    The Flim (beta) implementation is not final yet. It has a very advanced functionality, but details are subject to change. Please give us feedback (support@swabianinstruments.com)
    when you encounter issues or when you have ideas for additional functionality.

.. image:: ../figuresPyLab/output/Flim.*

Fluorescence-lifetime imaging microscopy (FLIM) is an imaging technique
for producing an image based on the differences in the exponential decay rate
of the fluorescence from a sample.

Fluorescence lifetimes can be determined in the time domain by using a pulsed source.
When a population of fluorophores is excited by an ultrashort or delta-peak pulse of light, the time-resolved fluorescence will decay exponentially.

This measurement implements a line scan in a |FLIM| image that
consists of a sequence of pixels. This could either represent a single line
of the image, or - if the image is represented as a single meandering line -
this could represent the entire image.

We provide two different classes that support |FLIM| measurements: :cpp:class:`Flim` and :cpp:class:`FlimBase`.
:cpp:class:`Flim` provides a versatile high-level API. :cpp:class:`FlimBase` instead provides the essential functionality with no overhead
to perform Flim measurements. :cpp:class:`FlimBase` is based on a callback approach.

Please visit the Python example folder for a reference implementation.

.. _flimreplacement:

.. note::

    Up to version 2.7.0, the `Flim` implementation was very limited and has been fully rewritten in version 2.7.2.
    You can use the following 1 to 1 replacement to get the old `Flim` behavior:

    .. code:: python

        # FLIM before version 2.7.0:
        Flim(tagger, click_channel=1, start_channel=2, next_channel=3,
            binwidth=100, n_bins=1000, n_pixels=320*240)

        # FLIM 2.7.0 replacement using TimeDifferences
        TimeDifferences(tagger, click_channel=1, start_channel=2,
            next_channel=3, sync_channel=CHANNEL_UNUSED,
            binwidth=100, n_bins=1000, n_histograms=320*240)

.. doxygenclass:: Flim
    :protected-members:

.. _api.FlimFrameInfo:

FlimFrameInfo
^^^^^^^^^^^^^

.. doxygenclass:: FlimFrameInfo

.. _api.FlimBase:

FlimBase
^^^^^^^^
The `FlimBase` provides only the most essential functionality for FLIM tasks. The benefit from the reduced functionality is that it is very memory and CPU efficient. 
The class provides the `FlimBase.frameReady` callback, which must be used to analyze the data.

.. doxygenclass:: FlimBase
    :protected-members:

Phase & frequency analysis
--------------------------

This section describes measurements that expect periodic signals, e.g., oscillator outputs.

FrequencyStability
^^^^^^^^^^^^^^^^^^
.. plot:: figures_engine/FrequencyStability.py
    :align: center

.. doxygenclass:: FrequencyStability

.. doxygenclass:: FrequencyStabilityData

FrequencyCounter
^^^^^^^^^^^^^^^^
.. plot:: figures_engine/FrequencyCounter.py
    :align: center

.. doxygenclass:: FrequencyCounter

.. doxygenclass:: FrequencyCounterData

PulsePerSecondMonitor
^^^^^^^^^^^^^^^^^^^^^
.. plot:: figures_engine/PulsePerSecondMonitor.py
    :align: center

.. note::
    :cpp:class:`~Experimental::PulsePerSecondMonitor` and :cpp:class:`~Experimental::PulsePerSecondData` are part of the ``Experimental`` namespace, and 
    their properties may change in future software versions without further notice.
    They can be accessed as:

    .. code:: python
        
        TimeTagger.Experimental.PulsePerSecondMonitor(tagger, reference_channel=1, signal_channels=[2,3],
                                                      filename="output", period=1E12)


.. doxygenclass:: Experimental::PulsePerSecondMonitor

.. doxygenclass:: Experimental::PulsePerSecondData

Time-tag-streaming
--------------------------------------------------------------------------------

Measurement classes described in this section provide direct access to the time tag stream with minimal or no pre-processing.

.. _time-tag-format:

.. rubric:: Time tag format

The time tag contain essential information about the detected event and have the following format:

.. list-table::
    :widths: 10 10 30
    :header-rows: 1

    * - Size
      - Type
      - Description
    * - 8 bit
      - enum :cpp:enum:`Tag::Type`
      - overflow type
    * - 8 bit
      - --
      - reserved
    * - 16 bit
      - uint16
      - number of missed events
    * - 32 bit
      - int32
      - channel number
    * - 64 bit
      - int64
      - time in ps from device start-up


TimeTagStream
^^^^^^^^^^^^^

.. doxygenclass:: TimeTagStream

.. doxygenclass:: TimeTagStreamBuffer

.. _api-FileWriter:

FileWriter
^^^^^^^^^^

.. doxygenclass:: FileWriter

.. _api-FileReader:

FileReader
^^^^^^^^^^

.. doxygenclass:: FileReader
    :members: FileReader, getData, hasData, getConfiguration, getChannelList, getLastMarker

.. _api-dump:

Dump
^^^^

.. doxygenclass:: Dump

.. _api-scope:

Scope
^^^^^

.. doxygenclass:: Scope

.. doxygenstruct:: Event

.. doxygenenum:: State

.. _api-sampler:

Sampler
^^^^^^^

.. doxygenclass:: Sampler



Helper classes
--------------

.. _api.SynchronizedMeasurements:

SynchronizedMeasurements
^^^^^^^^^^^^^^^^^^^^^^^^

.. doxygenclass:: SynchronizedMeasurements

.. _api.CustomMeasurements:

Custom Measurements
^^^^^^^^^^^^^^^^^^^

The class :class:`CustomMeasurement` allows you to access the raw time tag stream with very little overhead.
By inheriting from :class:`CustomMeasurement`, you can implement your fully customized measurement class. The :meth:`CustomMeasurement.process` method of this class
will be invoked as soon as new data is available.

.. note:: This functionality is only available for C++, C# and Python.
    You can find examples of how to use the :class:`CustomMeasurement` in your examples folder.


.. class:: CustomMeasurement(tagger)

    :param TimeTaggerBase tagger: TimeTagger object

    The constructor of the :class:`CustomMeasurement` class itself takes only the parameter `tagger`. When you sub-class your own measurement,
    you can add to your constructor any parameters that are necessary for your measurement. You can find detailed examples in your example folder.

    |common methods|

    .. method:: process(incoming_tags, begin_time, end_time)

        :param incoming_tags: Tag[][struct{type, missed_events, channel, time}], the chunk of time-tags to be processed in this call of
            :meth:`process`. This is an external reference that is shared with other measurements and might be overwritten for the next
            call. So if you need to store tags, create a copy.

        :param int begin_time: The begin time of the data chunk.

        :param int end_time: The end time of the data chunk

        Override the :meth:`process` method to include your data processing.
        The method will be called by the Time Tagger backend when a new chunk of time-tags is available.
        You are free to execute any code you like, but be aware that this
        is the critical part when it comes to performance. In Python, it is advisable to use
        :func:`numpy.array` for calculation or even pre-compiled code with
        `Numba <https://numba.pydata.org/>`_ if an explicit iteration of the tags is necessary. Check the examples in your examples folder
        carefully on how to design the :meth:`process` method.


        .. note::
            In Python, the `incoming_tags` are a :ref:`structured Numpy array <numpy:structured_arrays>`.
            You can access single tags as well as arrays of tag entries directly:

            .. code:: python

                first_tag = incoming_tags[0]
                all_timestamps = incoming_tags['time']

    .. attribute:: mutex

        Context manager object (see :ref:`python:typecontextmanager`) that locks the mutex when used and automatically unlocks it when the code block exits.
        For example, it is intended for use with Python's :ref:`"with" keyword <python:with>` as

        .. code-block:: python

            class MyMeasurement(CustomMeasurement):

                def getData(self):
                    # Acquire a lock for this instance to guarantee that 
                    # self.data is not modified in other parallel threads.
                    # This ensures to return a consistent data.
                    with self.mutex:
                        return self.data.copy()
                            

