model.func()
Add different types of functions.
Syntax
model.func().create(<tag>,<type>);
model.func(<tag>).create(<tag>,<type>);
model.func(<tag>).createPlot(<pgtag>)
model.func(<tag>).label(<label>)
model.func(<tag>).model(<mtag>)
model.func(<tag>).set(property,<value>);
model.func(<tag>).set("funcname",<funcname>)
model.func(<tag>).discardData()
model.func(<tag>).importData()
model.func(<tag>).refresh()
model.func(<tag>).image()
model.func(<tag>).run()
 
model.func(<tag>).model()
model.func(<tag>).getType(property);
model.func(<tag>).functionNames()
model.func(<tag>).getAllowedPropertyValues(property);
Description
model.func().create(<tag>,<type>) creates a new function of type <type> with the tag <tag>. The types can be one of the following strings: Analytic, Elevation, External, Image, Interpolation, GaussianProcess (requires Uncertainty quantification module), LeastSquares, MATLAB (requires LiveLink™ for MATLAB®), Piecewise, GaussianPulse, Ramp, Random, Rectangle, Step, Triangle, and Wave. In addition, model.create(<tag>,"FunctionSwitch") creates a function switch. You can add other functions to a function switch:
model.func().create("sw1", "FunctionSwitch");
model.func("sw1").create("int1", "Interpolation");
model.func("sw1").create("an1", "Analytic");
model.func("sw1").create("rn1", "Random");
model.func(<tag>).createPlot(<pgtag>) creates a plot group with the tag pgtag with a plot of the function. The method returns the plot group.
model.func(<tag>).label(<label>) sets a label for the function.
model.func(<tag>).model(<mtag>) sets the model component node of the function. 
model.func(<tag>).set(property,<value>) sets the value of a property of the function. See the available properties for each type of function below.
model.func(<tag>).set("funcname",<funcname>) sets the operator name of the function. The default operator name is <tag>.
model.func(<tag>).model() returns the model component node tag.
 model.func(<tag>).getType(property) retrieves a value of a function property.
model.func(<tag>).importData() imports the file that the function references into the model. This is possible for interpolation, elevation, and image functions. The importData() method also works for some physics features.
model.func(<tag>).discardData() discards the data imported with importData(). This is possible for interpolation, elevation, and image functions. The discardData() method also works for some physics features.
model.func(<tag>).refresh() reevaluates the file for functions that read files (Elevation, Image, and Interpolation).
Use the model.func(<tag>).image() methods for plotting and exporting images showing plots of the functions. See Plotting and Exporting Images.
model.func(<tag).run() performs optimization or training for functions that need to process their input data before they can be evaluated. (Least-squares fit and Gaussian process).
model.func(<tag>).functionNames() returns an array containing the function names that the function feature defines. Most functions always return an array of length one, but interpolation function features, for example, can define an arbitrary number of function names.
model.func(<tag>).getAllowedPropertyValues(property) returns the set of allowed values for a property if the set is a finite set of strings; otherwise, it returns null.
When using a local table the interpolation function uses the funcname property to set the function name. When the data comes from a file or a result table, the name is specified in the funcs string matrix property. This is necessary because there can be more than one function.
What properties that are available depends on the type of function. The following function types are available:
Analytic
Generate an analytic function using a symbolic expression.
automatic | manual
Interpolation
Generate an interpolation function. You can use several interpolation and extrapolation methods.
on | off
on | off
If source is file and defvars is set to true, the spatial coordinate variables are used as default arguments to the function if no arguments are supplied in a call to it.
point | comma
none | const | interior | linear | value
If source is table and defineinv is on: The name of the inverse function.
The name of the function if source is table or function.
Used source is file; the first column contains function names and the second column contains the positions in the file where the corresponding function is defined
neighbor | linear | piecewisecubic | cubicspline
If true, reinterpolate interpolation data on computational mesh. Available if defvars is true and frame is set to mesh.
automatic | uniform
auto | on | off
Apply scaling of data if the bounding box of the interpolation points has a bad aspect ratio (auto), always apply the scaling (on), or turn off scaling altogether (off).
table | file | resultTable | function
model | user
grid | sectionwise | spreadsheet
LeastSquares
Create a function based on a least-squares fit of the function’s input data to a parameterized function.
point | comma
The expression for the defined function(s), as an array of alternating column names from the input data and expressions. Using the setEntry, getEntryKeys, getEntryKeyIndex methods makes it easier to work with this array.
file | table | resultTable
GaussianProcess
Generate a Gaussian process regression (Kriging) function. Creating or training a Gaussian process function requires the Uncertainty quantification module. Using an already created and trained Gaussian process function does not require the Uncertainty Quantification Module.
se | matern32 | matern52 | nn
Type of covariance function to use in the Gaussian process regression. Use se for Squared exponential, matern32 for Matérn 3/2, matern52 for Matérn 5/2 and nn for Single-layer neural network.
If true, the related error estimation function(s) are made available.
point | comma
const | linear | quadratic
automatic | manual
Controls how the number of restart points during training is determined. If automatic, the number is calculated from the number of function arguments. If manual, the number is given by the manualrestarthypergpnumber property.
file | resultTable
none | new | results table
If validation is not none, specifies the table where verification error summary is stored. Use none to not generate the table data. Use new to create a new table for the data. Use a results table tag to store the data in an existing table.
none | new | results table
If validation is not none, specifies the table where detailed verification error information is stored. Use none to not generate the table data. Use new to create a new table for the data. Use a results table tag to store the data in an existing table.
manual | currenttime
Specifies how the random seed for training is determined. If manual, the seed is given by the lastinternalseed property. If currenttime, the seed is computed from the current time when training is started.
manual | currenttime
Specifies how the random seed for validation is determined. If manual, the seed is given by the lastinternalseedtest property. If currenttime, the seed is computed from the current time when training is started.
none | random | fraction | last | table
none: No validation is performed.
random: Use a random sample of the input data and exclude the corresponding values from the training data. The size of the sample is fraction times the number of input data points.
fraction: Use every 1/fraction values from the input data and exclude the corresponding values from the training data.
last: Use the last part of the input data and exclude the corresponding values from the training data. The size of the last part is fraction times the number of input data points.
table: Use a results table as validation data.
Changes in the following properties take effect without retraining the function: definestddev, stddevsuffix, funcs, plotargs, unit.
The Uncertainty Quantification Module User’s Guide explains the theory behind Gaussian process regression. See Surrogate Models — Gaussian Process.-
Piecewise
Generate a piecewise interpolation function, which is created by splicing together several functions, each defined on one interval.
const | interior | none | periodic | value
none | cont | contd1 | contd2
GaussianPulse
Generate a Gaussian pulse function. This function is the common bell-shaped curve (Gaussian function).
The integral value, when normalization is set to integral.
The peak value, when normalization is set to peak.
integral | peak
Ramp
Generate a ramp function.
Table 2-78: Ramp Properties
Random
Generate a random function. The random function can have a uniform or normal distribution.
Table 2-79: random properties
uniform | normal
Normal Distribution
Generate a normal distribution function.
rn_ + the tag name
Rectangle
Generate a rectangle-shaped function.
Step
Generate a step function.
Table 2-82: Step properties
Triangle
Generate a triangle-shaped function.
External
Generate an external function that interfaces to other external functions written in the C language.
An external function is a function defined in a shared library written by the user. The shared library must define the following three functions with C linkage:
int init(const char *str) is called when the function is initialized with the string from the Initialization data field. It returns a nonzero value in case of success and zero in case of failure. This function might be called several times; it is always called before solving a model that uses the function.
int eval(const char *func, int nArgs, const double **inReal, const double **inImag, int blockSize, double *outReal, double *outImag) is called for elementwise evaluation of the function func called with nArgs arguments of length blockSize. The array inReal contains the real parts of the arguments; it has length nArgs, and each element has length blockSize.
If the arguments are all-real, then inImag is null; otherwise it contains the imaginary parts of the arguments. If the function evaluation is successful, 1 is returned if it resulted in an all-real array and 2 is returned if it resulted in a complex array. The function should return 0 in case of error. In case of a real result, the function values should be written to the array outReal. In case of a complex result, the real parts of the function should be written to outReal and the imaginary parts to outImag. The outReal and outImag arrays both have length blockSize. All matrices are allocated and deallocated by COMSOL.
const char *getLastError() returns the last error that has occurred. A null or empty string is returned if no error has occurred. Calling init() or eval() must set the last error string to "" or null. All memory allocation of this string is handled by the shared library. There is no localization of the error messages.
If you are using Microsoft Visual Studio to compile your library, you can declare the functions as __declspec(dllexport) to export them from the DLL.
An example of a library that defines a function called extsinc that computes the sinc function (sin(x)/x):
#include <math.h>
#include <stdlib.h>
#include <string.h>
 
#ifdef _MSC_VER
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
 
static const char *error = NULL;
 
EXPORT int init(const char *str) {
  return 1;
}
 
EXPORT const char * getLastError() {
  return error;
}
 
EXPORT int eval(const char *func,
                              int nArgs,
                              const double **inReal,
                              const double **inImag,
                              int blockSize,
                              double *outReal,
                              double *outImag) {
  int i, j;
 
  if (strcmp("extsinc", func) == 0) {
    if (nArgs != 1) {
      error = "One argument expected";
      return 0;
    }
    for (i = 0; i < blockSize; i++) {
      double x = inReal[0][i];
      outReal[i] = (x == 0) ? 1 : sin(x) / x;
    }
    return 1;
  }
  else {
    error = "Unknown function";
    return 0;
  }
}
To compile this function into a library, place it in ext.c and proceed as follows depending on platform:
See https://www.comsol.com/system-requirements for information about supported compiler versions.
-
-
cd to the directory that contains ext.c.
-
cl /MT /c ext.c
-
link /OUT:ext.dll /DLL ext.obj
-
cd to the directory that contains ext.c.
-
icc -fPIC -c ext.c
-
icc -shared -fPIC -Wl,-z -Wl,defs -o ext.so ext.o -ldl
-
cd to the directory that contains ext.c.
-
icc -fPIC -c ext.c
-
icc -dynamiclib -fPIC -o ext.dylib ext.o
For other compilers, refer to the compiler’s documentation for instructions how to compile and create a shared library.
Elevation
Generate an elevation function by importing geospatial elevation data from digital elevation models (DEM files).
const | interior | linear | value
neighbor | linear
Image
Generate an image function from a BMP, GIF, JPEG, PNG, or TIFF file.
Table 2-86: Image properties
none | manual
const | interior | linear | value
neighbor | linear
automatic | manual
MATLAB
Declare use of function in MATLAB. This requires the LiveLink™ for MATLAB®.
Table 2-87: MATLAB properties
Wave
Use a wave function to generate a wave-shaped function (waveform). The wave shape can be a sawtooth, sine wave, square wave, or triangle wave.
Table 2-88: wave properties
sawtooth | sine | square | triangle
Compatibility
For the wave function, the freq property with a default value of 1 in previous versions of COMSOL Multiphysics has been replaced by period with a default value of 2π in version 6.0.
See Also
model.material()