# MATLAB/Octave Interface

The Matlab or Octave interface to **tasgrid** consists of several functions that call various **tasgrid** commands and read and write matrix files. Unlike most Matlab interfaces, this is code does not use .mex files, but rather system commands and text files. In a nut shell, Matlab **tsgMakeXYZ** functions take a user specified name and create a Matlab object and a file generated by **tasgrid** option **-gridfile** (or **TasmanianSparseGrid::write()** function). The Matlab object is used to reference the specific grid file and is needed by most other functions. Here are some notes to keep in mind:

* The interface requires that Matlab is able to call external commands, specifically the **tasgrid** executable.
* The interface also requires access to a folder where the files can be written.
* The Matlab work folder option in the *install* scrip as well as CMake allows you to automatically specify where the temporary files will be stored. The *make matlab* target in the GNU make engine sets the work folder in a sub-folder of the Tasmanian source directory. In either case, the default folder can be changed by manually editing **tsgGetPaths.m**.
* Each grid has a user specified name, that is a string which gets pre-pended at the beginning of the file name.
* The **tsgDeleteGrid()**, **tsgDeleteGridByName()** and **tsgListGridsByName()** functions allow for cleaning the files in the temporary folder.
* Every Tasmanian-Matlab function corresponds to one **tasgrid** command.
* Every function comes with help comments that can be accessed by typing
```
  help tsgFunctionName
```
* Note that it is recommended to add the folder with the Tasmanian interface to the Matlab path, otherwise the **addpath()** command has to be called after every restart.
* All input variables follow naming convention where the first character specifies the type of the variable:
    * **i** stands for integer
    * **s** stands for string
    * **f** stands for real number
    * **l** stands for list
    * **v** stands for vector, i.e., row or column matrix
    * **m** stands for matrix, i.e., two dimensional array
* See the notes about the Fortran 2003 interface regarding the row-major matrix format


### List of Matlab functions and corresponding C++ API

```
  tsgCancelRefine.m                     ->  clearRefinement()
  tsgEstimateAnisotropicCoefficients.m  ->  estimateAnisotropicCoefficients()
  tsgEvaluateHierarchy.m                ->  evaluateHierarchicalFunctions()
  tsgEvaluate.m                         ->  evaluateBatch()
  tsgGetHCoefficients.m                 ->  getHierarchicalCoefficients()
  tsgGetInterpolationWeights.m          ->  getInterpolationWeights()
  tsgGetNeededPoints.m                  ->  getNeededPoints()
  tsgGetPoints.m                        ->  getPoints()
  tsgGetPolynomialSpaces.m              ->  getGlobalPolynomialSpace()
  tsgGetQuadrature.m                    ->  getQuadratureWeights()/getPoints()
  tsgIntegrate.m                        ->  integrate()
  tsgLoadHCoefficients.m                ->  setHierarchicalCoefficients()
  tsgLoadValues.m                       ->  loadNeededPoints()
  tsgMakeFourier.m                      ->  makeFourierGrid()
  tsgMakeGlobal.m                       ->  makeGlobalGrid()
  tsgMakeLocalPolynomial.m              ->  makeLocalPolynomialGrid()
  tsgMakeQuadrature.m                   ->  (see tasgrid -makequadrature)
  tsgMakeSequence.m                     ->  makeSequenceGrid()
  tsgMakeWavelet.m                      ->  makeWaveletGrid()
  tsgMergeRefine.m                      ->  mergeRefinement()
  tsgRefineAnisotropic.m                ->  setAnisotropicRefinement()
  tsgRefineSurplus.m                    ->  setSurplusRefinement()
  tsgSummary.m                          ->  printStats()
```

The Matlab functions wrap around **tasgrid**, thus what applies to one applies to the other. See the **tasgrid** notes about the order of complex Fourier coefficients and make quadrature.


### Function tsgCoreTests()

```
  tsgCoreTests()
```

Performs a series of tests of the Matlab interface. If some tests are failing, the installation is incomplete or corrupted.


### Function tsgGetPaths()

```
  [ sFiles, sTasGrid ] = tsgGetPaths()
```

This function returns two strings:

* **sTasGrid** is a string containing the path to the **tasgrid** executable (including the name of the executable).
* **sFiles** is the path to a folder where Matlab has read/write permission. Files will be created and deleted in this folder.


### Function tsgReadMatrix() and tsgWriteMatrix()

Those functions are used internally to read from or write to matrix files. Those functions should not be called directly.

### Function tsgCleanTempFiles()

Those functions are used internally to clean the temporary files.

### Function tsgListGridsByName()

Scans the work folder and lists the existing grids regardless whether those are currently associated with Matlab objects. The names can be used for calls to **tsgDeleteGridByName()** and **tsgReloadGrid()**.

### Function tsgDeleteGrid()/tsgDeleteGridByName()

Deleting the Matlab object doesn't remove the files from the work folder, thus **tsgDeleteGrid()** has to be explicitly called to remove the files associated with the grid. If the Matlab object has been lost (i.e., cleared by accident), then the grid files can be deleted by specifying just the name for **tsgDeleteGridByName()**, see also **tsgListGridsByName()**.

### Function tsgReloadGrid()

Creates a new Matlab object file for a grid with existing files in the work folder. This function can restore access to a grid if the grid object has been lost. This function can also create aliases between two grids which can be dangerous, see the section about avoiding problems. This function can also be used to gain access to a file generated by **tasgrid -gridfile** option or **TasmanianSparseGrid::write()** function, just generate the file, move it to the work folder, rename it to `<name>_FileG`, and call
```
lGrid = tsgReloadGrid( <name> )
```

### Function tsgCopyGrid()

Creates a duplicate of an existing grid, this function creates a new Matlab object and a new grid file in the work folder.

### Function tsgWriteCustomRuleFile()

Writes a file with a custom quadrature or interpolation rule, see the Custom Rule File Format section.


### Function tsgExample()

```
tsgExample()
```

This function contains sample code that mimics the C++ examples and serves as a demonstration on the proper way to call the Matlab functions.


### GPU acceleration

```
  lGrid = tsgMakeLocalPolynomial( ... )
  lGrid.gpuDevice = 0;
  result = tsgEvaluate(lGrid, ...)
```

If the **lGrid** object has a **gpuDevice** field, then the corresponding GPU will be used for the evaluations. Run **tsgCoreTest()** to see a list of detected CUDA devices.


### Saving a Grid

You can save the **lGrid** object just like any other Matlab object. However, a saved grid has two components, the **lGrid** object and the files associated with the grid that are stored in the folder specified by **tsgGetPath()**. The files in the temporary folder will be persistent until either **tsgDeleteGrid()** is called or the files are manually deleted. The only exception is that the **tsgExample()** function will overwrite any grids with names starting with `_tsgExample1` through `_tsgExample10`. Note that modifying **tsgGetPath()** may result in the code not being able to find the needed files and hence the grid object may be invalidated.

### Avoiding Some Problems

* Make sure to call **tsgDeleteGrid()** as soon as you are done with a grid, this will avoid clutter in the temporary folder.
* If you clear an **lGrid** object without calling **tsgDeleteGrid()** (i.e., you exit Matlab without saving), then make sure to use **tsgListGridsByName()** and **tsgDeleteGridByName()** to safely delete the *lost* grids.
* Working with the Matlab interface is very similar to working with dynamical memory, where the data is stored on the disk as opposed to the RAM and the **lGrid** object is the pointer. Also, the grids are associated by name as opposed to a memory address.
* If multiple users are sharing the same temporary folder, then it would be useful if they come up with a naming convention that prevents two users from using the same grid name. For example, instead of both users creating a grid named *mygrid1*, the users should name their grids *johngrid1* and *janegrid1*.
* All of the grid data for all of the grids is stored in the same folder. Anyone with access to the temporary folder has full access to all of the sparse grid data.
* If two users have separate copied of **tsgGetPaths()**, then they can use separate storage folders without any of the multi-user considerations. This is true even if all other files are shared, including the **tasgrid** executable and Tasmanian libraries.
