.. _chapter_grids:

********************************************************************************
Scalar Grids
********************************************************************************

A grid is a data container that holds a value at every point in a
three dimensional lattice. The simplest type of value to hold is a
floating point value. In **OEChem TK**, these are called
:oe:cls:`OEScalarGrids<OESystem::OEScalarGrid>`.
:oe:cls:`OEScalarGrids<OESystem::OEScalarGrid>` are inherently cubic.

The following fundamental parameters define a grid:

:Dimension: The number of grid points per axis
:Midpoint:  The center of the grid in Cartesian space
:Spacing:   The length between grid points

.. _figure_gridfundamentals:

.. figure:: images/OEGridParameters.png
   :scale:  100
   :align:  center

   **Fundamental Grid Parameters**


:oe:src:`Listing 1<SNIPPET-ScalarGridCtor>` demonstrates how to
:oe:meth:`construct<OESystem::OEScalarGrid::Constructors>` a grid with
64 points in each direction, a midpoint at the origin, and a spacing
of 0.5 between each point in the grid.

.. oe:source:: ScalarGridCtor.cpp
   :language: c++
   :refnum:   1
   :caption:  Constructing a scalar grid
   :frag:     SNIPPET

.. oe:source:: ScalarGridCtor.py
   :language: python
   :refnum:   1
   :caption:  Constructing a scalar grid
   :frag:     SNIPPET

.. oe:language:: python

	:ref:`Full listing. <listing-ScalarGridCtor.py>`



.. oe:source:: ScalarGridCtor.java
   :language: java
   :refnum:   1
   :caption:  Constructing a scalar grid
   :frag:     SNIPPET

.. oe:source:: ScalarGridCtor.cs
   :language: csharp
   :refnum:   1
   :caption:  Constructing a scalar grid
   :frag:     SNIPPET

.. note::

   The memory footprint of the grid is determined by the
   dimensions. It is easy to create grids that are too large for
   memory. For example, the grid in :oe:src:`Listing 1<SNIPPET-ScalarGridCtor>`
   will consume :math:`64^3 * sizeof(float) = 1048576 bytes = 1 MB` of
   memory for this nominally sized grid.

Minimum and maximum
-----------------------

Every grid can have its maximum and minimum vales reported by GetXMax,
GetXMin etc. The image ``Grid coordinates`` shows a 2D representation
for simplicity. It shows 4 grid points centered at (0,0), with a
spacing of 1.0. Each grid point will have spatial coordinates
(0.5,0.5), (-0.5,0.5) etc. However each grid point lies at the center
of a pixel (or rather a voxel in 3D). Any property that falls into the
area (volume) of that grid point is mapped to that grid point. This
means that the maximum value of x is the extent of the grid, not just
the maximum value of the grid point coordinates. In this case that
value is 1.0.

.. _figure_minmaxgrid:

.. figure:: images/OEGrid.*
   :align:  center

   **Grid coordinates**

.. _section_dataaccess:

Data Access
================================================================================

Grids provide three ways to index data inside the grid. They are
ordered here by speed of access, i.e., grid elements perform simple
pointer arithmetic where spatial coordinates require floating point
computation.

:Grid Element: Index into the underlying data array
:Grid Indices: Unsigned integers less than the dimension for that axis
:Spatial Coordinates:
   Cartesian coordinates of any point inside the grid, the grid will
   determine the closest grid point

Spatial Coordinates
-----------------------

Assuming ``grid`` is already filled with relevant values,
:oe:src:`Listing 2<SNIPPET-SpatialGet-SpatialCoordAccess>` demonstrates
how to retrieve the grid value closest to the atoms in the molecule
``mol``.

.. oe:source:: SpatialCoordAccess.cpp
   :language: c++
   :noindent:
   :refnum:   2
   :frag:     SNIPPET-SpatialGet
   :caption:  Getting values associated with coordinates

.. oe:source:: SpatialCoordAccess.py
   :language: python
   :noindent:
   :refnum:   2
   :frag:     SNIPPET-SpatialGet
   :caption:  Getting values associated with coordinates

.. oe:source:: SpatialCoordAccess.java
   :language: java
   :noindent:
   :refnum:   2
   :frag:     SNIPPET-SpatialGet
   :caption:  Getting values associated with coordinates

.. oe:source:: SpatialCoordAccess.cs
   :language: csharp
   :noindent:
   :refnum:   2
   :frag:     SNIPPET-SpatialGet
   :caption:  Getting values associated with coordinates

Spatial coordinates can also be used to set data on the grid.
:oe:src:`Listing 3<SNIPPET-SpatialSet-SpatialCoordAccess>` demonstrates
how to assign an atom's partial charge to the grid point it is closest
to.

.. oe:source:: SpatialCoordAccess.cpp
   :language: c++
   :noindent:
   :refnum:   3
   :frag:     SNIPPET-SpatialSet
   :caption:  Setting values associated with coordinates

.. oe:source:: SpatialCoordAccess.py
   :language: python
   :noindent:
   :refnum:   3
   :frag:     SNIPPET-SpatialSet
   :caption:  Setting values associated with coordinates

.. oe:source:: SpatialCoordAccess.java
   :language: java
   :noindent:
   :refnum:   3
   :frag:     SNIPPET-SpatialSet
   :caption:  Setting values associated with coordinates

.. oe:source:: SpatialCoordAccess.cs
   :language: csharp
   :noindent:
   :refnum:   3
   :frag:     SNIPPET-SpatialSet
   :caption:  Setting values associated with coordinates


.. note::

   In the preceding two code fragments bounds checking was explicitly
   performed using the
   :oe:meth:`IsInGrid<OESystem::OEGridBase::IsInGrid>`
   method. Accessing data outside the grid is undefined behavior
   (usually a segmentation fault). However,
   :oe:meth:`IsInGrid<OESystem::OEGridBase::IsInGrid>` can become an
   expensive operation if performed excessively. One way to avoid this
   cost is to make sure your grid is big enough to enclose the object
   being worked on. See
   :oe:func:`OESystem::OEMakeGridFromCenterAndExtents` for an example
   of constructing a grid that covers the entire molecule to ensure no
   spatial coordinate access is outside the bounds of the grid.


Grid Indices
-----------------------

Grid indices are faster than spatial coordinates because there is no
floating point arithmetic to perform. Grid indices make it easy to
iterate over the neighbors of any particular point in the
grid. :oe:src:`Listing 4<SNIPPET-NeighborPoints-NeighborPoints>`
demonstrates iterating over all 27 grid points adjacent to and
including the grid point given by the grid indices: ``ix``, ``iy``,
``iz``.

.. oe:source:: NeighborPoints.cpp
   :language: c++
   :noindent:
   :refnum:   4
   :frag:     SNIPPET-NeighborPoints
   :caption:  Iterating over neighbor points

.. oe:source:: NeighborPoints.py
   :language: python
   :noindent:
   :refnum:   4
   :frag:     SNIPPET-NeighborPoints
   :caption:  Iterating over neighbor points

.. oe:source:: NeighborPoints.java
   :language: java
   :noindent:
   :refnum:   4
   :frag:     SNIPPET-NeighborPoints
   :caption:  Iterating over neighbor points

.. oe:source:: NeighborPoints.cs
   :language: csharp
   :noindent:
   :refnum:   4
   :frag:     SNIPPET-NeighborPoints
   :caption:  Iterating over neighbor points


Grid Elements
-----------------------

Grid values are actually stored in a large one dimensional block of
memory. The fastest way to access all the data is to linearly scan
through memory. :oe:src:`Listing 5<SNIPPET-SquarePoints-SquarePoints>`
demonstrates how to square every value in the grid.

.. oe:source:: SquarePoints.cpp
   :language: c++
   :noindent:
   :refnum:   5
   :frag:     SNIPPET-SquarePoints
   :caption:  Squaring every grid value

.. oe:source:: SquarePoints.py
   :language: python
   :noindent:
   :refnum:   5
   :frag:     SNIPPET-SquarePoints
   :caption:  Squaring every grid value

.. oe:source:: SquarePoints.java
   :language: java
   :noindent:
   :refnum:   5
   :frag:     SNIPPET-SquarePoints
   :caption:  Squaring every grid value

.. oe:source:: SquarePoints.cs
   :language: csharp
   :noindent:
   :refnum:   5
   :frag:     SNIPPET-SquarePoints
   :caption:  Squaring every grid value

.. oe:language:: c++

   Direct access to the memory is given by the
   :oe:meth:`GetValues<OESystem::OEFixedGrid::GetValues>` method. This
   allows faster memory functions, *e.g.*, memset and memcpy, to be
   applied to grid values. The following code is the quickest way to
   zero out all the grid values.

   .. oe:source:: SquarePoints.cpp
      :language: c++
      :noindent:
      :frag:     SNIPPET-ZeroValues
      :caption:  Clearing all grid data

.. _section_grid_input_output:

Input and Output
================================================================================

The following grid file formats are supported:

.. table::  **OEChem TK grid file format support**

   ===========================================  ======================  =====================================================================================  =======  ======
   Grid File Type (or reader)                   File Extension(s)       Description                                                                            Read     Write
   ===========================================  ======================  =====================================================================================  =======  ======
   :oe:const:`OESystem::OEGridFileType::Grasp`  ``.phi``                GRASP                                                                                  Yes      Yes
   :oe:const:`OESystem::OEGridFileType::GRD`    ``.grd``                OpenEye Binary format                                                                  Yes      Yes
   :oe:const:`OESystem::OEGridFileType::Ascii`  ``.agd``                OpenEye ASCII format                                                                   Yes      Yes
   :oe:const:`OESystem::OEGridFileType::CCP4`   ``.map .ccp .ccp4``     CCP4 format                                                                            Yes      Yes
   :oe:const:`OESystem::OEGridFileType::XPLOR`  ``.xplor .xplmap``      XPLOR format                                                                           Yes      No
   :oe:func:`OESystem::OEReadMTZ`               ``.mtz``                `MTZ <http://www.ccp4.ac.uk/html/mtzformat.html>`_ crystallographic reflection format  Yes      No
   ===========================================  ======================  =====================================================================================  =======  ======

The ASCII format (``.agd``) was developed by OpenEye to allow for easy
integration with other software. The following is an example of the
ASCII output for a grid centered at the origin, 2 points along
each axis, a spacing of 0.5, and every value zero.

.. code-block:: bash

   Title: Example Grid
   Mid:     0.000000     0.000000     0.000000
   Dim:      2      2      2
   Spacing:     0.500000
   Values:
   0.000000e+00
   0.000000e+00
   0.000000e+00
   0.000000e+00
   0.000000e+00
   0.000000e+00
   0.000000e+00
   0.000000e+00

:oe:src:`Listing 6<SNIPPET-ASCIIWriter>` is the code used to write the ASCII
format out. It is provided here to leave no doubt as to how to
inter-operate with the format.

.. oe:source:: ASCIIWriter.cpp
   :language: c++
   :noindent:
   :refnum:   6
   :caption:  Writing the ASCII format
   :frag:     SNIPPET

.. oe:source:: ASCIIWriter.py
   :language: python
   :noindent:
   :refnum:   6
   :caption:  Writing the ASCII format
   :frag:     SNIPPET

.. oe:source:: ASCIIWriter.java
   :language: java
   :noindent:
   :refnum:   6
   :caption:  Writing the ASCII format
   :frag:     SNIPPET

.. oe:source:: ASCIIWriter.cs
   :language: csharp
   :noindent:
   :refnum:   6
   :caption:  Writing the ASCII format
   :frag:     SNIPPET

.. _section_grids_genericdata:

Grid as Generic Data
================================================================================

Grids can also be attached to molecules and then written out to
OEBinary (:file:`.oeb`) files. A visualizer can then read in the
molecule and grid without any other means of making the association.
:oe:src:`Listing 7<SNIPPET-AttachGaussianGrid-AttachGaussianGrid>`
demonstrates how to attach a Gaussian grid to the molecule it was
created from.

The grid is attached to a molecule using the 'generic data' interface
provided by the :ref:`OEBase <OESystem_OEBase>` base class.  This allows an
arbitrary number of grids (or any type of data) to be attached to
molecules.
Since all grids also derive from :ref:`OEBase <OESystem_OEBase>` generic
data can be attached to grids as well allowing for arbitrarily complex
data hierarchies.

.. oe:source:: AttachGaussianGrid.cpp
   :language: c++
   :noindent:
   :refnum:   7
   :frag:     SNIPPET-AttachGaussianGrid
   :caption:  Attaching a grid to a molecule

.. oe:source:: AttachGaussianGrid.py
   :language: python
   :noindent:
   :refnum:   7
   :frag:     SNIPPET-AttachGaussianGrid
   :caption:  Attaching a grid to a molecule

.. oe:source:: AttachGaussianGrid.java
   :language: java
   :noindent:
   :refnum:   7
   :frag:     SNIPPET-AttachGaussianGrid
   :caption:  Attaching a grid to a molecule

.. oe:source:: AttachGaussianGrid.cs
   :language: csharp
   :noindent:
   :refnum:   7
   :frag:     SNIPPET-AttachGaussianGrid
   :caption:  Attaching a grid to a molecule


.. seealso::

   * :ref:`chapter_genericdata` chapter
