Industrial C Code Generation

SymbolicC, a C "Wrapper"

Yves Papegay

INRIA Sophia Antipolis, COPRIN - France

In this presentation, we describe the functionnalities of the SymbolicC package: a Mathematica wrapper of the C langage, making easier the generation of C code when such a code has to obey to several quality rules, implementation specifications, and development guidelines or/and when it has to be connected to and compiled with external C code.

<< SymbolicC`

Motivations

for using C

for using Mathematica to generate C

for using SymbolicC

A Simple Example

Write a C function computing ((∫_0)^x) f(t) dt with f(t) = (sin^5)(t).

By Hand

Integrate[Sin[t]^5, {t, 0, x}] // CForm

#include "mdefs.h"
double f(double x)
{
double y;
y = (-5*Cos(x))/8. + (5*Cos(3*x))/48. - Cos(5*x)/80. ;
return(y) ;
}

With Splice

#include "mdefs.h"
double f(double x)
{
double y;
y = <* Integrate[Sin[t]^5, {t,0,x}] *> ;
return(y) ;
}

Splice[\,\]

With SymbolicC

p = 
      ProgramC[IncludeC["mdefs.h"], 
        FunctionC[double, "f", {DeclareC[double, x]}, 
          BlockC[{DeclareC[double, y], 
              AssignC[y, Integrate[Sin[t]^5, {t, 0, x}]], 
              ReturnC[y]}]]]

CCode[p]

C Generation

A Complex Process with three Components

see MathCode example Hessian.nb or Mathematica Compile and CForm functions.

An intermediate Mathematica Representation of C

SymbolicC

Representation of C

SymbolicC provides a complete coverage of ANSI C and preprocessor instructions (SymbolicC/CWrapper.nb)

SymbolicCKeywords

Export

SymbolicC provides a translation CCode and an export CWrite function. (SymbolicC/CodeGen . nb)

Bonus

SymbolicC provides a few macros helpful for generation of SymbolicC objects.

SymbolicMCKeywords

MainMC[{instr1, instr2}]

Two more Examples

Academic

Given an expression and a number N,  
    generate a C function computing all its derivatives of order N

expr = 5  x Cos[y + z] - y^3  Sin[x z]

GenCode[expr_, N_Integer] := 
      CCode[With[{inputs = Union[Cases[expr, _Symbol, Infinity]]}, 
          ProgramC[IncludeC["math.h"], 
            FunctionMC[double, PtrC["gen_diff" <> ToString[N]], 
              Map[{#, double} &, inputs], 
              Flatten[{DeclareC[Nest[ArrayC[#, Length[inputs]] &, double, N], 
                    m], MapIndexed[
                    Function[{s, t}, 
                      AssignC[Fold[ArrayC[#1, #2 - 1] &, m, t], s]], 
                    D[expr, {inputs, N}], {N}], 
                  ReturnC[PtrC[m]]}]]]]]

GenCode[expr, 1]

Industrial

Conclusion

I probably forgot to talk about :

UpValues[IncludeC]

mailto : Yves . Papegay@sophia . inria . fr

http: // gforge . inria . fr/projects/
          mathematools/

Use SymbolicC and contribue to it (we need an Import)