.. _theano_type:

======================
Making the double type
======================


.. _type_contract:

Type's contract
===============

In Theano's framework, a ``Type`` (:api:`gof.type.Type`)
is any object which defines the following
methods. To obtain the default methods described below, the Type should
be an instance of ``Type`` or should be an instance of a
subclass of ``Type``. If you will write all methods yourself,
you need not use an instance of ``Type``.

Methods with default arguments must be defined with the same signature,
i.e.  the same default argument names and values. If you wish to add
extra arguments to any of these methods, these extra arguments must have
default values.

.. class:: PureType

    .. method:: filter(value, strict=False)

      This casts a value to match the Type and returns the
      casted value. If ``value`` is incompatible with the Type,
      the method must raise an exception. If ``strict`` is True, ``filter`` must return a
      reference to ``value`` (i.e. casting prohibited)

      We need to define ``filter`` with two arguments. The second argument
      must be called ``strict`` (Theano often calls it by keyword) and must
      have a default value of ``False``.

    .. method:: is_valid_value(value)

      Returns True iff the value is compatible with the Type. If
      ``filter(value, strict = True)`` does not raise an exception, the
      value is compatible with the Type.

      *Default:* True iff ``filter(value, strict = True)`` does not raise
      an exception.

    .. method:: values_eq(a, b)

      Returns True iff ``a`` and ``b`` are equal.

      *Default:* ``a == b``

    .. method:: values_eq_approx(a, b)

      Returns True iff ``a`` and ``b`` are approximately equal, for a
      definition of "approximately" which varies from Type to Type.

      *Default:* ``values_eq(a, b)``

    .. method:: make_variable(name=None)

      Makes a :term:`Variable` of this Type with the specified name, if
      ``name`` is not ``None``. If ``name`` is ``None``, then the Variable does
      not have a name. The Variable will have its ``type`` field set to
      the Type object.

      *Default:* there is a generic definition of this in Type. The
      Variable's ``type`` will be the object that defines this method (in
      other words, ``self``).

    .. method:: __call__(name=None)

      Syntactic shortcut to ``make_variable``.

      *Default:* ``make_variable``

    .. method:: __eq__(other)

      Used to compare Type instances themselves

      *Default:* ``object.__eq__``

    .. method:: __hash__()

      Types should not be mutable, so it should be OK to define a hash
      function.  Typically this function should hash all of the terms
      involved in ``__eq__``.

      *Default:* ``id(self)``

For each method, the *default* is what ``Type`` defines
for you. So, if you create an instance of ``Type`` or an
instance of a subclass of ``Type``, you
must define ``filter``. You might want to override ``values_eq_approx``,
as well as ``values_eq``. The other defaults generally need not be
overridden.

For more details you can go see the documentation for :ref:`type`.


Defining double
===============

We are going to base Type ``double`` on Python's ``float``. We
must define ``filter`` and shall override ``values_eq_approx``.


**filter**

.. code-block:: python

    # Note that we shadow Python's function ``filter`` with this
    # definition.
    def filter(x, strict=False):
        if strict:
            if isinstance(x, float):
                return x
            else:
                raise TypeError('Expected a float!')
        else:
            return float(x)

If ``strict == True`` we need to return ``x``. If ``strict == True`` and ``x`` is not a
``float`` (for example, ``x`` could easily be an ``int``) then it is
incompatible with our Type and we must raise an exception. If
``strict == False`` then we are allowed to cast ``x`` to a ``float``,
so if ``x`` is an ``int`` it we will return an equivalent ``float``.


**values_eq_approx**

.. code-block:: python

   def values_eq_approx(x, y, tolerance=1e-4):
       return abs(x - y) / (abs(x) + abs(y)) < tolerance

The second method we define is ``values_eq_approx``. This method
allows approximate comparison between two values respecting our Type's
constraints. It might happen that an optimization changes the computation
graph in such a way that it produces slightly different variables, for
example because of numerical instability like rounding errors at the
end of the mantissa. For instance, ``a + a + a + a + a + a`` might not
actually produce the exact same output as ``6 * a`` (try with a=0.1),
but with ``values_eq_approx`` we don't necessarily mind.

We added an extra ``tolerance`` argument here. Since this argument is
not part of the API, it must have a default value, which we
chose to be 1e-4.

.. note::

    ``values_eq`` is never actually used by Theano, but it might be used
    internally in the future. Equality testing in
    :ref:`DebugMode <debugmode>` is done using ``values_eq_approx``.

**Putting them together**

What we want is an object that respects the aforementioned
contract. Recall that Type defines default implementations for all
required methods of the interface, except ``filter``. One way to make
the Type is to instantiate a plain Type and set the needed fields:

.. code-block:: python

   from theano import gof

   double = gof.Type()
   double.filter = filter
   double.values_eq_approx = values_eq_approx


Another way to make this Type is to make a subclass of ``gof.Type``
and define ``filter`` and ``values_eq_approx`` in the subclass:

.. code-block:: python

   from theano import gof

   class Double(gof.Type):

       def filter(self, x, strict=False):
           if strict and not isinstance(x, float):
               raise TypeError('Expected a float!')
           return float(x)

       def values_eq_approx(self, x, y, tolerance=1e-4):
           return abs(x - y) / (abs(x) + abs(y)) < tolerance

   double = Double()

``double`` is then an instance of Type ``Double``, which in turn is a
subclass of ``Type``.

There is a small issue with defining ``double`` this way. All
instances of ``Double`` are technically the same Type. However, different
``Double`` Type instances do not compare the same:

>>> double1 = Double()
>>> double2 = Double()
>>> double1 == double2
False

Theano compares Types using ``==`` to see if they are the same.
This happens in DebugMode.  Also, Ops can (and should) ensure that their inputs
have the expected Type by checking something like ``if x.type == lvector``.

There are several ways to make sure that equality testing works properly:

 #. Define ``Double.__eq__`` so that instances of type Double
    are equal. For example:

    .. code-block:: python

        def __eq__(self, other):
            return type(self) is Double and type(other) is Double

 #. Override ``Double.__new__`` to always return the same instance.
 #. Hide the Double class and only advertise a single instance of it.

Here we will prefer the final option, because it's the simplest.
Often Ops in the Theano code define the ``__eq__`` function though.


Untangling some concepts
========================

Initially, confusion is common on what an instance of Type is versus
a subclass of Type or an instance of Variable. Some of this confusion is
syntactic. A Type is any object which has fields corresponding to the
functions defined above. The Type class provides sensible defaults for
all of them except ``filter``, so when defining new Types it is natural
to subclass Type. Therefore, we often end up with Type subclasses and
it is can be confusing what these represent semantically. Here is an
attempt to clear up the confusion:


* An **instance of Type** (or an instance of a subclass)
  is a set of constraints on real data. It is
  akin to a primitive type or class in C. It is a *static*
  annotation.

* An **instance of Variable** symbolizes data nodes in a data flow
  graph. If you were to parse the C expression ``int x;``, ``int``
  would be a Type instance and ``x`` would be a Variable instance of
  that Type instance. If you were to parse the C expression ``c = a +
  b;``, ``a``, ``b`` and ``c`` would all be Variable instances.

* A **subclass of Type** is a way of implementing
  a set of Type instances that share
  structural similarities. In the ``double`` example that we are doing,
  there is actually only one Type in that set, therefore the subclass
  doesn't represent anything that one of its instances doesn't. In this
  case it is a singleton, a set with one element. However, the
  :class:`TensorType`
  class in Theano (which is a subclass of Type)
  represents a set of types of tensors
  parametrized by their data type or number of dimensions. We could say
  that subclassing Type builds a hierarchy of Types which is based upon
  structural similarity rather than compatibility.


Final version
=============

.. code-block:: python

   from theano import gof

   class Double(gof.Type):

       def filter(self, x, strict=False):
           if strict and not isinstance(x, float):
               raise TypeError('Expected a float!')
           return float(x)

       def values_eq_approx(self, x, y, tolerance=1e-4):
           return abs(x - y) / (abs(x) + abs(y)) < tolerance

       def __str__(self):
           return "double"

   double = Double()


We add one utility function, ``__str__``. That way, when we print
``double``, it will print out something intelligible.

