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, Interpolation, Piecewise, GaussianPulse, Ramp, Rectangle, Step, Triangle, Wave, NormalDistribution, Random, External, MATLAB (requires LiveLink™ for MATLAB®), Elevation, Image, LeastSquares, GaussianProcess (requires the Uncertainty Quantification Module to create and train but not to use a created and trained function), PolynomialChaosExpansion (requires the Uncertainty Quantification Module to create and train but not to use a created and trained function), DNN, and PartialFractionFit. 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");
Use model.func("sw1").set("definecases", true); to instantiate all functions for all cases in a function sweep. By default, not all of them are instantiated.
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, Gaussian Process, Polynomial Chaos Expansion, and DNN).
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.
Function features can have associated problem features. To access the list of problem features for a function feature, use:
model.func(<tag>).problem();
To access a specific problem feature, use:
model.func(<tag>).problem(<problem_tag>);
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
Create an analytic function using a symbolic expression.
automatic | manual
Contains one value for each function argument. A false value means that the corresponding function argument will be constant when plotting. The constant value is taken from the lower limit value in the plotargs property. Constant arguments do no use an axis in the plot. Up to 3 axes are supported when plotting. Specify using setIndex("plotaxis", false, 2), for example.
Interpolation
Generate an interpolation function. You can use several interpolation and extrapolation methods.
on | off
If source is set to table: Whether to define the inverse function.
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
The extrapolation value if extrap is set to 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
The data format if source is set to file.
Contains the point/value pairs if source is set to table.
none | logarithmic
none | logarithmic
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-79: Ramp Properties.
Rectangle
Generate a rectangle-shaped function.
Step
Generate a step function.
Table 2-81: Step properties.
Triangle
Generate a triangle-shaped function.
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-83: wave properties.
sawtooth | sine | square | triangle
NormalDistribution
Generate a normal distribution function.
rn_ + the tag name
Random
Generate a random function. The random function can have a uniform or normal distribution.
Table 2-85: random properties.
Random seed, if seedtype is set to manual.
If true, the random seed will be used.
manual | currenttime
The random seed type, if seedactive is true.
uniform | normal
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.
MATLAB
Declare use of function in MATLAB. This requires the LiveLink™ for MATLAB®.
Table 2-87: MATLAB properties.
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-89: Image properties.
none | manual
const | interior | linear | value
neighbor | linear
automatic | manual
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
If true, causes lines in the training data that contain any NaN or Inf values to be ignored. If false, NaN and Inf values are treated as an error.
const | linear | quadratic
Contains one value for each function argument. A false value means that the corresponding function argument will be constant when plotting. The constant value is taken from the lower limit value in the plotargs property. Constant arguments do no use an axis in the plot. Up to 3 axes are supported when plotting. Specify using setIndex("plotaxis", false, 2), for example.
Contains one value for each function argument. For arguments that do not have an axis in the plot (see plotaxis), this property specifies the fixed value to use in the plot.
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, and unit.
The Uncertainty Quantification Module User’s Guide explains the theory behind Gaussian process regression. See Surrogate Models — Gaussian Process.
PolynomialChaosExpansion
Generate a polynomial chaos expansion (PCE) function. Creating or training a PCE function requires the Uncertainty Quantification Module. Using an already created and trained PCE function does not require the Uncertainty Quantification Module.
Defines the probability distributions for the function arguments, as an array of alternative column names and distribution types. Valid distribution types are uniform, normal, lognormal, gamma, beta, weibull, and gumbel. See also the description of the args property.
point | comma
If true, causes lines in the training data that contain any NaN or Inf values to be ignored. If false, NaN and Inf values are treated as an error.
Defines how the lower bounds of the valid range for the function arguments are determined, as an array of alternative column names and CDF (cumulative distribution function) values. Valid CDF values are 0.3, 0.1, 0.01, 0.001, 1e-4, 1e-5, 1e-6, 1e-7, and manual. Not used if distributionselection is uniform or beta. See also the description of the args property.
warning | cancel
Decides how to handle out-of-range and extrapolated training data. If outofrange is cancel, the training is canceled. If outofrange is warning, the training continues, but a warning is added under the function feature. In either case, details about the problematic training data points are logged in the log window.
auto | manual
If pcesettings is set to auto, the training will automatically determine the required polynomial degree needed to obtain suitable accuracy. If pcesettings is set to manual, the maximum polynomial degree is determined by the polydegreespce and qnorm settings.
Contains one value for each function argument. A false value means that the corresponding function argument will be constant when plotting. The constant value is taken from the lower limit value in the plotargs property. Constant arguments do no use an axis in the plot. Up to 3 axes are supported when plotting. Specify using setIndex("plotaxis", false, 2), for example.
Contains one value for each function argument. For arguments that do not have an axis in the plot (see plotaxis), this property specifies the fixed value to use in the plot.
The maximum polynomial degree to use when pcesettings is set to manual. See also the Uncertainty Quantification Module User’s Guide.
Controls the hyperbolic truncation of polynomial terms used for functions having more than one argument. Only used when pcesettings is set to manual. See also the Uncertainty Quantification Module User’s Guide.
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.
Defines the upper bound of the valid input range for the function arguments as an array of alternative column names and upper bounds. Only relevant if distributionselection is set to uniform or beta, or if ucdfselection is set to manual. See also the description of the args property.
Defines how the upper bounds of the valid range for the function arguments are determined as an array of alternative column names and CDF (cumulative distribution function) values. Valid CDF values are 0.7, 0.9, 0.99, 0.999, 1-1e-4, 1-1e-5, 1-1e-6, 1-1e-7, and manual. Not used if distributionselection is set to uniform or beta. See also the description of the args property.
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: funcs, plotargs, unit.
The Uncertainty Quantification Module User’s Guide explains the theory behind PCE. See Surrogate Models — Polynomial Chaos Expansion.
DNN
Generate a deep neural network (DNN) function. A DNN function provides training and validation using a deep neural network (DNN) for use with surrogate model training, for example. Deep neural networks form a class of machine learning algorithms similar to the artificial neural network and aims to mimic the information processing of the brain.
array of the following values: tanh | none | relu | elu | sigmoid
mse | mae
The momentum, if optmethod is set to sgd.
adam | sgd
Contains one value for each function argument. A false value means that the corresponding function argument will be constant when plotting. The constant value is taken from the lower limit value in the plotargs property. Constant arguments do no use an axis in the plot. Up to 3 axes are supported when plotting. Specify using setIndex("plotaxis", false, 2), for example.
Contains one value for each function argument. For arguments that do not have an axis in the plot (see plotaxis), this property specifies the fixed value to use in the plot.
The result table to use as source, if source is set to resultTable.
The random seed for training, if useseed is set to manual.
The random seed for validation, if useseedvalidation is set to manual.
file | resultTable
manual | currenttime
Specifies how the random seed for training is determined. If manual, the seed is given by the rndseed 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 rndseed property. If currenttime, the seed is computed from the current time when training is started.
random | fraction | last | table
PartialFractionFit
Create an partial fraction fit function.
point | comma
file | resultTable
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()