# Calling Nexus from Matlab

#### Contents

In this post we will see how to embed Nexus within Matlab. The idea is to operate with Nexus and its full process integration capabilities from within the Matlab Command Windows as you will do with native Matlab function.
This is made possible by the Nexus SDK technology that allow to embed Nexus within third applications among which Matlab, Python and VBScript.
We will see how to use the so-called Nexus Toolbox for Matlab with a simple practical example: the minimization of the Rosenbrock function.

##### The Problem

In this example, we aim at find the minimum of the so-called Rosembrock function in the 2D space X,Y. Details of the problem can be found here
The function is plotted below using Grapheme (or equivalently the Nexus plot module). On the left a slice of the function at Z=100 show how flat the function is when approaching the minimum located at [1.0,1.0].

##### The Objective Function

As discussed above, the objective is to minimize the Rosenbrock function in a 2D X-Y space. As input variables are passed as input as a single vector, we max x as x(1) and y as x(2). The resulting Matlab function objfnc.m is reported below:

```% iChrome Ltd (www.iChrome.com)
% Rosenbrock function
%
function F = objfnc(x)
F = 100*(x(2)-x(1)^2)^2 + (x(1) - 1)^2;
end
```

##### The Callback Function

Defining a call-back function is optional.
The call-back function is a Matlab function to be optionally defined by the user to be called by Nexus at runtime. The function receives an input the result tables from the optimization task at each new evaluation. The function should have prototype: callBackFunction( results ) being results a data structure containing the result tables of the current task. In this case, we want to use a callback function to plot optimization results on the fly, without waiting the optimization to be completed.

```% iChrome Ltd (www.iChrome.com)
% Callback function to draw objective function and Simplex radius
% vs number of iterations
%
function [] = callback(results)
global fig;

if( isempty(fig) )
fig = figure();
end
if( isfield(results,'summary' ) )
summary = getfield(results,'summary' );
if( isfield(summary,'iteration') && isfield(summary,'objective') )
figure(fig);

subplot(2,1,1);
plot( getfield(summary,'iteration'), getfield(summary,'objective'), 'r' );
title('Objective vs. Iterations');

subplot(2,1,2);

drawnow();
end
end
end
```

Note:
Callback functions are good for demonstration purposes but it clearly slow down Nexus when performing the optimization as we ask the kernel of Nexus to wait for Matlab plotting capabilities to complete before starting a new iteration. Generally speaking this is acceptable for many of the practical applications where time is spend to compute real-world objective functions. However, be moderately careful not to blindly use callbacks.

##### Running the Optimisation

Before attempting to run the optimization via the Nexus toolbox, please make sure you have configured the toolbox correctly as briefly described in section Configuring the Toolbox below.
From the main Matlab Command Windows, we start defining the optimization domain, which is x=[-1.0,3.0] and y=[-1.0,3.0].

```>> LB = [-1.0, -1.0];
>> UB = [ 3.0,  3.0];
```

The Simplex (Nelder-Mead) method available in Nexus requires a set of N+1 starting points (being N the number of design variable) in order to start a new minimization search. Hence we define a set of 3 random starting points X0.

```>> X0 = 2.0*rand(3,2);
```

The Nexus Toolbox allows configuring the most common optimization algorithms by means of the utility function nxParameterGet(..). The function is defined to preconfigure a parameter structure with the default parameters of the algorithm whose name is provided as input, Simplex in this specific case. In order to use the callback function defined above, we need to slightly modify the default parameters by assigning the callback function and by specifying how often this should be called. In this specific case we wish the callback function to be called at each new function evaluation. In order to have a better view of the tasks that the Nexus kernel is performing in the background, we also set the verbose flag to 1. This assure a more granular and detailed output.

```>> params = nxParamGet('Simplex');
>> params = nxParamSet(params,'cbackname','callback');
>> params = nxParamSet(params,'cbackfreq',1);
>> params = nxParamSet(params,'verbose',1);
```

We are now ready to start the optimization. We do that from the Matlab command line:

```>> [x,f,c,results] = nxOptim('objfnc',X0,LB,UB,params);
```

The verbose flag set to 1 will allow to print out running messages as the optimization progress.

The function returns when the optimization is completed however the callback function will create and update a Matlab plot to display the objective function and the Simplex radius as a function of the iterations as shown on the right.

Last, we should release Nexus resources (and licenses). To do that we call the nxRelease() API function.

```>> nxRelease();
```

#### Conclusive Remarks

In this post I showed you how to call (embed) Nexus from within Matlab and how to use default optimization settings to perform the minimization of the so-called Rosembrok function in the 2D domain.
Using the default settings, the Simplex method (a modified version of the Nelder-Mead algorithm) of Nexus returns in 28 iterations with:

x = 0.9970 0.9936, f = 2.0685e-05

which is inline with the default tolerance on the Objective function set at 1.0e-4. More accurate results can be achieved changing the default convergence settings via calls to nxParamSet(…). As an example, by setting the followings:

```>> params = nxParamSet(params,'objTol',1e-9);
>> params = nxParamSet(params,'varTol',1e-10);
```

and relaunching the optimization search, the Simplex method reaches convergence after 37 iterations at:

x = 1.0000 1.000, f = 3.7706e-010

#### Installing the Toolbox

If not already installed, first step is to install the Toolbox. From the Nexus main menu: Help=>Install New Software. If not already installer (i.e. if visible on the list) select the Matlab Toolbox from the iChrome Nexus: Tools list as shown on the right. The installer will prepare Nexus to run embedded from Matlab and will copy the toolbox installer within the \tools\matlab folder of your main Nexus installation. You should then go within that folder and launch the installer for Matlab (i.e. iChrome_nx2Matlab.exe).

The installer will guide you through the installation process of the Toolbox.

Make sure to provide the right path for both Nexus and the Matlab versions you wish the toolbox to work with. Please be aware the Nexus and Matlab installation shall use the same architecture, this means that you need the 32bit installation of Nexus if you wish to use the toolbox under Matlab 32bit. Similarly, you need a 64bit installation of Nexus if you use the toolbox under Matlab 64bit.

To make Nexus and the toolbox working together, you should also make sure that environment variable NEXUS_PATH is set correctly and added to the system PATH. This is done by the toolbox installer if flag Configure System path for Matlab to locate Nexus is selected.

#### Configuring the Toolbox

Once properly installer, you can check if the toolbox is working by calling one of the following Nexus API functions from within Matlab:

```>> nxGetVersion();
>> nxGetBuildId();
```

The first return the current version of Nexus used by the toolbox, the second an iChrome identifier for the installed build of the Nexus libraries – which if you like can be read as your actual micro-version.

If both version and build code are returned without errors, the toolbox has been successfully installed and correctly linked to the Nexus kernel. A final step is required to make sure you can use the plugin. From within the Matlab Command Windows:

```>> nxStartupSetup();
```

You will be asked for default configuration and the setup utility will configure the toobox to its defaults. You can find more details on how to personalize and re-configure the toolbox in the user manuals.