Example Worksheet - Maple Help
For the best experience, we recommend viewing online help using Google Chrome or Microsoft Edge.

Online Help

All Products    Maple    MapleSim


The CodeGeneration Package

The CodeGeneration package is a collection of functions that translate Maple code to other languages. This worksheet provides several simple examples to get you started with CodeGeneration.

Additional information and examples can be found in the help pages for the package and for the individual package members. The Code Generation Assistant also offers a convenient interface to code generation tools.

Introduction

The following command allows you to use the short form of the function names in the CodeGeneration package. The  functions C, CSharp, Fortran, Java, JavaScript, Matlab, Perl, Python, R, and VisualBasic provide translation to the programming languages implied by their names.

 

withCodeGeneration:

 

With the CodeGeneration package, you can translate an expression, a list of equations representing a computation sequence, a procedure, or a module to any of the target languages.

• 

Expressions are translated into assignments to variables with automatically generated names.

• 

Lists of equations are translated into a sequence of assignments.

• 

Procedures and modules are translated into their equivalent in the target language.

 

Javaⅇx+y

cg = Math.exp(x + y);

JavaScriptxⅇx

cg0 = x * Math.exp(x);

 

Cx=2,y=x+z,z=xy+5

x = 2;

y = x + z;
z = x * y + 5;

 

CSharpx=1,y=2 z,z=x +1

x = -1;

y = 2 * z;
z = x + 1;

 

VisualBasicx=1,y=x+z,z=y+5x

x = 1

y = x + z
z = y + 5 * x

 

f:=procu,v     return u*v+u  v end proc:

Perlf

#!/usr/bin/perl


sub f
{
  local($u, $v) = @_;
  return($u * $v + $u - $v);
}

 

Pythonf

def f (u, v):

    return(u * v + u - v)

 

Matlab15.0x2.5y

cg1 = [0.150e2 x; -0.25e1 y;];

 

R15.04.22.51.0

cg2 <- matrix(c(0.150e2,-0.25e1,0.42e1,-0.10e1),nrow=2,ncol=2)

 

The CodeGeneration package can translate only a subset of the Maple language. Limitations and special features of the individual target languages are described on the detail pages for each target (for example, CDetails).

Options for Customizing the Output

There are fundamental differences between the Maple language and the target languages supported by CodeGeneration that make direct translation difficult in some cases. For example, Maple is an interpreted language; it has a rich set of types, and allows implicit returns. The target languages support a more limited set of basic types and require variable and return types to be known at compile time.  

 

As a consequence of these differences, the CodeGeneration functions are often required to choose the most suitable translation in cases where more than one result is possible. Occasionally, the choices made may not be the ones expected or desired. However, there are a number of options that you can use to customize the output. Options common to all the CodeGeneration functions are described on the CodeGenerationOptions help page.

Controlling Type Translation

 

In the following example, all the parameters are assigned a floating-point type by default.

 

f:=procx&comma;y&comma;z     return x&ast;y  y&ast;z&plus;x&ast;zend proc&colon;Cf

double f (double x, double y, double z)
{
  return(x * y - y * z + x * z);
}

 

The default type given to untyped variables can be changed by using the defaulttype option.

 

Cf&comma;defaulttype&equals;integer

int f (int x, int y, int z)

{
  return(x * y - y * z + x * z);
}

 

CodeGeneration attempts to deduce the types of untyped variables. The default type is given only to those variables left untyped after the automatic type deduction process. In the following example, the parameters y and z are given a floating-point type because they are in an expression involving the float variable x. Thus, the default type, integer, is not assigned.

 

f:=procx::float&comma;y&comma;z     return x&ast;y  y&ast;z&plus;x&ast;zend proc&colon;Cf&comma;defaulttype&equals;integer

double f (double x, double y, double z)
{
  return(x * y - y * z + x * z);
}

 

You can turn off the automatic type deduction system by using the deducetypes=false option. In the following example, parameters y and z are now given the default type.

 

Cf&comma;defaulttype&equals;integer&comma;deducetypes&equals;false

double f (double x, int y, int z)

{
  return(x * (double) y - (double) (y * z) + x * (double) z);
}

 

You can turn off explicit type coercion using the coercetypes=false option.

 

Cf&comma;defaulttype&equals;integer&comma;deducetypes&equals;false&comma;coercetypes&equals;false

double f (double x, int y, int z)

{
  return(x * y - y * z + x * z);
}

 

You can obtain more control over how types are assigned by declaring the parameter, local variable, and return types explicitly in procedures or by using the declare option with expressions.

 

C1&plus;x&plus;y&comma;declare&equals;x::float&comma;y::integer

cg3 = 0.1e1 + x + (double) y;

Other Commonly Used Options

In the following example, the optimize option specifies that the computation sequence should be optimized before translation to Java.

 

cs:=s&equals;1.0&plus;x&comma;t&equals;lnx&ExponentialE;x&comma;r&equals;&ExponentialE;x&plus;xt&colon;Javacs&comma;optimize

s = 0.10e1 + x;
t1 = Math.log(x);
t2 = Math.exp(-x);
t = t1 * t2;
r = x * t + t2;

 

The CodeGeneration functions normally print the formatted results. You can use the output=string option to specify that a string containing the result should be returned. The output option can also be used to print the result to a file.  

 

s:=Javalogx&plus;siny&comma;output&equals;string

s:=cg4 = Math.log(x) + Math.sin(y);

(2.2.1)

sJavaScriptlogx&plus;siny&comma;output&equals;string

s:=cg5 = Math.log(x) + Math.sin(y);

(2.2.2)

 

There are many other options not described here. For information about the available options, refer to the CodeGenerationOptions help page.

Using CodeGeneration with Other Maple Functions

 

By combining the CodeGeneration functions with other Maple functions, you can easily generate substantial pieces of C, Fortran, Java, Matlab, or R code to solve specific problems. Several examples are given below. Note that to translate Maple commands directly into commands in a target language, it is necessary in some cases to use unevaluation quotes ( ' ' ) to surround the command. If the unevaluation quotes are not used, the result of running the Maple command on the argument is translated.

A Spline Example

 

Use the CurveFitting[Spline] function to fit a natural cubic spline through a given list of points.

 

sCurveFittingSpline0&comma;0&comma;1&comma;1&comma;2&comma;4&comma;3&comma;3&comma;4&comma;2&comma;v

s:=&lcub;2328v3&plus;528vv<15928v3&plus;12314v224128v&plus;4114v<24528v3272v2&plus;100728v37514v<3928v3&plus;277v245128v&plus;1777otherwise

(3.1.1)

 

Turn the resulting expression, a piecewise function, into a procedure by using the unapply function.

 

punapplys&comma;v

p:=v&rarr;piecewisev<1&comma;2328v3&plus;528v&comma;v<2&comma;5928v3&plus;12314v224128v&plus;4114&comma;v<3&comma;4528v3272v2&plus;100728v37514&comma;928v3&plus;277v245128v&plus;1777

(3.1.2)

 

Translate the procedure to Fortran, while declaring that v should be a float parameter.

 

Fortranp&comma;declare&equals;v::float

Warning, procedure/module options ignored

      doubleprecision function p (v)
        doubleprecision v
        if (v .lt. 0.1D1) then
          p = 0.23D2 / 0.28D2 * v ** 3 + 0.5D1 / 0.28D2 * v
          return
        else if (v .lt. 0.2D1) then
          p = -0.59D2 / 0.28D2 * v ** 3 + 0.123D3 / 0.14D2 * v ** 2 - 0.
     #241D3 / 0.28D2 * v + 0.41D2 / 0.14D2
          return
        else if (v .lt. 0.3D1) then
          p = 0.45D2 / 0.28D2 * v ** 3 - 0.27D2 / 0.2D1 * v ** 2 + 0.100
     #7D4 / 0.28D2 * v - 0.375D3 / 0.14D2
          return
        else
          p = -0.9D1 / 0.28D2 * v ** 3 + 0.27D2 / 0.7D1 * v ** 2 - 0.451
     #D3 / 0.28D2 * v + 0.177D3 / 0.7D1
          return
        end if
      end

An Automatic Differentiation Example

 

Create a procedure, f.

 

f:=procx::float&comma;y::float     local tfloat&semi;     texp&minus;x&semi;     return y&ast;t&plus;t&semi; end proc&colon;

 

Compute the gradient (vector of partial derivatives) of f by using the codegen[GRADIENT] function. Although using the codegen[C] and codegen[fortran] functions are not recommended any longer, the codegen package still contains a number of useful utilities that can be used in combination with the CodeGeneration package.

 

gcodegenGRADIENTf

g:=procx::float&comma;y::floatlocaldfr0&comma;t::float&semi;t:=exp&minus;x&semi;dfr0:=array1..1&semi;dfr0&lsqb;1&rsqb;:=y&plus;1&semi;return&minus;dfr0&lsqb;1&rsqb;&ast;exp&minus;x&comma;tend proc

(3.2.1)

 

Translate the gradient to C, optimizing the Maple code before translation.

 

Cg&comma;optimize

#include <math.h>


void g (double x, double y, double cgret[2])
{
  double dfr0[1];
  double t;
  t = exp(-x);
  dfr0[0] = 0;
  dfr0[0] = y + 0.1e1;
  cgret[0] = -dfr0[0] * t;
  cgret[1] = t;
}

Finding Eigenvalues of a Matrix

Declare a matrix:

MatlabMatrix3113&colon;

MatlabMatlabMatrix&semi;

cg6 = [3 1; 1 3;];

 

Find the eigenvalues of the matrix:

Matlab&lpar;&apos;LinearAlgebra:-Eigenvalues&apos;&lpar;MatlabMatrix&rpar;&rpar;

cg7 = eig([3 1; 1 3;]);

Computing Summary Statistics

Code generation for R can translate many commands from the Statistics package. In the following example, some summary statistics are computed on a list of value.

Declare a list of values:

RList4&comma;8&comma;15&comma;16&comma;23&comma;42&colon;

 

Translate the list to R code:

RRList&semi;

cg8 <- c(4,8,15,16,23,42)

 

Compute some summary statistics.

R&apos;Statistics:-FivePointSummary&apos;RList

cg9 <- fivenum(c(4,8,15,16,23,42))

 

Compare median and mean to see the differences in translations depending on if unevaluation quotes are used or not; when quotes are used, the command itself is translated to the target language.

R&apos;Statistics:-Mean&apos;RList

cg10 <- mean(c(4,8,15,16,23,42))

 

In the case of not using unevaluation quotes, the result of a Maple computation (Median) is translated.

RStatistics:-MedianRList

cg11 <- 0.155000000000000000e2

 

It is also possible to translate some visualization commands:

R&apos;Statistics:-Histogram&apos;RList&comma; color&equals;Orange

cg12 <- hist(c(4,8,15,16,23,42), col = "Orange")

See Also

CodeGeneration,  CodeGeneration[Options]

 

Return to Index for Example Worksheets