Changeset 13771


Ignore:
Timestamp:
Oct 16, 2019 1:57:00 PM (5 weeks ago)
Author:
randersson
Message:

#5792 Merged trunk into stable

Location:
branches/stable
Files:
55 edited
12 copied

Legend:

Unmodified
Added
Removed
  • branches/stable

  • branches/stable/CHANGELOG.txt

    r13687 r13771  
    11================= Unreleased ==================
     2# Feature ; Minor ; Compiler; #5837
     3Added a pre-compiled evaluator used for evaluating external functions
     4during the compilation (for performance). Activated by the option
     5"external_constant_evaluation_dynamic"
     6
    27# Fixed ; Minor ; Compiler ; #5855
    38Nominal are now always positive in the FMI model description.
  • branches/stable/Compiler/ModelicaCBackEnd/src/jastadd/CCodeGen/CCodeGenExternalCeval.jrag

    r12306 r13771  
    248248        Collection<ExternalArgument> res = new LinkedHashSet<>();
    249249        if (hasReturnVar()) {
    250             res.add(getReturnVar().externalArgument());
    251         }
     250            res.add(returnVarToSerialize());
     251        }
     252        res.addAll(argVarsToSerialize());
     253        return res;
     254    }
     255   
     256    syn ExternalArgument FExternalStmt.returnVarToSerialize() = getReturnVar().externalArgument();
     257    syn Collection<ExternalArgument> FExternalStmt.argVarsToSerialize() {
     258        Collection<ExternalArgument> res = new LinkedHashSet<>();
    252259        for (FExp e : getArgs()) {
    253260            res.add(e.externalArgument());
     
    288295        }
    289296        return functionArgs;
     297    }
     298   
     299
     300    syn String FType.cMappedTypeString() = cMappedTypeStringScalar() + (isArray() ? "v" : "");
     301
     302    syn String FType.cMappedTypeStringScalar() {
     303        throw new InternalCompilerError("cMappedTypeStringScalar() is not supported for class type " + getClass().getSimpleName());
     304    }
     305    eq FArrayType.cMappedTypeStringScalar() = getFPrimitiveType().cMappedTypeStringScalar();
     306    eq FIntegerType.cMappedTypeStringScalar() = "i";
     307    eq FEnumType.cMappedTypeStringScalar() = "i";
     308    eq FBooleanType.cMappedTypeStringScalar() = "i";
     309    eq FRealType.cMappedTypeStringScalar() = "d";
     310    eq FStringType.cMappedTypeStringScalar() = "s";
     311    eq FRecordType.cMappedTypeStringScalar() {
     312        String o = "R[";
     313        for (FRecordComponentType rType: getComponents()) {
     314                o = o.concat(rType.getFType().cMappedTypeStringScalar());
     315                o = o.concat(",");
     316        }
     317        return o.concat("]");
     318    }
     319   
     320    syn String FExternalStmt.functionReturnArgSerialized() {
     321        if (hasReturnVar()) {
     322            return returnVarToSerialize().type().cMappedTypeString();
     323        } else {
     324            return "void";
     325        }
     326    }
     327   
     328    syn String FExternalStmt.functionArgsSerialized() {
     329        String input = "";
     330        for (ExternalArgument var : argVarsToSerialize()) {
     331            if (var.isOutput()) {
     332               input = input.concat("*");
     333            }
     334            input += var.type().cMappedTypeString() + ",";
     335        }
     336        return input;
    290337    }
    291338   
     
    347394            }
    348395        }
     396    }
     397   
     398    public String FClass.externalCTypes() {
     399        StringBuilder sb = new StringBuilder();
     400        for (FExternalStmt stmt : myExternals()) {
     401            if (stmt.dynamicEvaluatorEnabled()) {
     402                sb.append(stmt.getName());
     403                sb.append("\n");
     404                sb.append(stmt.functionReturnArgSerialized());
     405                sb.append("\n");
     406                sb.append(stmt.functionArgsSerialized());
     407                sb.append("\n");
     408            }
     409        }
     410        return sb.toString();
    349411    }
    350412
  • branches/stable/Compiler/ModelicaCBackEnd/templates/ceval_external_template.c

    r11746 r13771  
    1414*/
    1515
    16 #include <stdio.h>
    17 #include <stdlib.h>
    18 #include <string.h>
    19 #include "jmi.h"
    20 #include "jmi_dyn_mem.h"
    21 #include "ModelicaUtilities.h"
    22 #include <fcntl.h>
     16#include "jmi_evaluator_util.h"
     17
     18/* Must be defined here in order to override the methods from jmi_global.c */
     19void jmi_global_log(int warning, const char* name, const char* fmt, const char* value) {
     20    _jmi_global_log(warning, name, fmt, value);
     21}
     22void jmi_throw() {
     23    _jmi_throw();
     24}
     25void* jmi_global_calloc(size_t n, size_t s) {
     26    return _jmi_global_calloc(n,s);
     27}
    2328
    2429$ECE_external_includes$
    2530 
    26 /* Manual debugging */
    27 #define JMCEVAL_DEBUG 0
    28 #define JMCEVAL_DBGP(x) if (JMCEVAL_DEBUG) { printf(x); fflush(stdout);}
    29 
    30 /* Format specifier when printing jmi_real_t */
    31 #define JMCEVAL_realFormat "%.16f"
    32 
    3331/* Used record definitions */
    3432$ECE_record_definitions$
    35 
    36 /* Parses ND dimensions into dimension buffer d*/
    37 #define JMCEVAL_parseArrayDims(ND) \
    38     for (di = 0; di < ND; di++) { scanf("%d",&d[di]); }
    39 
    40 /* Parse/print basic types */
    41 double JMCEVAL_parseReal() {
    42     /* Char buffer when reading jmi_real_t. This is necessary
    43        since "%lf" is not allowed in c89. */
    44     char buff[32];
    45     JMCEVAL_DBGP("Parse number: ");
    46     scanf("%s",buff);
    47     return strtod(buff, 0);
    48 }
    49 
    50 void JMCEVAL_printReal(double x) {
    51     printf(JMCEVAL_realFormat, x); \
    52     printf("\n"); \
    53     fflush(stdout); \
    54 }
    55 
    56 char* JMCEVAL_parseString() {
    57     int d[1];
    58     char* str;
    59     size_t si,di;
    60     JMCEVAL_parseArrayDims(1);
    61     getchar();
    62     str = ModelicaAllocateString(d[0]);
    63     JMCEVAL_DBGP("Parse string: ");
    64     for (si = 0; si < d[0]; si++) str[si] = getchar();
    65     str[d[0]] = '\0';
    66     return str;
    67 }
    68 
    69 void JMCEVAL_printString(const char* str) {
    70     printf("%u\n%s\n", (unsigned)strlen(str), str);
    71     fflush(stdout);
    72 }
    73 
    74 #define JMCEVAL_parseInteger()  JMCEVAL_parseReal()
    75 #define JMCEVAL_parseBoolean()  JMCEVAL_parseInteger()
    76 #define JMCEVAL_parseEnum()     JMCEVAL_parseInteger()
    77 #define JMCEVAL_printInteger(X) JMCEVAL_printReal(X)
    78 #define JMCEVAL_printBoolean(X) JMCEVAL_printInteger(X)
    79 #define JMCEVAL_printEnum(X)    JMCEVAL_printInteger(X)
    80 #define JMCEVAL_parse(TYPE, X)  X = JMCEVAL_parse##TYPE()
    81 #define JMCEVAL_print(TYPE, X)  JMCEVAL_print##TYPE(X)
    82 
    83 /* Parse/print arrays */
    84 #define JMCEVAL_parseArray(TYPE,ARR) for (vi = 1; vi <= ARR->num_elems; vi++) { JMCEVAL_parse(TYPE, jmi_array_ref_1(ARR,vi)); }
    85 #define JMCEVAL_printArray(TYPE,ARR) for (vi = 1; vi <= ARR->num_elems; vi++) { JMCEVAL_print(TYPE, jmi_array_val_1(ARR,vi)); }
    86 
    87 /* Used by ModelicaUtilities */
    88 void jmi_global_log(int warning, const char* name, const char* fmt, const char* value)
    89 {
    90     printf("LOG\n");
    91     JMCEVAL_printInteger((double)warning);
    92     JMCEVAL_printString(name);
    93     JMCEVAL_printString(fmt);
    94     JMCEVAL_printString(value);
    95 }
    96 
    97 jmp_buf jmceval_try_location;
    98 
    99 #define JMCEVAL_try() (setjmp(jmceval_try_location) == 0)
    100 
    101 void jmi_throw()
    102 {
    103     longjmp(jmceval_try_location, 1);
    104 }
    105 
    106 jmi_dynamic_function_memory_t* dyn_fcn_mem = NULL;
    107 
    108 jmi_dynamic_function_memory_t* jmi_dynamic_function_memory() {
    109     if (dyn_fcn_mem == NULL) { dyn_fcn_mem = jmi_dynamic_function_pool_create(1024*1024); }
    110     return dyn_fcn_mem;
    111 }
    112 
    113 void* jmi_global_calloc(size_t n, size_t s)
    114 {
    115     return jmi_dynamic_function_pool_direct_alloc(dyn_fcn_mem, n*s, 1);
    116 }
    117 
    118 void JMCEVAL_setup() {
    119 #ifdef _WIN32
    120     /* Prevent win from translating \n to \r\n */
    121     _setmode(fileno(stdout), _O_BINARY);
    122 #endif
    123 }
    124 
    125 int JMCEVAL_cont(const char* word) {
    126     char l[10];
    127     char* s = fgets(l, 10, stdin);
    128     if (strlen(s) == 1) {
    129         s = fgets(l, 10, stdin); /* Extra call to fix stray newline */
    130     }
    131     if (s == NULL) {
    132         exit(2);
    133     }
    134     if (strlen(s) == strlen(word)) {
    135         return strncmp(l, word, strlen(word)) == 0;
    136     }
    137     return 0;
    138 }
    139 
    140 void JMCEVAL_check(const char* str) {
    141     printf("%s\n",str);
    142     fflush(stdout);
    143 }
    144 
    145 void JMCEVAL_failed() {
    146     JMCEVAL_check("ABORT");
    147 }
    14833
    14934/* Main */
     
    19580        JMCEVAL_failed();
    19681    }
    197     jmi_dynamic_function_pool_destroy(dyn_fcn_mem);
     82    _jmi_dynamic_function_pool_destroy();
    19883    JMCEVAL_check("END");
    19984    return 0;
  • branches/stable/Compiler/ModelicaCBackEnd/test/modelica/CCodeGenExternalCevalTests.mo

    r13575 r13771  
    1717
    1818package CCodeGenExternalCevalTests
     19
     20model ExtDynFcn1
     21        type E = enumeration(A,B);
     22    function f
     23        input Real a1;
     24        input Integer a2;
     25        input Boolean a3;
     26        input String a4;
     27        input E a5;
     28        output Real b1;
     29        output Integer b2;
     30        output Boolean b3;
     31        output String b4;
     32        output E b5;
     33        external;
     34    end f;
     35   
     36    Real x1;
     37    Integer x2;
     38    Boolean x3;
     39    String x4;
     40    E x5;
     41equation
     42    (x1,x2,x3,x4,x5) = f(1,2,true,"s",E.A);
     43
     44    annotation(__JModelica(UnitTesting(tests={
     45        FClassMethodTestCase(
     46            name="ExtDynFcn1",
     47            methodName="externalCTypes",
     48            description="Test that the different primitive types generates the correct C mapping",
     49            external_constant_evaluation_dynamic=true,
     50            methodResult="
     51f
     52void
     53d,i,i,s,i,*d,*i,*i,*s,*i,
     54")})));
     55end ExtDynFcn1;
     56
     57model ExtDynFcn2
     58type E = enumeration(A,B);
     59function f
     60    input Real[:] a1;
     61    input Integer[:] a2;
     62    input Boolean[:] a3;
     63    input String[:] a4;
     64    input E[:] a5;
     65    output Real[size(a1,1)] b1;
     66    output Integer[size(a2,1)] b2;
     67    output Boolean[size(a3,1)] b3;
     68    output String[size(a4,1)] b4;
     69    output E[size(a5,1)] b5;
     70    external;
     71end f;
     72    Real[1] x1;
     73    Integer[1] x2;
     74    Boolean[1] x3;
     75    String[1] x4;
     76    E[1] x5;
     77equation
     78    (x1,x2,x3,x4,x5) = f({1},{2},{true},{"s"},{E.A});
     79
     80    annotation(__JModelica(UnitTesting(tests={
     81        FClassMethodTestCase(
     82            name="ExtDynFcn2",
     83            methodName="externalCTypes",
     84            description="Test that the different primitive types (arrays of) generates the correct C mapping",
     85            external_constant_evaluation_dynamic=true,
     86            methodResult="
     87f
     88void
     89dv,i,iv,i,iv,i,sv,i,iv,i,*dv,i,*iv,i,*iv,i,*sv,i,*iv,i,
     90")})));
     91end ExtDynFcn2;
     92
     93model ExtDynFcn3
     94    type E = enumeration(A,B);
     95    record R
     96        Real a1;
     97        Integer a2;
     98        Boolean a3;
     99        String a4;
     100        E a5;
     101        R2 r2;
     102    end R;
     103    record R2
     104        Real x;
     105    end R2;
     106   
     107    function f
     108        input R a;
     109        output R b;
     110        external f(a,b);
     111    end f;
     112   
     113    R r = f(R(1,2,true,"s",E.A, R2(3)));
     114
     115    annotation(__JModelica(UnitTesting(tests={
     116        FClassMethodTestCase(
     117            name="ExtDynFcn3",
     118            methodName="externalCTypes",
     119            description="Test that records generates the correct C mapping",
     120            external_constant_evaluation_dynamic=true,
     121            methodResult="
     122f
     123void
     124R[d,i,i,s,i,R[d,],],*R[d,i,i,s,i,R[d,],],
     125")})));
     126end ExtDynFcn3;
     127
    19128
    20129model Scalar
     
    789898end ExtObj5;
    790899
     900model ExtDynObj1
     901    function use1
     902        input  Os.Obj1 o1;
     903        output Real x;
     904        external annotation(Library="extObjectsUse", Include="#include \"extObjectsUse.h\"",
     905            LibraryDirectory="modelica://Library2", IncludeDirectory="Include2");
     906    end use1;
     907
     908    Os.Obj1 o1 = Os.Obj1(3.13, 3, true, "A message");
     909    Real x = use1(o1);
     910
     911    annotation(__JModelica(UnitTesting(tests={
     912        FClassMethodTestCase(
     913            name="ExtDynObj1",
     914            methodName="externalCTypes",
     915            description="Verifies that external objects are not handled by the dynamic evaluator",
     916            methodResult="
     917")})));
     918end ExtDynObj1;
     919
     920
    791921model Dgelsx
    792922    function dgelsx
  • branches/stable/Compiler/ModelicaCompiler/module.options

    r12895 r13771  
    136136external objects during compilation.If less than 1, no processes will be kept
    137137alive, i.e. this feature is turned off."
     138
     139********************************************************************************
     140BOOLEAN external_constant_evaluation_dynamic compiler experimental false
     141
     142"If enabled, calls to external functions will be evaluated during compilation
     143using a pre-compiled program (instead of generating and compiling one), if
     144possible."
    138145
    139146********************************************************************************
     
    458465
    459466********************************************************************************
    460 
  • branches/stable/Compiler/ModelicaCompiler/runtime.options

    r11347 r13771  
    221221"Compares the analytic block jacobians with the finite difference block
    222222jacobians during block evaluation. An error is given if the relative error is
    223 to big."
     223too big."
    224224
    225225********************************************************************************
  • branches/stable/Compiler/ModelicaCompiler/src/jastadd/DebugCompiler.jrag

    r11966 r13771  
    130130                mc.setLogger(out);
    131131                ModelicaCompiler.TargetObject targ = (ModelicaCompiler.TargetObject) target.getSelectedItem();
    132                 mc.compileModel(new String[] { file.getAbsolutePath() }, name, targ, null, null);
     132                mc.compileModel(new String[] { file.getAbsolutePath() }, name, targ, null);
    133133            } catch (Exception ex) {
    134134                out.writeException(ex);
  • branches/stable/Compiler/ModelicaCompiler/src/jastadd/ModelicaCompiler.jrag

    r13396 r13771  
    348348            hooks.packFmu(this, fc, dir);
    349349        }
    350         fc.root().getUtilInterface().packFmu(fc);
     350        fc.root().getUtilInterface().packFmu(fc, dir.toPath());
    351351    }
    352352   
     
    358358            hooks.fmuPacked(this, fc, path);
    359359        }
    360         fc.root().getUtilInterface().fmuPacked(fc, path);
     360        fc.root().getUtilInterface().fmuPacked(fc, path.toPath());
    361361    }
    362362   
     
    811811             * Compile mo-file and generate code for all templates that are not null.
    812812             */
    813             String flatName = null;
    814             if (!Files.isDirectory(compileTo)) {
    815                 flatName = compileTo.getFileName().toString();
    816                 int i = flatName.lastIndexOf('.');
    817                 if (i > 0) {
    818                     flatName = flatName.substring(0, i);
    819                 }
    820             }
    821             FClass fc = compileModel(fileName, className, target, flatName, compileTo);
     813            FClass fc = compileModel(fileName, className, target, compileTo);
    822814
    823815            if (!target.getCodeGenFlag()) {
     
    832824             */
    833825            hookCheckAbort();
    834             doCompileCCode(target, fc, className, flatName);
     826            doCompileCCode(target, fc);
    835827
    836828            /*
     
    838830             */
    839831            ASTNode.beginStep("packUnit()");
    840             File unitPath = packUnit(className, target, fc);
     832            Path unitPath = packUnit(className, target, fc);
    841833            unit = log.logCompiledUnit(unitPath, warnings, fc.numberOfComponents());
    842834            ASTNode.endStep("packUnit()");
     
    12661258        /* Temporary fix to problems with long compilation times due to later evaluations */
    12671259        getExternalFunctionCache().tearDown();
    1268         options.setIntegerOption("external_constant_evaluation", 0);
     1260        options.external_constant_evaluation.setValue(0);
    12691261       
    12701262        hookModelTransformed(fc);
     
    13691361        ASTNode.beginStep("generateCode()");
    13701362        log.info("Generating code...");
     1363       
    13711364        String name = fc.nameUnderscore();
    1372        
    13731365        Templates templates = target.getTemplates(getOptions());
    1374    
    1375         templates.generateCFiles(this, fc, createCGenerator(fc), sourceDir, name);
    1376         templates.generateXMLFiles(this, fc, target.getXMLGenerator(fc), outDir, "modelDescription");
     1366       
     1367        generateAllFiles(fc, target, templates, name);
    13771368        hookCodeGenerated(fc, outDir);
    13781369       
     
    19601951     * @param target
    19611952     *            The target object for the compiler.
    1962      * @param flatName
    1963      *            Name of the unit/flat model supplied by the user, if any.
    19641953     *
    19651954     * @return A flat representation of the class specified by <code>cl</code>.
     
    19831972     * @deprecated Use {@link #compileModel(Path[], String, TargetObject, String, Path)} instead
    19841973     */
    1985     public FClass ModelicaCompiler.compileModel(String files[], String cl, TargetObject target, String flatName, String compileTo)
     1974    public FClass ModelicaCompiler.compileModel(String files[], String cl, TargetObject target, String compileTo)
    19861975          throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    1987         return compileModel(stringsToPaths(files), cl, target, flatName, compileTo == null ? null : Paths.get(compileTo));
     1976        return compileModel(stringsToPaths(files), cl, target, compileTo == null ? null : Paths.get(compileTo));
    19881977    }
    19891978   
     
    19991988     * @param target
    20001989     *            The target object for the compiler.
    2001      * @param flatName
    2002      *            Name of the unit/flat model supplied by the user, if any.
    20031990     *
    20041991     * @return A flat representation of the class specified by <code>cl</code>.
     
    20222009     * @deprecated Use {@link #compileModel(Path[], String, TargetObject, String, Path)} instead
    20232010     */
    2024      public FClass ModelicaCompiler.compileModel(Path files[], String cl, TargetObject target, String flatName, Path compileTo)
     2011     public FClass ModelicaCompiler.compileModel(Path files[], String cl, TargetObject target, Path compileTo)
    20252012          throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    20262013        boolean doTearDown = true;
    20272014        try {
    20282015            doTearDown = trySetUp();
    2029             return doCompileModel(files, cl, target, flatName, compileTo);
     2016            return doCompileModel(files, cl, target, compileTo);
    20302017        } finally {
    20312018            tryTearDown(doTearDown);
     
    20332020    }
    20342021   
    2035     public FClass ModelicaCompiler.doCompileModel(String name[], String cl, TargetObject target, String flatName, String compileTo)
    2036           throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    2037         return doCompileModel(stringsToPaths(name), cl, target, flatName, compileTo == null ? null : Paths.get(compileTo));
    2038     }
    2039    
    2040    
    2041     public FClass ModelicaCompiler.doCompileModel(Path name[], String cl, TargetObject target, String flatName, Path compileTo)
     2022   
     2023    public FClass ModelicaCompiler.doCompileModel(Path name[], String cl, TargetObject target, Path compileTo)
    20422024          throws ModelicaException, FileNotFoundException, IOException, beaver.Parser.Exception {
    20432025        if (target.equals(TargetObject.PARSE)) {
     
    20622044            // compute instance tree
    20632045            InstClassDecl icl = instantiateModel(name, cl, target);
     2046            UtilInterface util = icl.root().getUtilInterface();
     2047            if (compileTo != null) {
     2048                Path unitFile = makePackagingDirs(cl, compileTo, target);
     2049                util.setCompilationOutputPath(unitFile);
     2050            }
    20642051           
    2065             if (compileTo != null) {
    2066                 File unitFile = makePackagingDirs(cl, compileTo.toFile(), target);
    2067                 icl.root().getUtilInterface().setCompilationOutputPath(unitFile);
    2068             }
     2052            String flatName = computeFlatName(compileTo, util);
    20692053           
    20702054            // flattening
     
    22072191     * Packs an FMU (helper function for {@link #compileUnit()}).
    22082192     */
    2209     protected File ModelicaCompiler.packUnit(String className,
     2193    protected Path ModelicaCompiler.packUnit(String className,
    22102194            TargetObject target, FClass fClass) throws PackingFailedException {
    2211 
    2212         File unitFile = fClass.root().getUtilInterface().getCompilationOutputPath();
    2213 
     2195        Path unitFile = fClass.root().getUtilInterface().getCompilationOutputPath();
     2196       
    22142197        hookPackFmu(fClass, outDir);
     2198        hookCheckAbort();
     2199        packUnit(className, target, fClass, unitFile);
     2200        hookFmuPacked(fClass, unitFile.toAbsolutePath().toFile());
     2201       
     2202        return unitFile;
     2203    }
     2204   
     2205    private void ModelicaCompiler.packUnit(String className, TargetObject target, FClass fClass, Path unitFile) {
    22152206        try {
    2216             hookCheckAbort();
    22172207            copySourceFiles(fClass, sourceDir, outDir);
    2218 
    2219             OutputStream dest = new BufferedOutputStream(new FileOutputStream(unitFile));
    2220             ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
    2221             out.setMethod(ZipOutputStream.DEFLATED);
    2222 
    2223             zipDir(outDir, out);
    2224             out.close();
    2225         } catch (CompilationAbortedException e) {
    2226             throw e;
     2208            try (ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(unitFile)))) {
     2209                out.setMethod(ZipOutputStream.DEFLATED);
     2210                zipDir(outDir, out);
     2211            }
    22272212        } catch (Exception e) {
    22282213            throw new PackingFailedException(String.format("Could not write to '%s'.", unitFile), e);
    22292214        }
    2230 
    2231         hookFmuPacked(fClass, unitFile.getAbsoluteFile());
    2232         return unitFile;
    22332215    }
    22342216
     
    22482230    }
    22492231
    2250     private void ModelicaCompiler.doCompileCCode(TargetObject target,  FClass fc, String className, String flatName) {
     2232    private void ModelicaCompiler.doCompileCCode(TargetObject target,  FClass fc) {
    22512233        if (target.getMakeFileFlag() != null) {
    22522234                ASTNode.beginStep("compileCCode()");
    2253                 String cFileName = (flatName != null) ? flatName : FClass.convertClassNameToUnderscore(className);
     2235                String cFileName = fc.nameUnderscore();
    22542236                CCompilerDelegator ccompiler = getCCompiler();
    22552237                CCompilerArguments ccArgs = new CCompilerArguments(cFileName, fc.myOptions(), target, fc.externalLibraries(), fc.externalLibraryDirectories(),
     
    22642246    /**
    22652247     * Calculates the destination directory for a packaged unit. If the specified destination is a file its directory
    2266      * is chosen as destination. If the destination does not exist, it is created (using {@link File#mkdirs()}).
     2248     * is chosen as destination. If the destination does not exist, it is created (using {@link Filed#createDirectories()}).
    22672249     *
    22682250     * @param className
     
    22732255     *          A {@link TargetObject} containing information about the target.
    22742256     * @return
    2275      *          the path to the destination directory of the packaged unit.
     2257     *          the path to the destination file of the packaged unit.
    22762258     */
    2277     private File ModelicaCompiler.makePackagingDirs(String className, File destination, TargetObject target) {
    2278         File dest = new File(destination.getAbsolutePath());
    2279         if (dest.isDirectory()) {
     2259    private Path ModelicaCompiler.makePackagingDirs(String className, Path destination, TargetObject target)
     2260            throws IOException {
     2261        Path dest = destination.toAbsolutePath();
     2262        if (Files.isDirectory(dest)) {
    22802263            String mangledName = FClass.convertClassNameToUnderscore(className);
    2281             dest = new File(dest, mangledName + "." + target.getUnitSuffix());
     2264            dest = dest.resolve(mangledName + "." + target.getUnitSuffix());
    22822265        } else {
    2283             File destDir = dest.getParentFile();
    2284             if (destDir != null && !destDir.isDirectory()) {
    2285                 dest.getParentFile().mkdirs();
     2266            Path destDir = dest.getParent();
     2267            if (destDir != null && !Files.isDirectory(destDir)) {
     2268                Files.createDirectories(dest.getParent());
    22862269            }
    22872270        }
    22882271        return dest;
     2272    }
     2273   
     2274    private void ModelicaCompiler.generateAllFiles(FClass fc, TargetObject target, Templates templates, String name)
     2275            throws FileNotFoundException {
     2276        templates.generateCFiles(this, fc, createCGenerator(fc), sourceDir, name);
     2277        templates.generateXMLFiles(this, fc, target.getXMLGenerator(fc), outDir, "modelDescription");
     2278    }
     2279   
     2280    private String ModelicaCompiler.computeFlatName(Path compileTo, UtilInterface util) {
     2281        String flatName = null;
     2282        if (compileTo != null && !Files.isDirectory(compileTo)) {
     2283            flatName = compileTo.getFileName().toString();
     2284            int i = flatName.lastIndexOf('.');
     2285            if (i > 0) {
     2286                flatName = flatName.substring(0, i);
     2287            }
     2288        }
     2289        return flatName;
    22892290    }
    22902291
  • branches/stable/Compiler/ModelicaCompiler/src/jastadd/UtilInterface.jrag

    r13396 r13771  
    4141             * Called after code has been compiled.
    4242             */
    43             public void packFmu(FClass fc) {}
     43            public void packFmu(FClass fc, Path outDir) {}
    4444           
    4545            /**
    4646             * Called after code has been compiled.
    4747             */
    48             public void fmuPacked(FClass fc, File path) {}
     48            public void fmuPacked(FClass fc, Path outDir) {}
    4949           
    5050            /**
     
    7272        private ExternalFunctionCache efc;
    7373        private GUIDManager guidManager;
    74         private File compilationOutputPath;
     74        private Path compilationOutputPath;
    7575       
    76         protected UtilInterface(ModelicaCompiler mc, OptionRegistry options, IErrorHandler eh, ExternalFunctionCache efc, File compilationOutputPath) {
     76        protected UtilInterface(ModelicaCompiler mc, OptionRegistry options, IErrorHandler eh, ExternalFunctionCache efc, Path compilationOutputPath) {
    7777            this.mc = mc;
    7878            this.options = options;
     
    110110        }
    111111       
    112         public File getCompilationOutputPath() {
     112        public Path getCompilationOutputPath() {
    113113            return compilationOutputPath;
    114114        }
    115115       
    116         public void setCompilationOutputPath(File compilationOutputPath) {
     116        public void setCompilationOutputPath(Path compilationOutputPath) {
    117117            this.compilationOutputPath = compilationOutputPath;
    118118        }
     
    146146    }
    147147   
    148     public void UtilInterface.packFmu(FClass fc) {
     148    public void UtilInterface.packFmu(FClass fc, Path outDir) {
    149149        for (Interfacer interfacer : interfacers) {
    150             interfacer.packFmu(fc);
     150            interfacer.packFmu(fc, outDir);
    151151        }
    152152    }
    153153   
    154     public void UtilInterface.fmuPacked(FClass fc, File path) {
     154    public void UtilInterface.fmuPacked(FClass fc, Path outDir) {
    155155        for (Interfacer interfacer : interfacers) {
    156             interfacer.fmuPacked(fc, path);
     156            interfacer.fmuPacked(fc, outDir);
    157157        }
    158158    }
  • branches/stable/Compiler/ModelicaCompiler/src/java/org/jmodelica/util/ccompiler/CCompilerDelegator.java

    r13274 r13771  
    351351        };
    352352    }
     353
     354    public abstract Set<String> expandCompilerSpecificLibraryPaths(ModelicaLogger log, AbstractOptionRegistry options,
     355            Set<String> extLibDirs, String platform);
    353356}
    354357
  • branches/stable/Compiler/ModelicaCompiler/src/java/org/jmodelica/util/ccompiler/GccCompilerDelegator.java

    r13300 r13771  
    2626import java.util.Set;
    2727
     28import org.jmodelica.common.options.AbstractOptionRegistry;
    2829import org.jmodelica.util.EnvironmentUtils;
    2930import org.jmodelica.util.exceptions.CcodeCompilationException;
     
    106107            vars.put("AR", new File(mingw_bin, "ar").getPath());
    107108        }
     109    }
     110   
     111    @Override
     112    public Set<String> expandCompilerSpecificLibraryPaths(ModelicaLogger log, AbstractOptionRegistry options, Set<String> extLibDirs, String platform) {
     113        Set<String> expandedLibDirs = expandLibraries(extLibDirs, platform, "gcc" + compilerVersionNumber());
     114        return expandedLibDirs;
    108115    }
    109116   
  • branches/stable/Compiler/ModelicaCompilerCasADi/src/jastadd/FExpToCasADi.jrag

    r12770 r13771  
    3131            target.setDefaultOptions(options);
    3232            try {
    33                 return compileModel(name, cl, target, null, null);
     33                return compileModel(name, cl, target, null);
    3434            } finally {
    3535                options.copyAllOptions(tempOptions);
  • branches/stable/Compiler/ModelicaFlatTree/src/jastadd/ConstantEvaluation/ConstantEvaluation.jrag

    r13687 r13771  
    50795079        }
    50805080       
    5081         public AlgorithmEvaluator createAlgorithmEvaluator(AbstractOptionRegistry options, Map<CommonVariableDecl, CValue> values) {
     5081        public AlgorithmEvaluator createAlgorithmEvaluator(OptionRegistry options, Map<CommonVariableDecl, CValue> values) {
    50825082            return new AlgorithmEvaluator(externalEvaluationEnabled, options, values);
    50835083        }
    50845084       
    5085         public AlgorithmEvaluator createEmptyAlgorithmEvaluator(AbstractOptionRegistry options) {
     5085        public AlgorithmEvaluator createEmptyAlgorithmEvaluator(OptionRegistry options) {
    50865086            return new AlgorithmEvaluator(true, options, Collections.<CommonVariableDecl, CValue>emptyMap());
    50875087        }
     
    51495149       
    51505150        @Override
    5151         public AlgorithmEvaluator createAlgorithmEvaluator(AbstractOptionRegistry options, Map<CommonVariableDecl, CValue> values) {
     5151        public AlgorithmEvaluator createAlgorithmEvaluator(OptionRegistry options, Map<CommonVariableDecl, CValue> values) {
    51525152            return new PartialAlgorithmEvaluator(externalEvaluationEnabled(), options, values, this);
    51535153        }
     
    51835183       
    51845184        @Override
    5185         public AlgorithmEvaluator createAlgorithmEvaluator(AbstractOptionRegistry options, Map<CommonVariableDecl, CValue> values) {
     5185        public AlgorithmEvaluator createAlgorithmEvaluator(OptionRegistry options, Map<CommonVariableDecl, CValue> values) {
    51865186            if (this.values == null) {
    51875187                this.values = values;
     
    52775277    public class AlgorithmEvaluator extends VariableEvaluator {
    52785278       
    5279         protected Map<CommonVariableDecl, CValue> values;
    5280         private AbstractOptionRegistry options;
    5281        
    5282         public AlgorithmEvaluator(boolean evaluateExternalEnabled, AbstractOptionRegistry options, Map<CommonVariableDecl, CValue> values) {
     5279        protected final Map<CommonVariableDecl, CValue> values;
     5280        private final OptionRegistry options;
     5281       
     5282        public AlgorithmEvaluator(boolean evaluateExternalEnabled, OptionRegistry options, Map<CommonVariableDecl, CValue> values) {
    52835283            super(evaluateExternalEnabled);
    52845284            this.values  = values;
     
    52875287       
    52885288        public int externalEvaluation() {
    5289             return externalEvaluationEnabled() ? options.getIntegerOption("external_constant_evaluation") : 0;
     5289            return externalEvaluationEnabled() ? options.external_constant_evaluation.getValue() : 0;
    52905290        }
    52915291       
     
    53515351        protected ArrayList<IfEvaluation> ifStack;
    53525352       
    5353         public PartialAlgorithmEvaluator(boolean evaluateExternalEnabled, AbstractOptionRegistry options,
     5353        public PartialAlgorithmEvaluator(boolean evaluateExternalEnabled, OptionRegistry options,
    53545354                Map<CommonVariableDecl, CValue> values, PartialVariableEvaluator variableEvaluator) {
    53555355            super(evaluateExternalEnabled, options, values);
     
    53685368       
    53695369        @Override
    5370         public AlgorithmEvaluator createAlgorithmEvaluator(AbstractOptionRegistry options, Map<CommonVariableDecl, CValue> values) {
     5370        public AlgorithmEvaluator createAlgorithmEvaluator(OptionRegistry options, Map<CommonVariableDecl, CValue> values) {
    53715371            return variableEvaluator.createAlgorithmEvaluator(options, values);
    53725372        }
  • branches/stable/Compiler/ModelicaFlatTree/src/jastadd/ConstantEvaluation/ExternalConstantEvaluation.jrag

    r13687 r13771  
    2626import java.util.TimerTask;
    2727
     28import org.jmodelica.common.evaluation.ExternalFunctionCompiler;
    2829import org.jmodelica.common.evaluation.ExternalFunction;
    2930import org.jmodelica.common.evaluation.ExternalProcessCache;
    3031import org.jmodelica.common.evaluation.ExternalProcessCacheImpl;
    3132import org.jmodelica.common.evaluation.ExternalProcessMultiCache;
     33import org.jmodelica.common.evaluation.FailedExternalFunction;
    3234import org.jmodelica.common.evaluation.ProcessCommunicator;
    3335
     
    4951    class ModelicaCompiler {}
    5052   
    51     ModelicaCompiler   implements ExternalProcessMultiCache.Compiler<ExternalArgument, FExternalStmt>;
     53    ModelicaCompiler   implements ExternalFunctionCompiler<ExternalArgument, FExternalStmt>;
    5254    FExternalStmt      implements ExternalProcessMultiCache.External<ExternalArgument>;
    5355    ExternalArgument   extends    ExternalProcessMultiCache.Variable<CValue,FType>;
     
    8991     * Check if this external function should be cached as a live process.
    9092     */
    91     syn boolean FExternalStmt.shouldCacheProcess() {
    92         return myOptions().getIntegerOption("external_constant_evaluation_max_proc") > 0;
    93     }
     93    syn int FExternalStmt.processLimit() =
     94            myOptions().external_constant_evaluation_max_proc.getValue();
     95   
     96    syn boolean FExternalStmt.dynamicEvaluatorEnabled() =
     97            myOptions().external_constant_evaluation_dynamic.getValue()
     98            && !externalObjectsToSerialize().iterator().hasNext();
    9499   
    95100    /**
     
    169174        ExternalFunctionCache efc = root().getUtilInterface().getExternalFunctionCache();
    170175        if (efc == null) {
    171             return new ExternalProcessCacheImpl<>(root().getUtilInterface().getModelicaCompiler())
    172                 .failedEval(this, "external function cache unavailable", false);
     176            return FailedExternalFunction.<ExternalArgument, CValue, FType, FExternalStmt>failedEval(
     177                    root().getUtilInterface().getModelicaCompiler(),
     178                    this, "external function cache unavailable", false);
    173179        }
    174180        return efc.getExternalProcessCache(getLibTopPackagePath()).getExternalFunction(this);
     
    205211       
    206212        if (error != null) {
    207             throw new ConstantEvaluationException(null, ExternalProcessCacheImpl.failedEvalMsg(getName(), error));
     213            throw new ConstantEvaluationException(null, FailedExternalFunction.failedEvalMsg(getName(), error));
    208214        }
    209215       
  • branches/stable/Compiler/ModelicaFrontEnd/src/jastadd/instance/InstLookupClasses.jrag

    r13575 r13771  
    261261        HashMap<String,SrcLibNode> map = new HashMap<String,SrcLibNode>(prog.getNumSrcLibNode() * 4 / 3 + 1);
    262262        for (SrcLibNode ln : prog.getSrcLibNodes()) {
    263             if (!map.containsKey(ln.name())) {
    264                 map.put(ln.name(), ln);
     263            String name = ln.name().toLowerCase();
     264            if (!map.containsKey(name)) {
     265                map.put(name, ln);
    265266            }
    266267        }
     
    269270
    270271    syn lazy InstLookupResult<InstClassDecl> InstProgramRoot.lookupLibrary(String name) {
    271         SrcLibNode ln = libraryMap().get(name);
     272        SrcLibNode ln = libraryMap().get(name.toLowerCase());
    272273        if (ln != null) {
    273274            InstClassDecl icd = createInstClassDecl(ln);
  • branches/stable/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/common/GUIDManager.java

    r13396 r13771  
    22
    33import java.io.BufferedReader;
    4 import java.io.BufferedWriter;
     4import java.io.ByteArrayInputStream;
    55import java.io.ByteArrayOutputStream;
    66import java.io.File;
    7 import java.io.FileNotFoundException;
    8 import java.io.FileReader;
    9 import java.io.FileWriter;
    107import java.io.IOException;
    11 import java.io.OutputStreamWriter;
    12 import java.io.Reader;
    13 import java.io.StringReader;
    14 import java.io.Writer;
     8import java.io.InputStream;
     9import java.io.InputStreamReader;
     10import java.io.OutputStream;
     11import java.io.PrintWriter;
    1512import java.math.BigInteger;
    1613import java.nio.charset.Charset;
     14import java.nio.file.Files;
     15import java.nio.file.Path;
    1716import java.security.MessageDigest;
    1817import java.security.NoSuchAlgorithmException;
     
    6564
    6665    public void setSourceFile(File source) {
     66        this.source = new FileOpenable(source.toPath());
     67    }
     68
     69    public void setSourceFile(Path source) {
    6770        this.source = new FileOpenable(source);
    6871    }
     
    7376
    7477    public void addDependentFile(File dependentFile) {
     78        dependentFiles.add(new FileOpenable(dependentFile.toPath()));
     79    }
     80
     81    public void addDependentFile(Path dependentFile) {
    7582        dependentFiles.add(new FileOpenable(dependentFile));
    7683    }
    7784
    78     public void addDependentString(String input, StringBuilder output) {
     85    public void addDependentString(String input, ByteArrayOutputStream output) {
    7986        dependentFiles.add(new StringOpenable(input, output));
    8087    }
     
    8592            final MessageDigest md5 = MessageDigest.getInstance("MD5");
    8693
    87             try (final BufferedReader reader = new BufferedReader(source.openInput())) {
     94            try (final BufferedReader reader = new BufferedReader(new InputStreamReader(source.openInput()))) {
    8895                String line = reader.readLine();
    8996                while (line != null) {
     
    118125        for (final Openable openable : dependentFiles) {
    119126            try {
    120                 ByteArrayOutputStream os = new ByteArrayOutputStream();
    121                 try (final Writer tmp = new OutputStreamWriter(os)) {
    122                     processFiles(openable.openInput(), tmp);
    123                 }
    124 
    125                 try (BufferedWriter writer = new BufferedWriter(openable.openOutput())) {
    126                     writer.append(os.toString());
     127                try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
     128                    processFiles(openable.openInput(), os);
     129                    try (PrintWriter writer = new PrintWriter(openable.openOutput())) {
     130                        writer.append(os.toString());
     131                    }
    127132                }
    128133            } catch (IOException e) {
     
    132137    }
    133138
    134     private void processFiles(Reader source, Writer destination) throws IOException {
    135         try (final BufferedReader reader = new BufferedReader(source);
    136                 final BufferedWriter writer = new BufferedWriter(destination)) {
     139    private void processFiles(InputStream source, OutputStream destination) throws IOException {
     140        try (final BufferedReader reader = new BufferedReader(new InputStreamReader(source));
     141             final PrintWriter writer = new PrintWriter(destination)) {
    137142
    138143            String line =  reader.readLine();
     
    200205
    201206    private static interface Openable {
    202         public Reader openInput();
    203         public Writer openOutput();
     207        public InputStream openInput();
     208        public OutputStream openOutput();
    204209    }
    205210   
    206     private static class FileOpenable implements Openable{
    207         private File file;
    208        
    209         public FileOpenable(File file) {
    210             this.file = file;
    211         }
    212        
    213         @Override
    214         public Reader openInput() {
     211    private static class FileOpenable implements Openable {
     212        private Path path;
     213       
     214        public FileOpenable(Path file) {
     215            this.path = file;
     216        }
     217       
     218        @Override
     219        public InputStream openInput() {
    215220            try {
    216                 return new FileReader(file);
    217             } catch (FileNotFoundException e) {
    218                 throw new RuntimeException(e);
    219             }
    220         }
    221        
    222         @Override
    223         public Writer openOutput() {
    224             try {
    225                 return new FileWriter(file);
     221                return Files.newInputStream(path);
    226222            } catch (IOException e) {
    227223                throw new RuntimeException(e);
     
    230226       
    231227        @Override
     228        public OutputStream openOutput() {
     229            try {
     230                return Files.newOutputStream(path);
     231            } catch (IOException e) {
     232                throw new RuntimeException(e);
     233            }
     234        }
     235       
     236        @Override
    232237        public String toString() {
    233             return file.toString();
     238            return path.toString();
    234239        }
    235240    }
     
    238243       
    239244        private String input;
    240         private StringBuilder output;
    241        
    242         public StringOpenable(String input, StringBuilder output) {
     245        private ByteArrayOutputStream output;
     246       
     247        public StringOpenable(String input, ByteArrayOutputStream output) {
    243248            this.input = input;
    244249            this.output = output;
     
    246251       
    247252        @Override
    248         public Reader openInput() {
    249             return new StringReader(input);
    250         }
    251        
    252         @Override
    253         public Writer openOutput() {
    254             return new Writer() {
    255                
    256                 @Override
    257                 public void write(char[] cbuf, int off, int len) throws IOException {
    258                     output.append(cbuf, off, len);
    259                 }
    260                
    261                 @Override
    262                 public void flush() throws IOException {
    263                     // Do nothing
    264                 }
    265                
    266                 @Override
    267                 public void close() throws IOException {
    268                     // Do nothing
    269                 }
    270             };
     253        public InputStream openInput() {
     254            return new ByteArrayInputStream(input.getBytes());
     255        }
     256       
     257        @Override
     258        public OutputStream openOutput() {
     259            return output;
    271260        }
    272261    }
  • branches/stable/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/common/evaluation/ExternalProcessCache.java

    r10910 r13771  
    2424
    2525    protected abstract void tearDown();
    26 
    27     public abstract ExternalFunction<K, V> failedEval(External<?> ext, String msg, boolean log);
    2826   
    2927
  • branches/stable/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/common/evaluation/ExternalProcessCacheImpl.java

    r12940 r13771  
    33import java.io.File;
    44import java.io.FileNotFoundException;
    5 import java.io.IOException;
    65import java.io.PrintStream;
    76import java.util.ArrayList;
    87import java.util.HashMap;
     8import java.util.HashSet;
    99import java.util.LinkedHashSet;
    1010import java.util.Map;
    11 
    12 import org.jmodelica.common.evaluation.ExternalProcessMultiCache.Compiler;
     11import java.util.Set;
     12
    1313import org.jmodelica.common.evaluation.ExternalProcessMultiCache.External;
    1414import org.jmodelica.common.evaluation.ExternalProcessMultiCache.Type;
     
    1616import org.jmodelica.common.evaluation.ExternalProcessMultiCache.Variable;
    1717import org.jmodelica.util.EnvironmentUtils;
     18import org.jmodelica.util.SystemUtil;
    1819import org.jmodelica.util.ccompiler.CCompilerDelegator;
    1920import org.jmodelica.util.exceptions.CcodeCompilationException;
    2021import org.jmodelica.util.logging.ModelicaLogger;
    21 import org.jmodelica.util.values.ConstantEvaluationException;
    2222
    2323public class ExternalProcessCacheImpl<K extends Variable<V, T>, V extends Value, T extends Type<V>, E extends External<K>> extends ExternalProcessCache<K, V, T, E> {
     
    2626     * Maps external functions names to compiled executables.
    2727     */
    28     private Map<String, ExternalFunction<K, V>> cachedExternals = new HashMap<String, ExternalFunction<K, V>>();
     28    private final Map<String, ExternalFunction<K, V>> cachedExternals = new HashMap<String, ExternalFunction<K, V>>();
    2929
    3030    /**
    3131     * Keeps track of all living processes, least recently used first.
    3232     */
    33     private LinkedHashSet<ExternalFunction<K, V>> livingCachedExternals = new LinkedHashSet<ExternalFunction<K, V>>();
    34 
    35     private Compiler<K, E> mc;
    36 
    37     public ExternalProcessCacheImpl(Compiler<K, E> mc) {
     33    private final LinkedHashSet<ExternalFunction<K, V>> livingCachedExternals = new LinkedHashSet<ExternalFunction<K, V>>();
     34
     35    private final ExternalFunctionCompiler<K, E> mc;
     36
     37    public ExternalProcessCacheImpl(ExternalFunctionCompiler<K, E> mc) {
    3838        this.mc = mc;
    3939    }
     
    4242        return mc.log();
    4343    }
    44 
     44   
     45    private String getPlatform() {
     46        return CCompilerDelegator.reduceBits(EnvironmentUtils.getJavaPlatform(),
     47                mc.getCCompiler().getTargetPlatforms());
     48    }
     49   
     50    private String getSharedLibrary(External<K> ext) {
     51        String sharedLib = "";
     52        String extLibrary = "";
     53       
     54        if (ext.library() != null && ext.library().length == 1) {
     55            extLibrary = ext.library()[0];
     56        } else {
     57            return sharedLib;
     58        }
     59       
     60        HashSet<String> externalLibraryDirectories = new HashSet<String>();
     61        externalLibraryDirectories.add(ext.libraryDirectory());
     62        Set<String> expandedLibDirs = mc.getCCompiler().expandCompilerSpecificLibraryPaths(mc.log(), ext.myOptions(),
     63                                                   externalLibraryDirectories, getPlatform());
     64       
     65        for (String dir : expandedLibDirs) {
     66            File testlib1 = new File(dir, extLibrary + SystemUtil.sharedLibraryExtension());
     67            File testlib2 = new File(dir, "lib" + extLibrary + SystemUtil.sharedLibraryExtension());
     68           
     69            if (testlib1.exists() && !testlib1.isDirectory()) {
     70                sharedLib = testlib1.toString();
     71                break;
     72            }
     73            if (testlib2.exists() && !testlib2.isDirectory()) {
     74                sharedLib = testlib2.toString();
     75                break;
     76            }
     77        }
     78       
     79        return sharedLib;
     80    }
     81   
     82    private static ArrayList<String> builtinExternalFunctions = new ArrayList<String>() {{
     83        add("ModelicaStrings_substring");
     84        add("ModelicaStrings_length");
     85        add("ModelicaStrings_skipWhiteSpace");
     86        add("ModelicaStrings_compare");
     87    }};
     88   
     89    private static ArrayList<String> supportedSignatures = new ArrayList<String>() {{
     90        add("d+d,d,");
     91        add("d+i,");
     92        add("d+i,d,d,");
     93        add("s+s,i,i,");
     94        add("i+s,");
     95        add("i+s,i,");
     96        add("i+s,s,i,");
     97        add("i+i,i,");
     98        add("void+i,d,d,*R[d,d,d,d,d,d,d,d,d,d,d,],");
     99        add("void+d,d,*d,");
     100    }};
     101   
     102    public boolean canUseEvaluator(E ext, ArrayList<String> arguments) {
     103        if (!ext.dynamicEvaluatorEnabled()) {
     104            return false;
     105        }
     106       
     107        String sharedLibrary = getSharedLibrary(ext);
     108        String functionName  = ext.getName();
     109        String outputArguments = ext.functionReturnArgSerialized();
     110        String inputArguments  = ext.functionArgsSerialized();
     111       
     112        if (sharedLibrary.equals("")) {
     113            if (builtinExternalFunctions.contains(functionName)) {
     114                sharedLibrary = "NoSharedLibrary";
     115            } else {
     116                mc.log().debug("Could not find a shared library containing '" + functionName + "'. Disabling use of the evaluator...");
     117                return false;
     118            }
     119        }
     120       
     121        if (!supportedSignatures.contains(outputArguments+"+"+inputArguments)) {
     122            mc.log().debug("The function signature, outputs '" + outputArguments + "', inputs '" + inputArguments + "', is not supported. Disabling use of the evaluator...");
     123            return false;
     124        }
     125       
     126        arguments.add(sharedLibrary);
     127        arguments.add(functionName);
     128        arguments.add(outputArguments);
     129        arguments.add(inputArguments);
     130
     131        return true;
     132    }
     133   
    45134    @Override
    46135    public ExternalFunction<K, V> getExternalFunction(E ext) {
     
    48137        if (ef == null) {
    49138            if (mc == null) {
    50                 return failedEval(ext, "Missing ModelicaCompiler", false);
     139                return FailedExternalFunction.<K,V,T,E>failedEval(mc, ext, "Missing ModelicaCompiler", false);
    51140            }
    52141            try {
    53142                long time = System.currentTimeMillis();
    54                 String executable = mc.compileExternal(ext);
    55                 if (ext.shouldCacheProcess()) {
    56                     ef = new MappedExternalFunction(ext, executable);
     143                String executable = null;
     144                ArrayList<String> arguments = new ArrayList<String>();
     145                String debugMsg = "";
     146                ExternalFunctionExecutable extFunctionExecutable;
     147                if (canUseEvaluator(ext, arguments)) {
     148                    String jmHome = System.getenv("JMODELICA_HOME");
     149                    String bits = getPlatform().contains("64") && SystemUtil.isWindows() ? "64" : "";
     150                    executable = jmHome + File.separator + "bin" + bits + File.separator + "jmi_evaluator" + SystemUtil.executableExtension();
     151                   
     152                    arguments.add(0, executable); /* Needs to be first */
     153                   
     154                    extFunctionExecutable = new ExternalFunctionExecutableDynamic(arguments);
     155                   
     156                    debugMsg = "Succesfully connected external function '" + ext.getName() + "' to the evaluator '"
     157                            + executable + "' with outputs: '" + ext.functionReturnArgSerialized() + "' and inputs: '" + ext.functionArgsSerialized() + "'";
    57158                } else {
    58                     ef = new CompiledExternalFunction(ext, executable);
     159                    executable = mc.compileExternal(ext);
     160                   
     161                    extFunctionExecutable = new ExternalFunctionExecutableGenerated(executable);
     162                   
     163                    debugMsg = "Succesfully compiled external function '" + ext.getName() + "' to executable '"
     164                            + executable + "' code for evaluation";
     165                }
     166               
     167                if (ext.processLimit() > 0) {
     168                    ef = new MappedExternalFunction<K,V,T,E>(mc, ext, extFunctionExecutable, livingCachedExternals);
     169                } else {
     170                    ef = new ExternalFunctionImpl<K,V,T,E>(mc, ext, extFunctionExecutable);
    59171                }
    60172                time = System.currentTimeMillis() - time;
    61                 mc.log().debug("Succesfully compiled external function '" + ext.getName() + "' to executable '"
    62                         + executable + "' code for evaluation, time: " + time + "ms");
     173                mc.log().debug(debugMsg +", time: " + time + "ms");
    63174            } catch (FileNotFoundException e) {
    64                 ef = failedEval(ext, "c-code generation failed '" + e.getMessage() + "'", true);
     175                ef = FailedExternalFunction.<K,V,T,E>failedEval(mc, ext, "c-code generation failed '" + e.getMessage() + "'", true);
    65176                mc.log().debug(ef.getMessage());
    66177            } catch (CcodeCompilationException e) {
    67                 ef = failedEval(ext, "c-code compilation failed '" + e.getMessage() + "'", true);
     178                ef = FailedExternalFunction.<K,V,T,E>failedEval(mc, ext, "c-code compilation failed '" + e.getMessage() + "'", true);
    68179                mc.log().debug(ef.getMessage());
    69180                e.printStackTrace(new PrintStream(mc.log().debugStream()));
     
    95206    }
    96207
    97     @Override
    98     public ExternalFunction<K, V> failedEval(External<?> ext, String msg, boolean log) {
    99         return new FailedExternalFunction(failedEvalMsg(ext.getName(), msg), log);
    100     }
    101 
    102     public static String failedEvalMsg(String name, String msg) {
    103         return "Failed to evaluate external function '" + name + "', " + msg;
    104     }
    105 
    106     private class FailedExternalFunction implements ExternalFunction<K, V> {
    107         private String msg;
    108         private boolean log;
    109 
    110         public FailedExternalFunction(String msg, boolean log) {
    111             this.msg = msg;
    112             this.log = log;
    113         }
    114 
    115         @Override
    116         public String getMessage() {
    117             return msg;
    118         }
    119 
    120         @Override
    121         public int evaluate(External<K> ext, Map<K, V> values, int timeout) throws IOException {
    122             if (log) {
    123                 log().debug("Evaluating failed external function: " + ext.getName());
    124             }
    125             throw new ConstantEvaluationException(null, getMessage());
    126         }
    127 
    128         @Override
    129         public void destroyProcess() {
    130             // Do nothing
    131         }
    132 
    133         @Override
    134         public void remove() {
    135             // Do nothing
    136         }
    137     }
    138 
    139     /**
    140      * Represents an external function that has been compiled successfully.
    141      */
    142     private class CompiledExternalFunction implements ExternalFunction<K, V> {
    143         protected String executable;
    144         protected ProcessBuilder processBuilder;
    145         private String msg;
    146 
    147         public CompiledExternalFunction(External<K> ext, String executable) {
    148             this.executable = executable;
    149             this.processBuilder = createProcessBuilder(ext);
    150             this.msg = "Succesfully compiled external function '" + ext.getName() + "'";
    151         }
    152 
    153         @Override
    154         public String getMessage() {
    155             return msg;
    156         }
    157 
    158         protected ProcessCommunicator<V, T> createProcessCommunicator() throws IOException {
    159             return new ProcessCommunicator<V, T>(mc, processBuilder.start());
    160         }
    161 
    162         @Override
    163         public int evaluate(External<K> ext, Map<K, V> values, int timeout) throws IOException {
    164             log().debug("Evaluating compiled external function: " + ext.getName());
    165             ProcessCommunicator<V, T> com = null;
    166             try {
    167                 com = createProcessCommunicator();
    168                 setup(ext, values, timeout, com);
    169                 evaluate(ext, values, timeout, com);
    170                 return teardown(timeout, com);
    171             } finally {
    172                 if (com != null) {
    173                     com.destroy();
    174                 }
    175             }
    176         }
    177 
    178         public void setup(External<K> ext, Map<K, V> values, int timeout, ProcessCommunicator<V, T> com)
    179                 throws IOException {
    180             com.startTimer(timeout);
    181             com.accept("START");
    182             for (K eo : ext.externalObjectsToSerialize()) {
    183                 com.put(values.containsKey(eo) ? values.get(eo) : eo.ceval(), eo.type());
    184             }
    185             com.accept("READY");
    186             com.cancelTimer();
    187         }
    188 
    189         public void evaluate(External<K> ext, Map<K, V> values, int timeout, ProcessCommunicator<V, T> com)
    190                 throws IOException {
    191             com.startTimer(timeout);
    192             com.check("EVAL");
    193 
    194             for (K arg : ext.functionArgsToSerialize()) {
    195                 com.put(values.containsKey(arg) ? values.get(arg) : arg.ceval(), arg.type());
    196             }
    197             com.accept("CALC");
    198             com.accept("DONE");
    199             for (K cvd : ext.varsToDeserialize())
    200                 values.put(cvd, com.get(cvd.type()));
    201             com.accept("READY");
    202             com.cancelTimer();
    203         }
    204 
    205         public int teardown(int timeout, ProcessCommunicator<V, T> com) throws IOException {
    206             com.startTimer(timeout);
    207             com.check("EXIT");
    208             com.accept("END");
    209             int result = com.end();
    210             com.cancelTimer();
    211             // log().debug("SUCCESS TEARDOWN");
    212             return result;
    213         }
    214 
    215         @Override
    216         public void destroyProcess() {
    217             // Do nothing
    218         }
    219 
    220         @Override
    221         public void remove() {
    222             new File(executable).delete();
    223         }
    224 
    225         private ProcessBuilder createProcessBuilder(External<K> ext) {
    226             ProcessBuilder pb = new ProcessBuilder(executable);
    227             Map<String, String> env = pb.environment();
    228             if (env.keySet().contains("Path")) {
    229                 env.put("PATH", env.get("Path"));
    230                 env.remove("Path");
    231             }
    232             pb.redirectErrorStream(true);
    233             if (ext.libraryDirectory() != null) {
    234                 // Update environment in case of shared library
    235                 String platform = CCompilerDelegator.reduceBits(EnvironmentUtils.getJavaPlatform(),
    236                         mc.getCCompiler().getTargetPlatforms());
    237                 File f = new File(ext.libraryDirectory(), platform);
    238                 String libLoc = f.isDirectory() ? f.getPath() : ext.libraryDirectory();
    239                 appendPath(env, libLoc, platform);
    240             }
    241             return pb;
    242         }
    243 
    244         /**
    245          * Append a library location <code>libLoc</code> to the path variable in
    246          * environment <code>env</code>.
    247          */
    248         private void appendPath(Map<String, String> env, String libLoc, String platform) {
    249             String sep = platform.startsWith("win") ? ";" : ":";
    250             String var = platform.startsWith("win") ? "PATH" : "LD_LIBRARY_PATH";
    251             String res = env.get(var);
    252             if (res == null)
    253                 res = libLoc;
    254             else
    255                 res = res + sep + libLoc;
    256             env.put(var, res);
    257         }
    258     }
    259 
    260     /**
    261      * A CompiledExternalFunction which can cache several processes with external
    262      * object constructor only called once.
    263      */
    264     private class MappedExternalFunction extends CompiledExternalFunction {
    265 
    266         private Map<String, ExternalFunction<K, V>> lives = new HashMap<>();
    267 
    268         private final int externalConstantEvaluationMaxProc;
    269 
    270         public MappedExternalFunction(External<K> ext, String executable) {
    271             super(ext, executable);
    272             externalConstantEvaluationMaxProc = ext.myOptions()
    273                     .getIntegerOption("external_constant_evaluation_max_proc");
    274         }
    275 
    276         /**
    277          * Find a LiveExternalFunction based on the external object of this external
    278          * function. Start a new process if not up already. Failure to set up (call
    279          * constructor) will cache and return a Failed external function.
    280          */
    281         private ExternalFunction<K, V> getActual(External<K> ext, Map<K, V> values, int timeout) {
    282             Variable<V, T> cvd = ext.cachedExternalObject();
    283             String name = cvd == null ? "" : cvd.ceval().getMarkedExternalObject();
    284             ExternalFunction<K, V> ef = lives.get(name);
    285             if (ef == null) {
    286                 LiveExternalFunction lef = new LiveExternalFunction();
    287                 try {
    288                     lef.ready(ext, values, timeout);
    289                     ef = lef;
    290                 } catch (IOException e) {
    291                     lef.destroyProcess();
    292                     ef = failedEval(ext, " error starting process '" + e.getMessage() + "'", true);
    293                 } catch (ConstantEvaluationException e) {
    294                     lef.destroyProcess();
    295                     ef = failedEval(ext, " error starting process '" + e.getMessage() + "'", true);
    296                 }
    297                 lives.put(name, ef);
    298             }
    299             return ef;
    300         }
    301 
    302         @Override
    303         public int evaluate(External<K> ext, Map<K, V> values, int timeout) throws IOException {
    304             return getActual(ext, values, timeout).evaluate(ext, values, timeout);
    305         }
    306 
    307         @Override
    308         public void destroyProcess() {
    309             for (ExternalFunction<K, V> ef : lives.values()) {
    310                 ef.destroyProcess();
    311             }
    312             lives.clear();
    313         }
    314 
    315         /**
    316          * Represents a (possible) living external function process.
    317          */
    318         private class LiveExternalFunction implements ExternalFunction<K, V> {
    319 
    320             protected ProcessCommunicator<V, T> com;
    321 
    322             public LiveExternalFunction() {
    323                 super();
    324             }
    325 
    326             @Override
    327             public String getMessage() {
    328                 return MappedExternalFunction.this.getMessage();
    329             }
    330 
    331             @Override
    332             public int evaluate(External<K> ext, Map<K, V> values, int timeout) throws IOException {
    333                 log().debug("Evaluating live external function: " + ext.getName());
    334                 try {
    335                     ready(ext, values, timeout);
    336                     long time = System.currentTimeMillis();
    337                     MappedExternalFunction.this.evaluate(ext, values, timeout, com);
    338                     time = System.currentTimeMillis() - time;
    339                     log().debug("Finished evaluating live external function, time: " + time + "ms");
    340                 } catch (ProcessCommunicator.AbortConstantEvaluationException e) {
    341 
    342                 } catch (ConstantEvaluationException e) {
    343                     destroyProcess();
    344                     throw e;
    345                 } catch (IOException e) {
    346                     destroyProcess();
    347                     throw e;
    348                 }
    349                 return 0;
    350             }
    351 
    352             /**
    353              * Make sure process is ready for evaluation call.
    354              */
    355             protected void ready(External<K> ext, Map<K, V> values, int timeout) throws IOException {
    356                 if (com == null) {
    357                     long time1 = System.currentTimeMillis();
    358                     // Start process if not live.
    359                     com = createProcessCommunicator();
    360                     long time2 = System.currentTimeMillis();
    361                     // Send external object constructor inputs
    362                     MappedExternalFunction.this.setup(ext, values, timeout, com);
    363                     long time3 = System.currentTimeMillis();
    364                     log().debug("Setup live external function: " + ext.getName()
    365                               + ", createProcessCommunicator() time: " + (time2 - time1)
    366                               + "ms, setup time: " + (time3 - time2) + "ms");
    367                 }
    368 
    369                 // Mark as most recently used
    370                 livingCachedExternals.remove(this);
    371                 livingCachedExternals.add(this);
    372 
    373                 // If we are over the allowed number of cached processes
    374                 // we kill the least recently used.
    375                 if (livingCachedExternals.size() > externalConstantEvaluationMaxProc) {
    376                     livingCachedExternals.iterator().next().destroyProcess();
    377                 }
    378             }
    379 
    380             @Override
    381             public void destroyProcess() {
    382                 if (com != null) {
    383                     livingCachedExternals.remove(this);
    384                     com.destroy();
    385                     com = null;
    386                 }
    387             }
    388 
    389             @Override
    390             public void remove() {
    391                 // Removing this executable is handled by surrounding MappedExternalFunction
    392                 throw new UnsupportedOperationException();
    393             }
    394         }
    395     }
    396208}
  • branches/stable/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/common/evaluation/ExternalProcessMultiCache.java

    r13252 r13771  
    22
    33import java.io.BufferedWriter;
    4 import java.io.FileNotFoundException;
    54import java.io.IOException;
    65import java.util.LinkedHashMap;
    76import java.util.Map;
    87
    9 import org.jmodelica.common.LogContainer;
    108import org.jmodelica.common.options.AbstractOptionRegistry;
    11 import org.jmodelica.util.ccompiler.CCompilerDelegator;
    12 import org.jmodelica.util.exceptions.CcodeCompilationException;
    139
    1410public class ExternalProcessMultiCache<K extends ExternalProcessMultiCache.Variable<V, T>, V extends ExternalProcessMultiCache.Value, T extends ExternalProcessMultiCache.Type<V>, E extends ExternalProcessMultiCache.External<K>> {
    15 
    16     public interface Compiler<K, E extends External<K>> extends LogContainer {
    17         public String compileExternal(E ext) throws FileNotFoundException, CcodeCompilationException;
    18 
    19         public CCompilerDelegator getCCompiler();
    20     }
    2111
    2212    public interface External<K> {
    2313        public String getName();
    2414
    25         public boolean shouldCacheProcess();
     15        public int processLimit();
     16
     17        public boolean dynamicEvaluatorEnabled();
    2618
    2719        public AbstractOptionRegistry myOptions();
     
    3527        public Iterable<K> functionArgsToSerialize();
    3628
     29        public String functionArgsSerialized();
     30
     31        public String functionReturnArgSerialized();
     32
    3733        public Iterable<K> varsToDeserialize();
     34
     35        public String[] library();
    3836    }
    3937
     
    5654    private Map<String, ExternalProcessCache<K, V, T, E>> map = new LinkedHashMap<>();
    5755
    58     private Compiler<K, E> mc;
     56    private ExternalFunctionCompiler<K, E> mc;
    5957
    60     public ExternalProcessMultiCache(Compiler<K, E> mc) {
     58    public ExternalProcessMultiCache(ExternalFunctionCompiler<K, E> mc) {
    6159        this.mc = mc;
    6260    }
  • branches/stable/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/util/SystemUtil.java

    r11394 r13771  
    7272        return isLinux() ? "" : ".exe";
    7373    }
     74   
     75    public static String sharedLibraryExtension() {
     76        if (isWindows()) {
     77            return ".dll";
     78        } else if (isLinux()) {
     79            return ".so";
     80        } else {
     81            return ".dylib";
     82        }
     83    }
    7484
    7585    /**
  • branches/stable/Compiler/ModelicaFrontEnd/src/java/org/jmodelica/util/files/FileUtil.java

    r11394 r13771  
    33import java.io.File;
    44import java.io.IOException;
     5import java.nio.file.DirectoryStream;
    56import java.nio.file.Files;
     7import java.nio.file.Path;
    68import java.nio.file.Paths;
    79import java.nio.file.StandardCopyOption;
     
    155157        return names;
    156158    }
     159   
     160    /**
     161     * @return A collection of all files in {@code dir} matching the {@code glob}
     162     *         pattern
     163     */
     164    public static Collection<Path> getMatching(Path dir, String glob) throws IOException {
     165        Collection<Path> res = new ArrayList<>();
     166        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, glob)) {
     167            for (Path path : stream) {
     168                res.add(path);
     169            }
     170        }
     171        return res;
     172    }
    157173
    158174    /**
     
    234250     *             if there was any error copying the files.
    235251     */
    236     public static void copyRecursive(Collection<File> files, File destination, boolean replace) throws IOException {
     252    public static void copyRecursive(Iterable<File> files, File destination, boolean replace) throws IOException {
    237253        for (File file : files) {
    238254            copyRecursive(file, destination, replace);
     255        }
     256    }
     257   
     258    /**
     259     * Copies file to a directory. Contents of directories is copied recursively.
     260     *
     261     * @param sourceFile
     262     *            The file to copy.
     263     * @param destDir
     264     *            The destination directory.
     265     * @throws IOException
     266     *             if there was any error copying the files.
     267     */
     268    public static void copyRecursive(Path sourceFile, Path destDir) throws IOException {
     269        Path outFile = destDir.resolve(sourceFile.getFileName());
     270        if (Files.isDirectory(sourceFile)) {
     271            if (!Files.exists(outFile)) {
     272                Files.createDirectory(outFile);
     273            }
     274            try (DirectoryStream<Path> stream = Files.newDirectoryStream(sourceFile)) {
     275                copyRecursive(stream, outFile);
     276            }
     277        } else {
     278            Files.copy(sourceFile, outFile, StandardCopyOption.REPLACE_EXISTING);
     279        }
     280    }
     281   
     282    /**
     283     * Copies several files to a directory.
     284     *
     285     * @param sourceFiles
     286     *            The files to copy.
     287     * @param destDir
     288     *            The destination directory.
     289     * @throws IOException
     290     *             if there was any error copying the files.
     291     */
     292    public static void copyRecursive(Iterable<Path> sourceFiles, Path destDir) throws IOException {
     293        for (Path file : sourceFiles) {
     294            copyRecursive(file, destDir);
    239295        }
    240296    }
  • branches/stable/Compiler/ModelicaFrontEnd/test/junit/org/jmodelica/test/common/ExternalProcessCacheTest.java

    r13274 r13771  
    99import java.io.IOException;
    1010
     11import org.jmodelica.common.evaluation.ExternalFunctionCompiler;
     12import org.jmodelica.common.evaluation.ExternalFunction;
    1113import org.jmodelica.common.evaluation.ExternalProcessCache;
    12 import org.jmodelica.common.evaluation.ExternalFunction;
    1314import org.jmodelica.common.evaluation.ExternalProcessMultiCache;
     15import org.jmodelica.common.evaluation.ExternalProcessMultiCache.External;
     16import org.jmodelica.common.evaluation.ExternalProcessMultiCache.Type;
     17import org.jmodelica.common.evaluation.ExternalProcessMultiCache.Value;
    1418import org.jmodelica.common.evaluation.ExternalProcessMultiCache.Variable;
     19import org.jmodelica.common.evaluation.ProcessCommunicator;
    1520import org.jmodelica.common.options.AbstractOptionRegistry;
    16 import org.jmodelica.common.evaluation.ExternalProcessMultiCache.Value;
    17 import org.jmodelica.common.evaluation.ExternalProcessMultiCache.Type;
    18 import org.jmodelica.common.evaluation.ExternalProcessMultiCache.External;
    19 import org.jmodelica.common.evaluation.ProcessCommunicator;
    2021import org.jmodelica.util.ccompiler.CCompilerDelegator;
    2122import org.jmodelica.util.exceptions.CcodeCompilationException;
     
    7475    class ExternalProcessCacheMock<K extends Variable<V,T>, V extends Value, T extends Type<V>, E extends External<K>> extends ExternalProcessMultiCache<K,V,T,E> {
    7576
    76         public ExternalProcessCacheMock(Compiler<K,E> mc) {
     77        public ExternalProcessCacheMock(ExternalFunctionCompiler<K,E> mc) {
    7778            super(mc);
    7879        }
     
    108109        }
    109110
    110         @Override
    111         public ExternalFunction<K,V> failedEval(External<?> ext, String msg, boolean log) {
    112             // TODO Auto-generated method stub
    113             return null;
    114         }
    115        
    116     }
    117 
    118     class CompilerMock implements ExternalProcessMultiCache.Compiler<VariableMock, ExternalMock> {
     111    }
     112
     113    class CompilerMock implements ExternalFunctionCompiler<VariableMock, ExternalMock> {
    119114
    120115        @Override
     
    189184
    190185        @Override
    191         public boolean shouldCacheProcess() {
    192             // TODO Auto-generated method stub
     186        public int processLimit() {
     187            // TODO Auto-generated method stub
     188            return 0;
     189        }
     190
     191        @Override
     192        public boolean dynamicEvaluatorEnabled() {
    193193            return false;
    194194        }
     
    223223            return null;
    224224        }
     225       
     226        @Override
     227        public String functionArgsSerialized() {
     228            // TODO Auto-generated method stub
     229            return null;
     230        }
     231       
     232        @Override
     233        public String functionReturnArgSerialized() {
     234            // TODO Auto-generated method stub
     235            return null;
     236        }
    225237
    226238        @Override
     
    229241            return null;
    230242        }
     243       
     244        @Override
     245        public String[] library() {
     246            // TODO Auto-generated method stub
     247            return null;
     248        }
    231249
    232250    }
  • branches/stable/Compiler/ModelicaFrontEnd/test/junit/org/jmodelica/test/common/GUIDManagerTest.java

    r13396 r13771  
    44import static org.junit.Assert.assertFalse;
    55import static org.junit.Assert.assertTrue;
     6
     7import java.io.ByteArrayOutputStream;
    68
    79import org.jmodelica.common.GUIDManager;
     
    2022    private void test(String source, String[] dependent, String[] expected) {
    2123        guidManager.setSourceString(source);
    22         StringBuilder[] output = new StringBuilder[dependent.length];
     24        ByteArrayOutputStream[] output = new ByteArrayOutputStream[dependent.length];
    2325        for (int i = 0; i < dependent.length; i++) {
    24             output[i] = new StringBuilder();
     26            output[i] = new ByteArrayOutputStream();
    2527            guidManager.addDependentString(dependent[i], output[i]);
    2628        }
     
    4749        String expected = "guid=277efff8e9f33c422aa6e3fecb8b592";
    4850        guidManager.setSourceString(input);
    49         StringBuilder output = new StringBuilder();
     51        ByteArrayOutputStream output = new ByteArrayOutputStream();
    5052        guidManager.addDependentString(input, output);
    5153        guidManager.processDependentFiles();
  • branches/stable/Compiler/ModelicaMiddleEnd/src/jastadd/structural/Symbolic.jrag

    r13661 r13771  
    217217    private static Boolean FEquation.nominalAllowsDivision(FExp factor, FVariable var, double tol) {
    218218        if (factor.variability().constantVariability()) {
    219             FExp nominal = factor.dynamicFExp(var.nominal());
    220             if (nominal.variability().constantVariability() &&
    221                     Math.abs(factor.ceval().realValue()) *
    222                     nominal.ceval().realValue() < tol) {
    223                 return false;
     219            FExp varNominalExp = factor.dynamicFExp(var.nominal());
     220            if (varNominalExp.variability().constantVariability()) {
     221                double factorNominal = Math.abs(factor.ceval().realValue());
     222                double varNominal    = varNominalExp.ceval().realValue();
     223                double totalNominal  = factorNominal * varNominal;
     224                if (totalNominal < tol) {
     225                    return false;
     226                }
    224227            }
    225228        }
  • branches/stable/Compiler/ModelicaMiddleEnd/test/modelica/EquationSolvingTests.mo

    r13661 r13771  
    3434        FClassMethodTestCase(
    3535            name="ParametricNominal1",
    36             description="",
     36            description="Test that parametric nominal that cannot be evaluated does not lead to exception during equation solving. Instead we handle it as if there was no nominal set.",
    3737            methodName="printDAEBLT",
    3838            methodResult="
  • branches/stable/Compiler/TestFramework/src/jastadd/CodeGenTestCase.jrag

    r11966 r13771  
    4444       
    4545        GUIDManager guidManager = fc.guidManager();
    46         StringBuilder actual = new StringBuilder();
     46        ByteArrayOutputStream actual = new ByteArrayOutputStream();
    4747        guidManager.setSourceString(test);
    4848        guidManager.addDependentString(test, actual);
  • branches/stable/Makefile.am

    r13661 r13771  
    4545bindistdir=JModelica.org-$(VERSION)-bin
    4646
    47 casadi:
    48 if COMPILE_WITH_IPOPT
    49     cd $(abs_builddir)/ThirdParty/CasADi; \
    50     make -f Makefile  "SWIGCHECK_BUILD_DIR=$(SWIGCHECK_BUILD_DIR)" "CASADI_BUILD_DIR=$(CASADI_BUILD_DIR)" "IPOPT_HOME=$(IPOPT_HOME)" "CASADI_PYTHON_INST_DIR=${CASADI_PYTHON_INST_DIR}" "CASADI_INST_DIR=${CASADI_INST_DIR}" "CASADI_PLUGIN_INST_DIR=${CASADI_PLUGIN_INST_DIR}" "CMAKE_CASADI_ARGS=${CMAKE_CASADI_ARGS}" "CMAKE_CASADI_COMPILER_ARGS=${CMAKE_CASADI_COMPILER_ARGS}" "CMAKE_CASADI_CXX_FLAG=${CMAKE_CASADI_CXX_FLAG}" "CMAKE_PYTHON_LIB=${CMAKE_PYTHON_LIB}"
    51 endif
    52 if COMPILE_WITH_IPOPT64
    53     export PATH=$(PYTHON64_HOME):$(PYTHON64_HOME)/Scripts:$(PYTHON64_HOME)/Lib:"${PATH}"; \
    54     export PYTHONHOME=$(PYTHON64_HOME); \
    55     cd $(abs_builddir)/ThirdParty/CasADi; \
    56     make -f Makefile  "SWIGCHECK_BUILD_DIR=$(SWIGCHECK_BUILD_DIR64)" "CASADI_BUILD_DIR=$(CASADI_BUILD_DIR64)" "IPOPT_HOME=$(IPOPT64_HOME)" "CASADI_PYTHON_INST_DIR=${CASADI_PYTHON_INST_DIR64}" "CASADI_INST_DIR=${CASADI_INST_DIR64}" "CASADI_PLUGIN_INST_DIR=${CASADI_PLUGIN_INST_DIR64}" "CMAKE_CASADI_ARGS=${CMAKE_CASADI_ARGS64}" "CMAKE_CASADI_COMPILER_ARGS=${CMAKE_CASADI_COMPILER_ARGS64}" "CMAKE_CASADI_CXX_FLAG=${CMAKE_CASADI_CXX_FLAG64}" "CMAKE_PYTHON_LIB=${CMAKE_PYTHON64_LIB}" "CMAKE_PYTHON_INCLUDE=${CMAKE_PYTHON64_INCLUDE}"
    57     export PYTHONHOME=$(ORIG_PYTHON_HOME); \
    58     export PATH="$(ORIG_PATH)";
    59 endif
    60 
    61 install_casadi: casadi
    62 if COMPILE_WITH_IPOPT
    63     cd $(abs_builddir)/ThirdParty/CasADi; \
    64     make -f Makefile install "SWIGCHECK_BUILD_DIR=$(SWIGCHECK_BUILD_DIR)" "CASADI_BUILD_DIR=$(CASADI_BUILD_DIR)" "IPOPT_HOME=$(IPOPT_HOME)"
    65     mkdir -p $(DESTDIR)$(prefix)/Python/
    66     cp -r $(CASADI_PYTHON_INST_DIR)/casadi $(DESTDIR)$(prefix)/Python/
    67     ## temp fix
    68     cp $(CASADI_BUILD_DIR)/swig/casadi_core.py $(DESTDIR)$(prefix)/Python/casadi
    69 endif
    70 if COMPILE_WITH_IPOPT64 
    71     export PATH=$(PYTHON64_HOME):$(PYTHON64_HOME)/Scripts:$(PYTHON64_HOME)/Lib:"${PATH}"; \
    72     export PYTHONHOME=$(PYTHON64_HOME); 
    73     cd $(abs_builddir)/ThirdParty/CasADi; \
    74     make -f Makefile install "SWIGCHECK_BUILD_DIR=$(SWIGCHECK_BUILD_DIR)" "CASADI_BUILD_DIR=$(CASADI_BUILD_DIR64)" "IPOPT_HOME=$(IPOPT64_HOME)"
    75     mkdir -p $(DESTDIR)$(prefix)/Python/
    76     cp -r $(CASADI_PYTHON_INST_DIR64)/casadi $(DESTDIR)$(prefix)/Python_64/
    77     ## temp fix
    78     cp $(CASADI_BUILD_DIR64)/swig/casadi_core.py $(DESTDIR)$(prefix)/Python_64/casadi
    79     export PYTHONHOME=$(ORIG_PYTHON_HOME); \
    80     export PATH="$(ORIG_PATH)";
    81 endif
    82 ## Install for CasADiInterface, Variables and targets.
    83 ## MC_interface installs the system with Python.
    84 ## If C++ compilation/tests are wanted there is the target MC_interface_cplusplus
    85 
    86 MC_INTERFACE=$(abs_top_srcdir)/ModelicaCasADiInterface
    87 
    88 CASADI_HOME=$(abs_top_srcdir)/ThirdParty/CasADi/CasADi
    89 MC_SRC=$(JAVA_CASADI_BASE_DIR)/ModelicaCompilerCasADi
    90 OC_SRC=$(JAVA_CASADI_BASE_DIR)/OptimicaCompilerCasADi
    91 MC_SRC_SWIG=$(abs_top_srcdir)/Compiler/ModelicaCompilerCasADi/src/swig
    92 
    93 MC_CASADI_BUILD=$(abs_builddir)/ModelicaCompilerCasADi
    94 OC_CASADI_BUILD=$(abs_builddir)/OptimicaCompilerCasADi
    95 
    96 # The modelica casadi interface is built into a build folder
    97 MC_BUILD=$(abs_builddir)/ModelicaCasADiInterfaceBuild
    98 MC_BUILD64=$(abs_builddir)/ModelicaCasADiInterfaceBuild64
    99 # Jars from the modified modelica and optimica compilers are put into the JModelica folder
    100 MC_COMPILERS_DIR=$(MC_BUILD)/JModelica.org
    101 MC_LIB=$(DESTDIR)$(prefix)/lib/casadi_interface
    102 MC_LIB64=$(DESTDIR)$(prefix)/lib/casadi_interface64
    103 
    104 CASADI_BUILD_DIR=$(abs_builddir)/casadi_build
    105 CASADI_BUILD_DIR64=$(abs_builddir)/casadi_build64
    106 SWIGCHECK_BUILD_DIR=$(abs_builddir)/swig_check
    107 SWIGCHECK_BUILD_DIR64=$(abs_builddir)/swig_check64
    108 CASADI_PYTHON_INST_DIR=$(abs_builddir)/casadi_install
    109 CASADI_INST_DIR=$(prefix)/ThirdParty/CasADi
    110 CASADI_PLUGIN_INST_DIR=$(CASADI_INST_DIR)/lib
    111 CASADI_PYTHON_INST_DIR64=$(abs_builddir)/casadi_install64
    112 CASADI_INST_DIR64=$(prefix)/ThirdParty/CasADi64
    113 CASADI_PLUGIN_INST_DIR64=$(CASADI_INST_DIR64)/lib
    114 CMAKE_CASADI_CXX_FLAG=-m32
    115 CMAKE_CASADI_COMPILER_ARGS=-m32 -mincoming-stack-boundary=2
    116 CMAKE_CASADI_CXX_FLAG64=-m64
    117 CMAKE_CASADI_COMPILER_ARGS64=-m64 -fpermissive
    118 
    119 casadi_interface: install_casadi_interface
    120 build_casadi_interface: casadi modelicacasadi_wrapper
    121 install_casadi_interface: install_casadi $(MC_LIB) $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer/__init__.py $(DESTDIR)$(prefix)/Python/modelicacasadi_wrapper/__init__.py $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer/modelica_casadi_transfer_wrapper.py
    122     if [ "$(INSTALL_EXTRA_CASADI)" ]; then exec "$(INSTALL_EXTRA_CASADI)" "$(abs_top_srcdir)" "$(DESTDIR)$(prefix)"; fi
    123 
    124 ifcasadi: casadi
    125 if COMPILE_WITH_IPOPT
    126     mkdir -p $(MC_BUILD)/ifcasadi; \
    127     cd $(MC_BUILD)/ifcasadi; \
    128     case $(build) in \
    129     *-cygwin*|*-mingw*) \
    130     cmake $(MC_SRC_SWIG) -G "MSYS Makefiles" -DCMAKE_CXX_COMPILER_ARG1="-m32" -DCMAKE_CXX_FLAGS="-m32" \
    131         -DIFCASADI_OUTDIR="$(MC_CASADI_BUILD)" -DCASADI_HOME="$(CASADI_HOME)" -DCASADI_BUILD_DIR="$(CASADI_BUILD_DIR)";; \
    132     *) \
    133     cmake $(MC_SRC_SWIG) \
    134         -DIFCASADI_OUTDIR="$(MC_CASADI_BUILD)" -DCASADI_HOME="$(CASADI_HOME)" -DCASADI_BUILD_DIR="$(CASADI_BUILD_DIR)";; \
    135     esac
    136     cd $(MC_BUILD)/ifcasadi;  make
    137 endif
    138 if COMPILE_WITH_IPOPT64
    139     export PATH=$(PYTHON64_HOME):$(PYTHON64_HOME)/Scripts:$(PYTHON64_HOME)/Lib:"${PATH}";
    140     export PYTHONHOME=$(PYTHON64_HOME);
    141     mkdir -p $(MC_BUILD64)/ifcasadi; \
    142     cd $(MC_BUILD64)/ifcasadi; \
    143     cmake $(MC_SRC_SWIG) -G "MSYS Makefiles" -DCMAKE_CXX_COMPILER_ARG1="-m64" -DCMAKE_CXX_FLAGS="-m64" \
    144         -DIFCASADI_OUTDIR="$(MC_CASADI_BUILD)" -DCASADI_HOME="$(CASADI_HOME)" -DCASADI_BUILD_DIR="$(CASADI_BUILD_DIR64)"; \
    145     cd $(MC_BUILD64)/ifcasadi;  make
    146     export PYTHONHOME=$(ORIG_PYTHON_HOME); \
    147     export PATH="$(ORIG_PATH)";
    148 endif
    149 
    150 $(MC_LIB): $(MC_CASADI_BUILD)/bin/ModelicaCompiler.jar $(OC_CASADI_BUILD)/bin/OptimicaCompiler.jar $(MC_CASADI_BUILD)/bin/util.jar ifcasadi
    151 if COMPILE_WITH_IPOPT
    152     rm -rf $(MC_LIB)
    153     mkdir -p $(MC_LIB)
    154     cp $(MC_CASADI_BUILD)/bin/ModelicaCompiler.jar $(MC_LIB)
    155     cp $(OC_CASADI_BUILD)/bin/OptimicaCompiler.jar $(MC_LIB)
    156     cp $(MC_CASADI_BUILD)/bin/util.jar $(MC_LIB)
    157     case $(build) in \
    158     *-cygwin*) \
    159     cp $(MC_BUILD)/ifcasadi/ifcasadi.dll $(MC_LIB) ;; \
    160     *-mingw*) \
    161     cp $(MC_BUILD)/ifcasadi/ifcasadi.dll $(MC_LIB) ;; \
    162     *) \
    163     cp $(MC_BUILD)/ifcasadi/libifcasadi.so $(MC_LIB) ;; \
    164     esac
    165 endif
    166 if COMPILE_WITH_IPOPT64
    167     rm -rf $(MC_LIB64)
    168     mkdir -p $(MC_LIB64)
    169     cp $(MC_CASADI_BUILD)/bin/ModelicaCompiler.jar $(MC_LIB64)
    170     cp $(OC_CASADI_BUILD)/bin/OptimicaCompiler.jar $(MC_LIB64)
    171     cp $(MC_CASADI_BUILD)/bin/util.jar $(MC_LIB64)
    172     cp $(MC_BUILD64)/ifcasadi/ifcasadi.dll $(MC_LIB64)
    173 endif
    174 
    175 mc_modelica: ifcasadi
    176     cd $(MC_CASADI_BUILD); $(ANT_OPTS) $(ANT) -f "$(JAVA_MC_CASADI_ANT_FILE)" "-Dcompiler=$(COMPILER_DIR)" "-Dtarget=$(MC_CASADI_BUILD)"
    177 
    178 mc_optimica: ifcasadi
    179     mkdir -p $(OC_CASADI_BUILD)/src/generated/optimica/java
    180     cp -pr $(MC_CASADI_BUILD)/src/generated/modelica/java/ifcasadi $(OC_CASADI_BUILD)/src/generated/optimica/java
    181     cd $(OC_CASADI_BUILD); $(ANT_OPTS) $(ANT) -f "$(JAVA_OC_CASADI_ANT_FILE)" "-Dcompiler=$(COMPILER_DIR)" "-Dtarget=$(OC_CASADI_BUILD)"
    182 
    183 $(MC_CASADI_BUILD)/bin/ModelicaCompiler.jar: mc_modelica
    184 $(MC_CASADI_BUILD)/bin/util.jar:             mc_modelica
    185 $(MC_CASADI_BUILD)/bin/separateProcess.jar:  mc_modelica
    186 
    187 $(OC_CASADI_BUILD)/bin/OptimicaCompiler.jar: mc_optimica
    188 $(OC_CASADI_BUILD)/bin/util.jar:             mc_optimica
    189 $(OC_CASADI_BUILD)/bin/separateProcess.jar:  mc_optimica
    190 
    191 $(MC_BUILD)/modelicacasadi_wrapper/swig/modelicacasadi_wrapper.py: modelicacasadi_wrapper
    192 
    193 
    194 modelicacasadi_wrapper: $(MC_CASADI_BUILD)/bin/ModelicaCompiler.jar $(OC_CASADI_BUILD)/bin/OptimicaCompiler.jar $(MC_CASADI_BUILD)/bin/util.jar ifcasadi # $(MC_LIB)
    195 if COMPILE_WITH_IPOPT
    196     mkdir -p $(MC_BUILD)/modelicacasadi_wrapper; \
    197     cd $(MC_BUILD)/modelicacasadi_wrapper; \
    198     case $(build) in \
    199     *-cygwin*|*-mingw*) \
    200     cmake $(MC_INTERFACE) -G "MSYS Makefiles" -DCMAKE_CXX_COMPILER_ARG1="-m32" -DCMAKE_CXX_FLAGS="-m32" \
    201         -DMC_BUILD="$(MC_BUILD)" -DIPOPT_HOME="$(IPOPT_HOME)" -DCASADI_BUILD_DIR="$(CASADI_BUILD_DIR)" \
    202         -DIFCASADI_JAR_BASE="$(JAVA_CASADI_BUILD_DIR)" -DCASADI_HOME="$(CASADI_HOME)" \
    203         "$(CMAKE_PYTHON_LIB)" "$(CMAKE_PYTHON_INCLUDE)" ;; \
    204     *) \
    205     cmake $(MC_INTERFACE) \
    206         -DMC_BUILD="$(MC_BUILD)" -DIPOPT_HOME="$(IPOPT_HOME)" -DCASADI_BUILD_DIR="$(CASADI_BUILD_DIR)" \
    207         -DIFCASADI_JAR_BASE="$(JAVA_CASADI_BUILD_DIR)" -DCASADI_HOME="$(CASADI_HOME)" \
    208         "$(CMAKE_PYTHON_LIB)" "$(CMAKE_PYTHON_INCLUDE)" ;; \
    209     esac
    210     cd $(MC_BUILD)/modelicacasadi_wrapper;  make modelicacasadi_wrapper
    211 endif
    212 if COMPILE_WITH_IPOPT64
    213     export PATH=$(PYTHON64_HOME):$(PYTHON64_HOME)/Scripts:$(PYTHON64_HOME)/Lib:"${PATH}"; \
    214     export PYTHONHOME=$(PYTHON64_HOME); \
    215     mkdir -p $(MC_BUILD64)/modelicacasadi_wrapper; \
    216     cd $(MC_BUILD64)/modelicacasadi_wrapper; \
    217     cmake $(MC_INTERFACE) -G "MSYS Makefiles" -DCMAKE_CXX_COMPILER_ARG1="-m64" -DCMAKE_CXX_FLAGS="-m64" \
    218         -DMC_BUILD="$(MC_BUILD64)" -DIPOPT_HOME="$(IPOPT64_HOME)" -DCASADI_BUILD_DIR="$(CASADI_BUILD_DIR64)" \
    219         -DIFCASADI_JAR_BASE="$(JAVA_CASADI_BUILD_DIR)" -DCASADI_HOME="$(CASADI_HOME)" \
    220         "$(CMAKE_PYTHON64_LIB)" "$(CMAKE_PYTHON64_INCLUDE)"; \
    221     cd $(MC_BUILD64)/modelicacasadi_wrapper;  make modelicacasadi_wrapper
    222     export PYTHONHOME=$(ORIG_PYTHON_HOME);
    223     export PATH="$(ORIG_PATH)";
    224 endif
    225 
    226  $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer/__init__.py: install_modelicacasadi_transfer
    227  $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer/modelica_casadi_transfer_wrapper.py: install_modelicacasadi_transfer
    228  
    229  $(DESTDIR)$(prefix)/Python/modelicacasadi_wrapper/__init__.py: install_modelicacasadi_wrapper
    230  
    231  install_modelicacasadi_wrapper: $(MC_BUILD)/modelicacasadi_wrapper/swig/modelicacasadi_wrapper.py
    232 if COMPILE_WITH_IPOPT
    233     mkdir -p $(DESTDIR)$(prefix)/Python/modelicacasadi_wrapper
    234     cp $(MC_BUILD)/modelicacasadi_wrapper/swig/*modelicacasadi_wrapper* $(DESTDIR)$(prefix)/Python/modelicacasadi_wrapper
    235     rm -f $(DESTDIR)$(prefix)/Python/modelicacasadi_wrapper/__init__.py
    236     touch $(DESTDIR)$(prefix)/Python/modelicacasadi_wrapper/__init__.py
    237     echo "from modelicacasadi_wrapper import *" >> $(DESTDIR)$(prefix)/Python/modelicacasadi_wrapper/__init__.py
    238 endif
    239 if COMPILE_WITH_IPOPT64
    240     export PATH=$(PYTHON64_HOME):$(PYTHON64_HOME)/Scripts:$(PYTHON64_HOME)/Lib:"${PATH}"; \
    241     export PYTHONHOME=$(PYTHON64_HOME);
    242     mkdir -p $(DESTDIR)$(prefix)/Python_64/modelicacasadi_wrapper
    243     cp $(MC_BUILD64)/modelicacasadi_wrapper/swig/*modelicacasadi_wrapper* $(DESTDIR)$(prefix)/Python_64/modelicacasadi_wrapper
    244     rm -f $(DESTDIR)$(prefix)/Python_64/modelicacasadi_wrapper/__init__.py
    245     touch $(DESTDIR)$(prefix)/Python_64/modelicacasadi_wrapper/__init__.py
    246     echo "from modelicacasadi_wrapper import *" >> $(DESTDIR)$(prefix)/Python_64/modelicacasadi_wrapper/__init__.py
    247     export PYTHONHOME=$(ORIG_PYTHON_HOME)
    248     export PATH="$(ORIG_PATH)"
    249 endif
    250 
    251  install_modelicacasadi_transfer: $(MC_INTERFACE)/python/modelica_casadi_transfer_wrapper.py
    252 if COMPILE_WITH_IPOPT
    253     mkdir -p $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer
    254     rm -f $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer/__init__.py
    255     touch $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer/__init__.py
    256     echo "from modelica_casadi_transfer_wrapper import *" >> $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer/__init__.py
    257     cp $(MC_INTERFACE)/python/modelica_casadi_transfer_wrapper.py $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer
    258 endif
    259 if COMPILE_WITH_IPOPT64   
    260     mkdir -p $(DESTDIR)$(prefix)/Python_64/modelicacasadi_transfer
    261     rm -f $(DESTDIR)$(prefix)/Python_64/modelicacasadi_transfer/__init__.py
    262     touch $(DESTDIR)$(prefix)/Python_64/modelicacasadi_transfer/__init__.py
    263     echo "from modelica_casadi_transfer_wrapper import *" >> $(DESTDIR)$(prefix)/Python_64/modelicacasadi_transfer/__init__.py
    264     cp $(MC_INTERFACE)/python/modelica_casadi_transfer_wrapper.py $(DESTDIR)$(prefix)/Python_64/modelicacasadi_transfer
    265 endif
    266        
     47include MakefileCasadi.am
     48
    26749if NUMPY_NO_MSVCR
    26850NUMPY_NO_MSVCR_ARG=--no-msvcr="true"
     
    654436
    655437clean-local: clean-frontends clean-python-packages clean-casadi-interface
    656 
    657 clean-casadi-interface:
    658     rm -rf $(MC_BUILD)
    659     rm -rf $(MC_BUILD64)
    660 #   rm -rf $(DESTDIR)$(prefix)/Python/casadi
    661 #   rm -rf $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer
    662 if HAVE_ANT
    663     cd $(JAVA_CASADI_BUILD_DIR)/ModelicaCompilerCasADi; \
    664     $(ANT_OPTS) $(ANT) clean ; rm -rf $(MC_CASADI_BUILD)/src/cpp-generated $(MC_CASADI_BUILD)/src/generated/modelica/java/ifcasadi
    665     cd $(JAVA_CASADI_BUILD_DIR)/OptimicaCompilerCasADi; \
    666     $(ANT_OPTS) $(ANT) clean ; rm -rf $(OC_CASADI_BUILD)/src/cpp-generated $(OC_CASADI_BUILD)/src/generated/optimica/java/ifcasadi
    667 endif
    668438   
    669439clean-python-packages:
     
    701471    make -C $(abs_top_srcdir)/doc/PyJMI html
    702472
    703 
    704 .PHONY: modelicacasadi_wrapper ifcasadi install_modelicacasadi_transfer install_modelicacasadi_wrapper
  • branches/stable/Makefile.in

    r13661 r13771  
    1515
    1616@SET_MAKE@
     17
     18#
     19#    Copyright (C) 2009 Modelon AB
     20#
     21#    This program is free software: you can redistribute it and/or modify
     22#    it under the terms of the Common Public License as published by
     23#    IBM, version 1.0 of the License.
     24#
     25#    This program is distributed in the hope that it will be useful,
     26#    but WITHOUT ANY WARRANTY. See the Common Public License for more details.
     27#
     28#    You should have received a copy of the Common Public License
     29#    along with this program.  If not, see
     30#     <http://www.ibm.com/developerworks/library/os-cpl.html/>.
    1731
    1832#
     
    4963host_triplet = @host@
    5064@PYTHON_ENABLED_TRUE@am__append_1 = Python
    51 subdir = .
    5265DIST_COMMON = $(am__configure_deps) $(srcdir)/Makefile.am \
    53     $(srcdir)/Makefile.in $(srcdir)/config.h.in \
    54     $(srcdir)/jm_tests.in \
     66    $(srcdir)/Makefile.in $(srcdir)/MakefileCasadi.am \
     67    $(srcdir)/config.h.in $(srcdir)/jm_tests.in \
    5568    $(top_srcdir)/Python/src/required_defaults.py.in \
    5669    $(top_srcdir)/configure INSTALL config.guess config.sub \
    5770    depcomp install-sh ltmain.sh missing
     71subdir = .
    5872ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
    5973am__aclocal_m4_deps = $(top_srcdir)/m4/libtool.m4 \
     
    371385am--refresh:
    372386    @:
    373 $(srcdir)/Makefile.in:  $(srcdir)/Makefile.am $(am__configure_deps)
     387$(srcdir)/Makefile.in:  $(srcdir)/Makefile.am $(srcdir)/MakefileCasadi.am $(am__configure_deps)
    374388    @for dep in $?; do \
    375389      case '$(am__configure_deps)' in \
     
    865879
    866880
     881.PHONY: modelicacasadi_wrapper ifcasadi install_modelicacasadi_transfer install_modelicacasadi_wrapper
     882
    867883casadi:
    868884@COMPILE_WITH_IPOPT_TRUE@   cd $(abs_builddir)/ThirdParty/CasADi; \
     
    10171033@COMPILE_WITH_IPOPT64_TRUE@ echo "from modelica_casadi_transfer_wrapper import *" >> $(DESTDIR)$(prefix)/Python_64/modelicacasadi_transfer/__init__.py
    10181034@COMPILE_WITH_IPOPT64_TRUE@ cp $(MC_INTERFACE)/python/modelica_casadi_transfer_wrapper.py $(DESTDIR)$(prefix)/Python_64/modelicacasadi_transfer
     1035
     1036clean-casadi-interface:
     1037    rm -rf $(MC_BUILD)
     1038    rm -rf $(MC_BUILD64)
     1039#   rm -rf $(DESTDIR)$(prefix)/Python/casadi
     1040#   rm -rf $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer
     1041@HAVE_ANT_TRUE@ cd $(JAVA_CASADI_BUILD_DIR)/ModelicaCompilerCasADi; \
     1042@HAVE_ANT_TRUE@ $(ANT_OPTS) $(ANT) clean ; rm -rf $(MC_CASADI_BUILD)/src/cpp-generated $(MC_CASADI_BUILD)/src/generated/modelica/java/ifcasadi
     1043@HAVE_ANT_TRUE@ cd $(JAVA_CASADI_BUILD_DIR)/OptimicaCompilerCasADi; \
     1044@HAVE_ANT_TRUE@ $(ANT_OPTS) $(ANT) clean ; rm -rf $(OC_CASADI_BUILD)/src/cpp-generated $(OC_CASADI_BUILD)/src/generated/optimica/java/ifcasadi
    10191045
    10201046build-python-packages:
     
    13231349clean-local: clean-frontends clean-python-packages clean-casadi-interface
    13241350
    1325 clean-casadi-interface:
    1326     rm -rf $(MC_BUILD)
    1327     rm -rf $(MC_BUILD64)
    1328 #   rm -rf $(DESTDIR)$(prefix)/Python/casadi
    1329 #   rm -rf $(DESTDIR)$(prefix)/Python/modelicacasadi_transfer
    1330 @HAVE_ANT_TRUE@ cd $(JAVA_CASADI_BUILD_DIR)/ModelicaCompilerCasADi; \
    1331 @HAVE_ANT_TRUE@ $(ANT_OPTS) $(ANT) clean ; rm -rf $(MC_CASADI_BUILD)/src/cpp-generated $(MC_CASADI_BUILD)/src/generated/modelica/java/ifcasadi
    1332 @HAVE_ANT_TRUE@ cd $(JAVA_CASADI_BUILD_DIR)/OptimicaCompilerCasADi; \
    1333 @HAVE_ANT_TRUE@ $(ANT_OPTS) $(ANT) clean ; rm -rf $(OC_CASADI_BUILD)/src/cpp-generated $(OC_CASADI_BUILD)/src/generated/optimica/java/ifcasadi
    1334 
    13351351clean-python-packages:
    13361352@PYTHON_ENABLED_TRUE@   if [ -d $(assimulo_build_dir)/Assimulo ]; then \
     
    13631379    make -C $(abs_top_srcdir)/doc/PyJMI html
    13641380
    1365 .PHONY: modelicacasadi_wrapper ifcasadi install_modelicacasadi_transfer install_modelicacasadi_wrapper
    1366 
    13671381# Tell versions [3.59,3.63) of GNU make to not export all variables.
    13681382# Otherwise a system limit (for SysV at least) may be exceeded.
  • branches/stable/Python/src/pyjmi/examples/cstr_mpc_casadi.py

    r8187 r13771  
    8686    sim_model.set('_start_T', T_0_A)
    8787    sim_model.set('Tc', 280)
    88     init_res = sim_model.simulate(start_time=0., final_time=150)
     88   
     89    opts = sim_model.simulate_options()
     90    opts["CVode_options"]["maxh"] = 0.0
     91    opts["ncp"] = 0
     92   
     93    init_res = sim_model.simulate(start_time=0., final_time=150, options=opts)
    8994
    9095    ### 2. Define the optimal control problem and solve it using the MPC class
     
    159164        sim_res = sim_model.simulate(start_time=k*sample_period,
    160165                                     final_time=(k+1)*sample_period,
    161                                      input=u_k)
     166                                     input=u_k, options=opts)
    162167
    163168        # Extract state at end of sample_period from sim_res and add Gaussian
  • branches/stable/Python/src/pyjmi/examples/if_example_2.py

    r4648 r13771  
    4949    t = res['time']
    5050   
    51     assert N.abs(res.final('x') - 3.5297217)    < 1e-3
    52     assert N.abs(res.final('u') - (-0.2836621)) < 1e-3
     51    assert N.abs(res.final('x') - 3.5297217)    < 1e-2, N.abs(res.final('x') - 3.5297217)
     52    assert N.abs(res.final('u') - (-0.2836621)) < 1e-2, N.abs(res.final('u') - (-0.2836621))
    5353
    5454    if with_plots:
  • branches/stable/Python/src/pyjmi/ukf.py

    r10171 r13771  
    368368                opt['CVode_options']['atol'] = 1e-8
    369369                opt['CVode_options']['rtol'] = 1e-6
     370                opt['CVode_options']['maxh'] = 0.0
     371                opt['ncp'] = 0
    370372                print 'Simulating sigma-point '+str(i+1)+' out of '+str(sigma.shape[1])+' :'
    371373                try:
  • branches/stable/Python/src/tests_jmodelica/files/Modelica

  • branches/stable/Python/src/tests_jmodelica/files/Modelica/ExtFunctionTests.mo

    r11759 r13771  
    11package ExtFunctionTests
     2
     3model Evaluator_Double
     4    function d_i
     5     input Integer a;
     6     output Real b;
     7
     8     external "C" b=f_d_i(a) annotation(Library="evaluatorTestsShared",
     9                             Include="#include \"evaluatorTests.h\"");
     10    end d_i;
     11   
     12    function d_idd
     13     input Integer a;
     14     input Real b;
     15     input Real c;
     16     output Real d;
     17
     18     external "C" d=f_d_idd(a,b,c) annotation(Library="evaluatorTestsShared",
     19                             Include="#include \"evaluatorTests.h\"");
     20    end d_idd;
     21   
     22   
     23    Real c = d_i(1);
     24    Real d = d_idd(1, 2.0, 3.0);
     25end Evaluator_Double;
     26
     27model Evaluator_Integer
     28    function i_ii
     29     input Integer a;
     30     input Integer b;
     31     output Integer c;
     32
     33     external "C" c=f_i_ii(a,b) annotation(Library="evaluatorTestsShared",
     34                             Include="#include \"evaluatorTests.h\"");
     35    end i_ii;
     36   
     37    constant Integer c = i_ii(1,2);
     38end Evaluator_Integer;
     39
     40model Evaluator_Record
     41    record R
     42        Real x0;
     43        Real x1;
     44        Real x2;
     45        Real x3;
     46        Real x4;
     47        Real x5;
     48        Real x6;
     49        Real x7;
     50        Real x8;
     51        Real x9;
     52        Real x10;
     53    end R;
     54    function iddpR_ddddddddddd_
     55     input Integer a;
     56     input Real b;
     57     input Real c;
     58     output R d;
     59
     60     external "C" f___iddpR_ddddddddddd_(a,b,c,d) annotation(Library="evaluatorTestsShared",
     61                             Include="#include \"evaluatorTests.h\"");
     62    end iddpR_ddddddddddd_;
     63   
     64    constant R c = iddpR_ddddddddddd_(1,2.0,3.0);
     65end Evaluator_Record;
     66
     67
     68model Evaluator_Substring
     69    constant String full="Yy00";
     70    constant String sub=Modelica.Utilities.Strings.substring(full,1,1);
     71    constant String string1 = "This is line 111";
     72    constant String string2 = Modelica.Utilities.Strings.substring(string1,9,12); // string2 = \"line\"
     73    constant Integer len = Modelica.Utilities.Strings.length(string1);
     74    constant Integer start = Modelica.Utilities.Strings.Advanced.skipWhiteSpace("   Hello", 1);
     75    constant Boolean not_equal = Modelica.Utilities.Strings.isEqual("Temp", "test", true);
     76    constant Boolean equal = Modelica.Utilities.Strings.isEqual("Temp", "Temp", true);
     77end Evaluator_Substring;
     78
     79model Evaluator_Add
     80 function add1
     81     input Real a;
     82     input Real b;
     83     output Real c;
     84
     85     external "C" c=add(a,b) annotation(Library="addNumbersShared",
     86                             Include="#include \"addNumbers.h\"");
     87 end add1;
     88 
     89 function add2
     90     input Real a;
     91     input Real b;
     92     output Real c;
     93
     94     external "C" add_output(a,b,c) annotation(Library="addNumbersShared",
     95                             Include="#include \"addNumbers.h\"");
     96 end add2;
     97
     98 constant Real a = 1;
     99 constant Real b = 2;
     100 Real c = add1(a,b);
     101 Real d = add2(a,b);
     102end Evaluator_Add;
     103
     104model Evaluator_Multiple_Add
     105 function add
     106     input Real a;
     107     input Real b;
     108     input Real c;
     109     input Real d;
     110     input Real e;
     111     input Real f;
     112     input Real g;
     113     input Real h;
     114     input Real i;
     115     output Real o;
     116
     117     external "C" o=multiple_add(a,b,c,d,e,f,g,h,i) annotation(Library="addNumbersShared",
     118                             Include="#include \"addNumbers.h\"");
     119 end add;
     120 
     121 constant Real a = 1;
     122 constant Real b = 2;
     123 Real c = add(a,b,a,b,a,b,a,b,a);
     124end Evaluator_Multiple_Add;
     125
     126model Evaluator_Unknown_Shared
     127    function unknown_function
     128        input Real a;
     129        output Real b;
     130        external "C" b = unknown(a) annotation(Library="unknown");
     131    end unknown_function;
     132   
     133    constant Real a = unknown_function(1.0);
     134end Evaluator_Unknown_Shared;
    2135
    3136model ExtFunctionTest1
  • branches/stable/Python/src/tests_jmodelica/files/Modelica/Resources/CMakeLists.txt

    r10171 r13771  
    3838include_directories(${TOP_SRC}/RuntimeLibrary/src/jmi)
    3939
     40set(EVALUATORTESTS_Sources
     41    src/evaluatorTests.c
     42    Include/evaluatorTests.h
     43)
     44
    4045set(ADDNUMBERS_Sources
    4146    src/addNumbers.c
     
    7075endif()
    7176
     77#Build evaluatorTests library
     78add_library(evaluatorTestsShared SHARED ${EVALUATORTESTS_Sources})
     79if(NOT MSVC)
     80    set_target_properties(evaluatorTestsShared PROPERTIES COMPILE_FLAGS "-Wall -g -std=c89 -pedantic -Werror -O2")
     81endif()
     82
    7283#Build addNumbers library
    7384add_library(addNumbers STATIC ${ADDNUMBERS_Sources})
     85add_library(addNumbersShared SHARED ${ADDNUMBERS_Sources})
    7486if(NOT MSVC)
    7587    set_target_properties(addNumbers PROPERTIES COMPILE_FLAGS "-Wall -g -std=c89 -pedantic -Werror -O2")
     88    set_target_properties(addNumbersShared PROPERTIES COMPILE_FLAGS "-Wall -g -std=c89 -pedantic -Werror -O2")
    7689endif()
    7790
     
    106119
    107120#Install the libraries
     121install(TARGETS evaluatorTestsShared DESTINATION "${TEST_LIBRARY_INSTALL_DIR}")
    108122install(TARGETS addNumbers DESTINATION "${TEST_LIBRARY_INSTALL_DIR}")
     123install(TARGETS addNumbersShared DESTINATION "${TEST_LIBRARY_INSTALL_DIR}")
    109124install(TARGETS arrayFunctions DESTINATION "${TEST_LIBRARY_INSTALL_DIR}")
    110125install(TARGETS externalFunctionsC DESTINATION "${TEST_LIBRARY_INSTALL_DIR}")
  • branches/stable/Python/src/tests_jmodelica/files/Modelica/Resources/Include/addNumbers.h

    r3965 r13771  
    22#define ADDNUMBERS_H
    33
    4 double add(double a, double b);
     4#if defined _WIN32
     5    #define DllExport __declspec(dllexport)
     6#else
     7    #define DllExport
     8#endif
     9
     10DllExport double add(double a, double b);
     11DllExport void add_output(double a, double b, double *c);
     12DllExport double multiple_add(double a, double b, double c, double d, double e, double f, double g, double h, double i);
    513void multiplyAnArray(int* inputs, int* outputs, int size, int m);
    614
  • branches/stable/Python/src/tests_jmodelica/files/Modelica/Resources/src/addNumbers.c

    r6459 r13771  
    11#include "addNumbers.h"
    22
    3 double add(double a, double b)
     3DllExport double add(double a, double b)
    44{
    5   return a+b;
     5  return a + b;
     6}
     7
     8DllExport void add_output(double a, double b, double *c)
     9{
     10  *c = a + b;
     11}
     12
     13DllExport double multiple_add(double a, double b, double c, double d, double e, double f, double g, double h, double i)
     14{
     15  return a+b+c+d+e+f+g+h+i;
    616}
    717
  • branches/stable/Python/src/tests_jmodelica/general/base_simul.py

    r10446 r13771  
    286286       
    287287        if not cvode_options:
    288             cvode_options = {'atol':self.abs_tol,'rtol':self.rel_tol}
     288            cvode_options = {'atol':self.abs_tol,'rtol':self.rel_tol, 'maxh':0.0}
     289        else:
     290            if not 'maxh' in cvode_options:
     291                cvode_options['maxh'] = 0.0
    289292       
    290293        if isinstance(self.model, FMUModelME1) or isinstance(self.model, FMUModelME2):
  • branches/stable/Python/src/tests_jmodelica/general/test_extfunctions.py

    r11759 r13771  
    2222
    2323import nose
     24import fnmatch
    2425
    2526from pymodelica import compile_fmu
    2627from pymodelica.common.core import get_platform_dir, create_temp_dir
    27 from pyfmi import load_fmu
     28from pyfmi import load_fmu, FMUModelME2
    2829from pyfmi.fmi import FMUException
    2930from tests_jmodelica import testattr, get_files_path
     
    3334path_to_mofiles = os.path.join(get_files_path(), 'Modelica')
    3435
     36class TestEvaluator:
     37    @classmethod
     38    def setUpClass(cls):
     39        """
     40        Sets up the test class.
     41        """
     42        cls.fpath = path(path_to_mofiles, "ExtFunctionTests.mo")
     43   
     44    @testattr(stddist_base = True)
     45    def test_builtin_substring(self):
     46        cpath = "ExtFunctionTests.Evaluator_Substring"
     47        fmu_name = compile_fmu(cpath, self.fpath, compiler_options={"external_constant_evaluation_dynamic":True}, compiler_log_level="d:log.txt")
     48       
     49        nbr_of_evaluator_calls = 0
     50        with open("log.txt") as f:
     51            res = fnmatch.filter(f, "Succesfully connected external function '*' to the evaluator*")
     52            nbr_of_evaluator_calls = len(res)
     53       
     54        assert nbr_of_evaluator_calls == 4, "Wrong number of external function calls, check log."
     55       
     56        model = load_fmu(fmu_name)
     57       
     58        assert model.get("sub")[0] == "Y", model.get("sub")
     59        assert model.get("string2")[0] == "line", model.get("string2")
     60        assert model.get("len") == 16, model.get("len")
     61        assert model.get("start") == 4, model.get("start")
     62        assert not model.get("not_equal"), model.get("not_equal")
     63        assert model.get("equal"), model.get("equal")
     64   
     65    @testattr(stddist_base = True)
     66    def test_add(self):
     67        cpath = "ExtFunctionTests.Evaluator_Add"
     68        fmu_name = compile_fmu(cpath, self.fpath, compiler_options={"external_constant_evaluation_dynamic":True}, version=2.0, compiler_log_level="d:log.txt")
     69       
     70        nbr_of_evaluator_calls = 0
     71        with open("log.txt") as f:
     72            res = fnmatch.filter(f, "Succesfully connected external function '*' to the evaluator*")
     73            nbr_of_evaluator_calls = len(res)
     74       
     75        assert nbr_of_evaluator_calls == 2, "Wrong number of external function calls, check log."
     76       
     77        model = FMUModelME2(fmu_name, _connect_dll=False)
     78       
     79        assert model.get_variable_start("c") == 3, model.get_variable_start("c")
     80        assert model.get_variable_start("d") == 3, model.get_variable_start("d")
     81   
     82    @testattr(stddist_base = True)
     83    def test_unsupported_signature(self):
     84        cpath = "ExtFunctionTests.Evaluator_Multiple_Add"
     85        fmu_name = compile_fmu(cpath, self.fpath, compiler_options={"external_constant_evaluation_dynamic":True}, compiler_log_level="d:log.txt")
     86       
     87        matches = 0
     88        with open("log.txt") as f:
     89            res = fnmatch.filter(f, "*is not supported. Disabling use of the evaluator*")
     90            matches = len(res)
     91       
     92        assert matches == 1, "Does not seem to disabling the evaluator"
     93
     94    @testattr(stddist_base = True)
     95    def test_unknown_shared_library(self):
     96        cpath = "ExtFunctionTests.Evaluator_Unknown_Shared"
     97        try:
     98            fmu_name = compile_fmu(cpath, self.fpath, compiler_options={"external_constant_evaluation_dynamic":True}, compiler_log_level="d:log_unknown_shared.txt")
     99        except: #The compilation will fail, the interesting parts will though still be contained in the log file
     100            pass
     101       
     102        matches = 0
     103        with open("log_unknown_shared.txt") as f:
     104            res = fnmatch.filter(f, "Could not find a shared library containing*")
     105            matches = len(res)
     106       
     107        assert matches == 1, "Seems to have found an unknown shared library"
     108   
     109    @testattr(stddist_base = True)
     110    def test_double_return(self):
     111        cpath = "ExtFunctionTests.Evaluator_Double"
     112        fmu_name = compile_fmu(cpath, self.fpath, compiler_options={"external_constant_evaluation_dynamic":True}, version=2.0, compiler_log_level="d:log.txt")
     113       
     114        nbr_of_evaluator_calls = 0
     115        with open("log.txt") as f:
     116            res = fnmatch.filter(f, "Succesfully connected external function '*' to the evaluator*")
     117            nbr_of_evaluator_calls = len(res)
     118       
     119        assert nbr_of_evaluator_calls == 2, "Wrong number of external function calls, check log."
     120       
     121        model = FMUModelME2(fmu_name, _connect_dll=False)
     122       
     123        assert model.get_variable_start("c") == 3.0, model.get_variable_start("c")
     124        assert model.get_variable_start("d") == 9.0, model.get_variable_start("d")
     125   
     126    @testattr(stddist_base = True)
     127    def test_integer_return(self):
     128        cpath = "ExtFunctionTests.Evaluator_Integer"
     129        fmu_name = compile_fmu(cpath, self.fpath, compiler_options={"external_constant_evaluation_dynamic":True}, version=2.0, compiler_log_level="d:log.txt")
     130       
     131        nbr_of_evaluator_calls = 0
     132        with open("log.txt") as f:
     133            res = fnmatch.filter(f, "Succesfully connected external function '*' to the evaluator*")
     134            nbr_of_evaluator_calls = len(res)
     135       
     136        assert nbr_of_evaluator_calls == 1, "Wrong number of external function calls, check log."
     137       
     138        model = FMUModelME2(fmu_name, _connect_dll=False)
     139       
     140        assert model.get_variable_start("c") == 3.0, model.get_variable_start("c")
     141   
     142    @testattr(stddist_base = True)
     143    def test_record(self):
     144        cpath = "ExtFunctionTests.Evaluator_Record"
     145        fmu_name = compile_fmu(cpath, self.fpath, compiler_options={"external_constant_evaluation_dynamic":True}, version=2.0, compiler_log_level="d:log.txt")
     146       
     147        nbr_of_evaluator_calls = 0
     148        with open("log.txt") as f:
     149            res = fnmatch.filter(f, "Succesfully connected external function '*' to the evaluator*")
     150            nbr_of_evaluator_calls = len(res)
     151       
     152        assert nbr_of_evaluator_calls == 1, "Wrong number of external function calls, check log."
     153       
     154        model = FMUModelME2(fmu_name, _connect_dll=False)
     155       
     156        assert model.get_variable_start("c.x0") == 1.0, model.get_variable_start("c.x0")
     157        assert model.get_variable_start("c.x1") == 2.0, model.get_variable_start("c.x1")
     158        assert model.get_variable_start("c.x2") == 3.0, model.get_variable_start("c.x2")
     159        assert model.get_variable_start("c.x3") == 3.0, model.get_variable_start("c.x3")
     160        assert model.get_variable_start("c.x4") == 4.0, model.get_variable_start("c.x4")
     161        assert model.get_variable_start("c.x5") == 5.0, model.get_variable_start("c.x5")
     162        assert model.get_variable_start("c.x6") == 6.0, model.get_variable_start("c.x6")
     163        assert model.get_variable_start("c.x7") == 7.0, model.get_variable_start("c.x7")
     164        assert model.get_variable_start("c.x8") == 8.0, model.get_variable_start("c.x8")
     165        assert model.get_variable_start("c.x9") == 9.0, model.get_variable_start("c.x9")
     166        assert model.get_variable_start("c.x10") == 10.0, model.get_variable_start("c.x10")
     167   
    35168class TestExternalStatic:
    36169
  • branches/stable/Python/src/tests_jmodelica/optimization/test_casadi_collocation.py

    r13401 r13771  
    366366        opts["CVode_options"]["rtol"] = 1e-6
    367367        opts["CVode_options"]["atol"] = 1e-8 * model.nominal_continuous_states
     368        opts["CVode_options"]["maxh"] = 0.0
     369        opts["ncp"] = 0
    368370        init_res = model.simulate(final_time=300, input=('Tc', u_traj),
    369371                                  options=opts)
     
    21252127        opts["CVode_options"]["rtol"] = 1e-6
    21262128        opts["CVode_options"]["atol"] = 1e-8 * model.nominal_continuous_states
     2129        opts["CVode_options"]["maxh"] = 0.0
     2130        opts["ncp"] = 0
    21272131        res = model.simulate(start_time=0., final_time=150., input=opt_input,
    21282132                             options=opts)
  • branches/stable/Python/src/tests_jmodelica/optimization/test_realtime_mpc.py

    r13575 r13771  
    3535def check_result(results, ref):
    3636    for key in ref:
    37         assert abs(ref[key] - results[key][-1]) < 1e-3, abs(ref[key] - results[key][-1])
     37        assert abs(ref[key] - results[key][-1]) < 1e-2, abs(ref[key] - results[key][-1])
    3838       
    3939
  • branches/stable/Python/src/tests_jmodelica/simulation/test_assimulo_interface_fmi.py

    r13366 r13771  
    20022002        opts["CVode_options"]["rtol"] = 1e-4
    20032003        opts["CVode_options"]["atol"] = 1e-6
     2004        opts["CVode_options"]["maxh"] = 0.0
     2005        opts["ncp"] = 0
    20042006        res = bounce.simulate(start_time=2.,final_time=5.,options=opts)
    20052007
     
    20202022        opts["CVode_options"]["rtol"] = 1e-4
    20212023        opts["CVode_options"]["atol"] = 1e-6
     2024        opts["CVode_options"]["maxh"] = 0.0
     2025        opts["ncp"] = 0
    20222026        res = bounce.simulate(final_time=3., options=opts)
    20232027       
     
    20332037        opt["CVode_options"]["rtol"] = 1e-4
    20342038        opt["CVode_options"]["atol"] = 1e-6
     2039        opt["CVode_options"]["maxh"] = 0.0
     2040        opt["ncp"] = 0
    20352041        res = bounce.simulate(final_time=3., options=opt)
    20362042       
     
    20592065        opts["CVode_options"]["rtol"] = 1e-4
    20602066        opts["CVode_options"]["atol"] = 1e-6
     2067        opts["CVode_options"]["maxh"] = 0.0
     2068        opts["ncp"] = 0
    20612069        res = bounce.simulate(final_time=3., options=opts)
    20622070
     
    20702078        #Writing continuous
    20712079        bounce = load_fmu('bouncingBall.fmu', path_to_fmus_me1)
    2072         #bounce.initialize(options={'initialize':False})
    20732080        res = bounce.simulate(final_time=3.,
    2074             options={'initialize':True,'CVode_options':{'iter':'FixedPoint','rtol':1e-6,'atol':1e-6}})
     2081            options={'initialize':True,'ncp':0, 'CVode_options':{'maxh':0.0, 'iter':'FixedPoint','rtol':1e-6,'atol':1e-6}})
    20752082   
    20762083        nose.tools.assert_almost_equal(res.solver.rtol, 0.00000100, 7)
     
    20922099        opts["CVode_options"]["rtol"] = 1e-4
    20932100        opts["CVode_options"]["atol"] = 1e-6
    2094         #bounce.initialize()
     2101        opts["CVode_options"]["maxh"] = 0.0
     2102        opts["ncp"] = 0
    20952103        res = bounce.simulate(final_time=3., options=opts)
    20962104       
     
    20992107       
    21002108        bounce.reset()
    2101         #bounce.initialize()
    2102        
     2109
    21032110        nose.tools.assert_almost_equal(bounce.get('h'), 1.00000,5)
    21042111       
  • branches/stable/Python/src/tests_jmodelica/test_delay.py

    r10318 r13771  
    3838def simulate(fmu, final_time, maxh = None):
    3939    opts = fmu.simulate_options()     
    40     opts['solver'] = 'CVode'           
     40    opts['solver'] = 'CVode'
     41    opts['ncp'] = 0
     42    opts['CVode_options']['maxh'] = 0.0
    4143    if maxh is not None:
    4244        opts['CVode_options']['maxh'] = maxh
  • branches/stable/Python/src/tests_jmodelica/test_fmi_2.py

    r13338 r13771  
    988988        assert opts['initialize']
    989989        assert opts['with_jacobian'] == "Default"
    990         assert opts['ncp'] == 0
    991990
    992991        #Test the result file
  • branches/stable/Python/src/tests_jmodelica/test_fmi_coupled.py

    r13338 r13771  
    8282        nose.tools.assert_almost_equal(res.final("time"),1.5)
    8383        nose.tools.assert_almost_equal(res.final("First.J1.w"),res.final("Second.J1.w"))
    84         nose.tools.assert_almost_equal(res.final("First.J1.w"), 3.2501079, places=3)
     84        nose.tools.assert_almost_equal(res.final("First.J1.w"), 3.2501079, places=2)
    8585       
    8686        coupled.reset()
     
    9090        nose.tools.assert_almost_equal(res.final("time"),1.5)
    9191        nose.tools.assert_almost_equal(res.final("First.J1.w"),res.final("Second.J1.w"))
    92         nose.tools.assert_almost_equal(res.final("First.J1.w"), 3.2501079, places=3)
     92        nose.tools.assert_almost_equal(res.final("First.J1.w"), 3.2501079, places=2)
    9393
    9494    @testattr(stddist_full = True)
  • branches/stable/RuntimeLibrary/CMakeLists.txt

    r9663 r13771  
    5555if(" ${CMAKE_C_FLAGS} " MATCHES " -m64 ")
    5656    set(RTLIB_LIB_DIR ${JMODELICA_INSTALL_DIR}/lib/RuntimeLibrary64)
     57    set(RTLIB_BIN_DIR ${JMODELICA_INSTALL_DIR}/bin64)
    5758else()
    5859    set(RTLIB_LIB_DIR ${JMODELICA_INSTALL_DIR}/lib/RuntimeLibrary)
     60    set(RTLIB_BIN_DIR ${JMODELICA_INSTALL_DIR}/bin)
    5961endif()
    6062install(CODE "file(MAKE_DIRECTORY $ENV{DESTDIR}${RTLIB_LIB_DIR})")
     
    9193add_subdirectory(src/modules)
    9294
     95#Add evaluator
     96include_directories(src/evaluator)
     97add_subdirectory(src/evaluator)
    9398
    9499if(EXTRA_RUNTIME_MODULES)
  • branches/stable/RuntimeLibrary/Makefiles/Makefile.linux

    r10938 r13771  
    126126LIBS_FMUCS10 = -lfmi1_cs -lfmi1_me $(LIBS_FMU_STD) $(LIB_COMMON) -l:libsundials_cvode.a
    127127LIBS_FMU20   = -lfmi2 $(LIBS_FMU_STD) $(LIB_COMMON) -l:libsundials_cvode.a
    128 LIBS_CEVAL   = $(LIBS_FMU_STD)
     128LIBS_CEVAL   = -ljmi_evaluator_util $(LIBS_FMU_STD)
    129129
    130130# Include paths for compilation
  • branches/stable/RuntimeLibrary/Makefiles/Makefile.macosx

    r10938 r13771  
    125125LIBS_FMUCS10 = -lfmi1_cs -lfmi1_me $(LIBS_FMU_STD) $(LIB_COMMON) $(SUNDIALS_HOME)/lib/libsundials_cvode.a
    126126LIBS_FMU20   = -lfmi2 $(LIBS_FMU_STD) $(LIB_COMMON) $(SUNDIALS_HOME)/lib/libsundials_cvode.a
    127 LIBS_CEVAL   = $(LIBS_FMU_STD)
     127LIBS_CEVAL   = -ljmi_evaluator_util $(LIBS_FMU_STD)
    128128
    129129# Include paths for compilation
  • branches/stable/RuntimeLibrary/Makefiles/Makefile.windows

    r11565 r13771  
    160160LIBS_FMUCS10 = -lfmi1_cs -lfmi1_me $(LIBS_FMU_ALL)
    161161LIBS_FMU20   = -lfmi2              $(LIBS_FMU_ALL)
    162 LIBS_CEVAL = $(LIBS_FMU_STD)
     162LIBS_CEVAL = -ljmi_evaluator_util $(LIBS_FMU_STD)
    163163
    164164# Include paths for compilation
  • branches/stable/RuntimeLibrary/src

  • branches/stable/RuntimeLibrary/src/fmi1_cs/CMakeLists.txt

    r6737 r13771  
    3737
    3838#Install the libraries
    39 install(TARGETS fmi1_cs DESTINATION "${RTLIB_LIB_DIR}")
     39if (NOT MSVC)
     40    install(TARGETS fmi1_cs DESTINATION "${RTLIB_LIB_DIR}")
     41endif()
    4042
    4143#Install header files
  • branches/stable/RuntimeLibrary/src/fmi1_me/CMakeLists.txt

    r6737 r13771  
    3939
    4040#Install the libraries
    41 install(TARGETS fmi1_me DESTINATION "${RTLIB_LIB_DIR}")
     41if (NOT MSVC)
     42    install(TARGETS fmi1_me DESTINATION "${RTLIB_LIB_DIR}")
     43endif()
    4244
    4345#Install header files
  • branches/stable/RuntimeLibrary/src/fmi2/CMakeLists.txt

    r6737 r13771  
    4949
    5050#Install the libraries
    51 install(TARGETS fmi2 DESTINATION "${RTLIB_LIB_DIR}")
     51if (NOT MSVC)
     52    install(TARGETS fmi2 DESTINATION "${RTLIB_LIB_DIR}")
     53endif()
    5254
    5355#Install header files
  • branches/stable/RuntimeLibrary/src/jmi/CMakeLists.txt

    r12148 r13771  
    202202
    203203    #Install the libraries
    204     install(TARGETS jmi
    205         DESTINATION "${RTLIB_LIB_DIR}")
     204    if (NOT MSVC)
     205        install(TARGETS jmi
     206            DESTINATION "${RTLIB_LIB_DIR}")
     207    endif()
    206208
    207209    #Install header files
     
    247249
    248250    #Install the libraries
    249     install(TARGETS ModelicaExternalC ModelicaStandardTables ModelicaIO ModelicaMatIO zlib
    250         DESTINATION "${RTLIB_LIB_DIR}")
     251    if (NOT MSVC)
     252        install(TARGETS ModelicaExternalC ModelicaStandardTables ModelicaIO ModelicaMatIO zlib
     253            DESTINATION "${RTLIB_LIB_DIR}")
     254    endif()
    251255
    252256    install(DIRECTORY "${MSLCSOURCES}/"
  • branches/stable/ThirdParty/build_thirdparties/build/sundials/makefile

    r12138 r13771  
    2828    mkdir -p $(SUNDIALS_BUILD_DIR); \
    2929    cd $(SUNDIALS_BUILD_DIR); \
    30     cmake $(GENERATOR) -DEXAMPLES_ENABLE=OFF -DBUILD_SHARED_LIBS=OFF -DCMAKE_C_FLAGS=$(SUNDIALS_C_FLAGS) -DCMAKE_INSTALL_PREFIX:PATH=$(SUNDIALS_INSTALL_DIR) $(SUNDIALS_SRC_DIR)
     30    cmake $(GENERATOR) $(SUPERLU_ADDON) -DEXAMPLES_ENABLE=OFF -DBUILD_SHARED_LIBS=OFF -DCMAKE_C_FLAGS=$(SUNDIALS_C_FLAGS) -DCMAKE_INSTALL_PREFIX:PATH=$(SUNDIALS_INSTALL_DIR) $(SUNDIALS_SRC_DIR)
    3131
    3232clean:
Note: See TracChangeset for help on using the changeset viewer.