Claudio Gomes 7 years ago
parent
commit
0f58049de2

+ 244 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/model_exchange/main.c

@@ -0,0 +1,244 @@
+/* ------------------------------------------------------------------------- 
+ * main.c
+ * Implements simulation of a single FMU instance using the forward Euler
+ * method for numerical integration.
+ * Command syntax: see printHelp()
+ * Simulates the given FMU from t = 0 .. tEnd with fixed step size h and
+ * writes the computed solution to file 'result.csv'.
+ * The CSV file (comma-separated values) may e.g. be plotted using
+ * OpenOffice Calc or Microsoft Excel.
+ * This program demonstrates basic use of an FMU.
+ * Real applications may use advanced numerical solvers instead, means to 
+ * exactly locate state events in time, graphical plotting utilities, support
+ * for co-execution of many FMUs, stepping and debug support, user control
+ * of parameter and start values etc. 
+ * All this is missing here.
+ *
+ * Revision history
+ *  07.02.2010 initial version released in FMU SDK 1.0
+ *  05.03.2010 bug fix: removed strerror(GetLastError()) from error messages
+ *  11.06.2010 bug fix: replaced win32 API call to OpenFile in getFmuPath
+ *    which restricted path length to FMU to 128 chars. New limit is MAX_PATH.
+ *  15.07.2010 fixed wrong label in xml parser: deault instead of default
+ *  13.12.2010 added check for undefined 'declared type' to xml parser
+ *  31.07.2011 bug fix: added missing freeModelInstance(c)
+ *  31.07.2011 bug fix: added missing terminate(c)
+ *  30.08.2012 fixed access violation in xmlParser after reporting unknown attribute name
+ *
+ * Free libraries and tools used to implement this simulator:
+ *  - header files from the FMU specification
+ *  - eXpat 2.0.1 XML parser, see http://expat.sourceforge.net
+ *  - 7z.exe 4.57 zip and unzip tool, see http://www.7-zip.org
+ * Author: Jakob Mauss
+ * Copyright QTronic GmbH. All rights reserved.
+ * -------------------------------------------------------------------------*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h> //strerror()
+#include "fmi_me.h"
+#include "sim_support.h"
+
+FMU fmu; // the fmu to simulate
+
+// simulate the given FMU using the forward euler method.
+// time events are processed by reducing step size to exactly hit tNext.
+// state events are checked and fired only at the end of an Euler step. 
+// the simulator may therefore miss state events and fires state events typically too late.
+static int simulate(FMU* fmu, double tEnd, double h, fmiBoolean loggingOn, char separator) {
+    int i, n;
+    double dt, tPre;
+    fmiBoolean timeEvent, stateEvent, stepEvent;
+    double time;  
+    int nx;                          // number of state variables
+    int nz;                          // number of state event indicators
+    double *x;                       // continuous states
+    double *xdot;                    // the crresponding derivatives in same order
+    double *z = NULL;                // state event indicators
+    double *prez = NULL;             // previous values of state event indicators
+    fmiEventInfo eventInfo;          // updated by calls to initialize and eventUpdate
+    ModelDescription* md;            // handle to the parsed XML file
+    const char* guid;                // global unique id of the fmu
+    fmiCallbackFunctions callbacks;  // called by the model during simulation
+    fmiComponent c;                  // instance of the fmu 
+    fmiStatus fmiFlag;               // return code of the fmu functions
+    fmiReal t0 = 0;                  // start time
+    fmiBoolean toleranceControlled = fmiFalse;
+    int nSteps = 0;
+    int nTimeEvents = 0;
+    int nStepEvents = 0;
+    int nStateEvents = 0;
+    FILE* file;
+
+    // instantiate the fmu
+    md = fmu->modelDescription;
+    guid = getString(md, att_guid);
+    callbacks.logger = fmuLogger;
+    callbacks.allocateMemory = calloc;
+    callbacks.freeMemory = free;
+    c = fmu->instantiateModel(getModelIdentifier(md), guid, callbacks, loggingOn);
+    if (!c) return error("could not instantiate model");
+
+    // allocate memory 
+    nx = getNumberOfStates(md);
+    nz = getNumberOfEventIndicators(md);
+    x    = (double *) calloc(nx, sizeof(double));
+    xdot = (double *) calloc(nx, sizeof(double));
+    if (nz>0) {
+        z    =  (double *) calloc(nz, sizeof(double));
+        prez =  (double *) calloc(nz, sizeof(double));
+    }
+    if ((!x || !xdot) || (nz>0 && (!z || !prez))) return error("out of memory");
+
+    // open result file
+    if (!(file=fopen(RESULT_FILE, "w"))) {
+        printf("could not write %s because:\n", RESULT_FILE);
+        printf("    %s\n", strerror(errno));
+        free(x);
+        free(xdot);
+        free(z);
+        free(prez);
+
+        return 0; // failure
+    }
+
+    // set the start time and initialize
+    time = t0;
+    fmiFlag =  fmu->setTime(c, t0);
+    if (fmiFlag > fmiWarning) return error("could not set time");
+    fmiFlag =  fmu->initialize(c, toleranceControlled, t0, &eventInfo);
+    if (fmiFlag > fmiWarning)  return error("could not initialize model");
+    if (eventInfo.terminateSimulation) {
+        printf("model requested termination at init");
+        tEnd = time;
+    }
+
+    // output solution for time t0
+    outputRow(fmu, c, t0, file, separator, fmiTrue);  // output column names
+    outputRow(fmu, c, t0, file, separator, fmiFalse); // output values
+
+    // enter the simulation loop
+    while (time < tEnd) {
+     // get current state and derivatives
+     fmiFlag = fmu->getContinuousStates(c, x, nx);
+     if (fmiFlag > fmiWarning) return error("could not retrieve states");
+     fmiFlag = fmu->getDerivatives(c, xdot, nx);
+     if (fmiFlag > fmiWarning) return error("could not retrieve derivatives");
+
+     // advance time
+     tPre = time;
+     time = min(time+h, tEnd);
+     timeEvent = eventInfo.upcomingTimeEvent && eventInfo.nextEventTime < time;
+     if (timeEvent) time = eventInfo.nextEventTime;
+     dt = time - tPre; 
+     fmiFlag = fmu->setTime(c, time);
+     if (fmiFlag > fmiWarning) error("could not set time");
+
+     // perform one step
+     for (i=0; i<nx; i++) x[i] += dt*xdot[i]; // forward Euler method
+     fmiFlag = fmu->setContinuousStates(c, x, nx);
+     if (fmiFlag > fmiWarning) return error("could not set states");
+     if (loggingOn) printf("Step %d to t=%.16g\n", nSteps, time);
+
+     // Check for step event, e.g. dynamic state selection
+     fmiFlag = fmu->completedIntegratorStep(c, &stepEvent);
+     if (fmiFlag > fmiWarning) return error("could not complete integrator step");
+
+     // Check for state event
+     for (i=0; i<nz; i++) prez[i] = z[i]; 
+     fmiFlag = fmu->getEventIndicators(c, z, nz);
+     if (fmiFlag > fmiWarning) return error("could not retrieve event indicators");
+     stateEvent = FALSE;
+     for (i=0; i<nz; i++) 
+         stateEvent = stateEvent || (prez[i] * z[i] < 0);
+
+     // handle events
+     if (timeEvent || stateEvent || stepEvent) {
+
+        if (timeEvent) {
+            nTimeEvents++;
+            if (loggingOn) printf("time event at t=%.16g\n", time);
+        }
+        if (stateEvent) {
+            nStateEvents++;
+            if (loggingOn) for (i=0; i<nz; i++)
+                printf("state event %s z[%d] at t=%.16g\n", 
+                        (prez[i]>0 && z[i]<0) ? "-\\-" : "-/-", i, time);
+        }
+        if (stepEvent) {
+            nStepEvents++;
+            if (loggingOn) printf("step event at t=%.16g\n", time);
+        }
+
+        // event iteration in one step, ignoring intermediate results
+        fmiFlag = fmu->eventUpdate(c, fmiFalse, &eventInfo);
+        if (fmiFlag > fmiWarning) return error("could not perform event update");
+        
+        // terminate simulation, if requested by the model
+        if (eventInfo.terminateSimulation) {
+            printf("model requested termination at t=%.16g\n", time);
+            break; // success
+        }
+
+        // check for change of value of states
+        if (eventInfo.stateValuesChanged && loggingOn) {
+            printf("state values changed at t=%.16g\n", time);
+        }
+        
+        // check for selection of new state variables
+        if (eventInfo.stateValueReferencesChanged && loggingOn) {
+            printf("new state variables selected at t=%.16g\n", time);
+        }
+
+     } // if event
+     outputRow(fmu, c, time, file, separator, fmiFalse); // output values for this step
+     nSteps++;
+  } // while
+
+  // cleanup
+  if(! eventInfo.terminateSimulation) fmu->terminate(c);
+  fmu->freeModelInstance(c);
+  fclose(file);
+  if (x!=NULL) free(x);
+  if (xdot!= NULL) free(xdot);
+  if (z!= NULL) free(z);
+  if (prez!= NULL) free(prez);
+
+  // print simulation summary 
+  printf("Simulation from %g to %g terminated successful\n", t0, tEnd);
+  printf("  steps ............ %d\n", nSteps);
+  printf("  fixed step size .. %g\n", h);
+  printf("  time events ...... %d\n", nTimeEvents);
+  printf("  state events ..... %d\n", nStateEvents);
+  printf("  step events ...... %d\n", nStepEvents);
+
+  return 1; // success
+}
+
+int main(int argc, char *argv[]) {
+    const char* fmuFileName;
+
+    // parse command line arguments and load the FMU
+    double tEnd = 1.0;
+    double h=0.1;
+    int loggingOn = 0;
+    char csv_separator = ',';
+    parseArguments(argc, argv, &fmuFileName, &tEnd, &h, &loggingOn, &csv_separator);
+    loadFMU(fmuFileName);
+
+    // run the simulation
+    printf("FMU Simulator: run '%s' from t=0..%g with step size h=%g, loggingOn=%d, csv separator='%c'\n",
+            fmuFileName, tEnd, h, loggingOn, csv_separator);
+    simulate(&fmu, tEnd, h, loggingOn, csv_separator);
+    printf("CSV file '%s' written\n", RESULT_FILE);
+
+    // release FMU 
+#if WINDOWS
+    FreeLibrary(fmu.dllHandle);
+#else /* WINDOWS */
+    dlclose(fmu.dllHandle);
+#endif /* WINDOWS */
+    freeElement(fmu.modelDescription);
+    deleteUnzippedFiles();
+    return EXIT_SUCCESS;
+}

+ 72 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/models/Makefile

@@ -0,0 +1,72 @@
+# Build the .fmu files for both co-simulation and model-exchange.
+#
+# The build_fmu script calls make with the appropriate makefile variables set.
+
+# The architecture: linux32, linux64, darwin32, darwin64
+ARCH = darwin64
+
+# Either cs for co-simuluation or me for model exchange.
+CSORME = cs
+CSORME_INCLUDE = -DFMI_COSIMULATION -I../../co_simulation/include
+#CSORME = me
+#CSORME_INCLUDE = -I../../model_exchange/include
+
+# The suffix for shared libraries.
+# dylib for Mac OS X, so for Linux
+SHARED_LIBRARY_SUFFIX = dylib
+#SHARED_LIBRARY_SUFFIX = so
+
+# Empty for Mac OS X, -fPIC for Linux
+PIC =
+#PIC = -fPIC
+
+# Build the .fmu files for both co-simulation and model-exchange
+all:
+	chmod 777 build_fmu
+	./build_fmu me bouncingBall
+	./build_fmu me dq
+	./build_fmu me inc
+	./build_fmu me values
+	./build_fmu me vanDerPol
+	./build_fmu cs bouncingBall
+	./build_fmu cs dq
+	./build_fmu cs inc
+	./build_fmu cs values
+	./build_fmu cs vanDerPol
+
+# CBITSFLAGS is set to -m32 to build linux32 fmus
+
+%.o: %.c
+	echo `pwd`
+	$(CC) -g -c $(CBITSFLAGS) $(PIC) -Wall $(CSORME_INCLUDE) $(CFLAGS) $< -o $@
+
+%.so: %.o
+	$(CC) $(CBITSFLAGS) -shared -Wl,-soname,$@ -o $@ $<
+
+%.dylib: %.o
+	$(CC) -dynamiclib -o $@ $<
+
+%.fmu: %.$(SHARED_LIBRARY_SUFFIX)
+	rm -rf fmu
+	mkdir -p fmu/binaries/$(ARCH) fmu/sources fmu/documentation
+	cp $< fmu/binaries/$(ARCH)
+	-cp *.c fmu/sources
+	rsync -av --ignore-missing-args ./*.h ./fmu/sources
+	-cp *.html *.png fmu/documentation
+	cp modelDescription_$(CSORME).xml fmu/modelDescription.xml
+	cp model.png fmu
+	@if [ ! -d ../../../fmu/$(CSORME) ]; then \
+		echo "mkdir -p ../../../fmu/$(CSORME)"; \
+		mkdir -p ../../../fmu/$(CSORME); \
+	fi
+	(cd fmu; zip -q -r ../../../../fmu/$(CSORME)/$@ *)
+
+clean:
+	(cd bouncingBall; make dirclean)
+	(cd dq; make dirclean)
+	(cd inc; make dirclean)
+	(cd values; make dirclean)
+	(cd vanDerPol; make dirclean)
+
+dirclean:
+	rm -rf *.so *.dylib *.o *.fmu *~ fmu

+ 3 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/models/bouncingBall/Makefile

@@ -0,0 +1,3 @@
+CFLAGS = -I..
+
+include ../Makefile

+ 116 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/models/bouncingBall/bouncingBall.c

@@ -0,0 +1,116 @@
+/* ---------------------------------------------------------------------------*
+ * Sample implementation of an FMU - a bouncing ball. 
+ * This demonstrates the use of state events and reinit of states.
+ * Equations:
+ *  der(h) = v;
+ *  der(v) = -g;
+ *  when h<0 then v := -e * v;  
+ *  where
+ *    h      height [m], used as state, start = 1
+ *    v      velocity of ball [m/s], used as state
+ *    der(h) velocity of ball [m/s] 
+ *    der(v) acceleration of ball [m/s2] 
+ *    g      acceleration of gravity [m/s2], a parameter, start = 9.81
+ *    e      a dimensionless parameter, start = 0.7
+ *
+ * Copyright QTronic GmbH. All rights reserved.
+ * ---------------------------------------------------------------------------*/
+
+// define class name and unique id
+#define MODEL_IDENTIFIER bouncingBall
+#define MODEL_GUID "{8c4e810f-3df3-4a00-8276-176fa3c9f003}"
+
+// define model size
+#define NUMBER_OF_REALS 6
+#define NUMBER_OF_INTEGERS 0
+#define NUMBER_OF_BOOLEANS 0
+#define NUMBER_OF_STRINGS 0
+#define NUMBER_OF_STATES 2
+#define NUMBER_OF_EVENT_INDICATORS 1
+
+// include fmu header files, typedefs and macros
+#include "fmuTemplate.h"
+
+// define all model variables and their value references
+// conventions used here:
+// - if x is a variable, then macro x_ is its variable reference
+// - the vr of a variable is its index in array  r, i, b or s
+// - if k is the vr of a real state, then k+1 is the vr of its derivative
+#define h_      0
+#define der_h_  1
+#define v_      2
+#define der_v_  3
+#define g_      4
+#define e_      5
+
+// define initial state vector as vector of value references
+#define STATES { h_, v_ }
+
+// called by fmiInstantiateModel
+// Set values for all variables that define a start value
+// Settings used unless changed by fmiSetX before fmiInitialize
+void setStartValues(ModelInstance *comp) {
+    r(h_)     =  1;
+    r(v_)     =  0;
+    r(der_v_) = -9.81;
+    r(g_)     =  9.81;
+    r(e_)     =  0.7;
+    pos(0) = r(h_) > 0;
+}
+
+// called by fmiGetReal, fmiGetContinuousStates and fmiGetDerivatives
+fmiReal getReal(ModelInstance* comp, fmiValueReference vr){
+    switch (vr) {
+        case h_     : return r(h_);
+        case der_h_ : return r(v_);
+        case v_     : return r(v_);
+        case der_v_ : return r(der_v_);
+        case g_     : return r(g_);
+        case e_     : return r(e_);
+        default: return 0;
+    }
+}
+
+// called by fmiInitialize() after setting eventInfo to defaults
+// Used to set the first time event, if any.
+void initialize(ModelInstance* comp, fmiEventInfo* eventInfo) {
+    r(der_v_) = -r(g_);
+}
+
+// offset for event indicator, adds hysteresis and prevents z=0 at restart
+#define EPS_INDICATORS 1e-14
+
+fmiReal getEventIndicator(ModelInstance* comp, int z) {
+    switch (z) {
+        case 0 : return r(h_) + (pos(0) ? EPS_INDICATORS : -EPS_INDICATORS);
+        default: return 0;
+    }
+}
+
+// Used to set the next time event, if any.
+void eventUpdate(ModelInstance* comp, fmiEventInfo* eventInfo) {
+
+	eventInfo->iterationConverged = fmiTrue;
+	eventInfo->stateValueReferencesChanged = fmiFalse;
+	eventInfo->stateValuesChanged = fmiFalse;
+	eventInfo->terminateSimulation = fmiFalse;
+	eventInfo->upcomingTimeEvent = fmiFalse;
+
+	pos(0) = r(h_) > 0;
+	
+	if (!pos(0)) {
+
+		r(h_) = 0;
+		r(v_) = - r(e_) * r(v_);
+
+		// avoid fall-through effect. The ball will not jump high enough, so v and der_v is set to 0 at this surface impact.
+		if (r(v_) < 1e-3) {
+			r(der_v_) = 0;  // turn off gravity.
+		}
+
+		eventInfo->stateValuesChanged = fmiTrue;
+	}
+ }
+
+// include code that implements the FMI based on the above definitions
+#include "fmuTemplate.c"

+ 55 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/models/bouncingBall/index.html

@@ -0,0 +1,55 @@
+<html>
+<head>
+    <title>Documentation for bouncingBall.fmu</title>
+<style type="text/css">
+  html { font-family: Verdana, Arial, Helvetica, sans-serif; }
+  h1   { color: #000066; }
+</style>
+</head>
+<body>
+<h1>bouncingBall.fmu</h1>
+The bouncingBall implements the following equation: 
+<ul>
+<li> der(h) = v;
+<li> der(v) = -g;
+<li> when h<0 then v := -e* v
+</ul>
+with start values h=1, e=0.7, g = 9.81 and
+<ul>
+<li> h: height [m], used as state
+<li> v: velocity of ball [m/s], used as state
+<li> der(h): velocity of ball [m/s]
+<li> der(v): acceleration of ball [m/s2]
+<li> g: acceleration of gravity [m/s2], a parameter
+<li> e: a dimensionless parameter
+</ul>
+
+<br>
+<img src="plot_h.png">
+<br>
+The figure shows the solution computed with Silver 
+for height h of the ball for the start values given above.
+
+<p>
+The chain of events during simulation is as follows
+<ol>
+<li> initially h>0 and pos(0)=true </li>
+<li> continuous integration until a state event is detected, i.e.
+     until h + EPS_INDICATORS = 0.
+     At this time h < 0, the EPS_INDICATORS adds hysteresis.</li>
+<li> the simulator calls eventUpdate once which reverses the speed direction
+     v of the ball: v = -e * v, and sets pos(0)=false</li>
+<li> continuous integration until state event is detected, i.e.
+     until h - EPS_INDICATORS = 0.
+     At this time h > 0, the EPS_INDICATORS adds hysteresis.</li>
+<li> the simulator calls  eventUpdate once more which sets pos(0)=true.</li>
+<li> goto 2</li>
+</ol>
+The above description refers to the variables used 
+in file <code>bouncingBall.c</code>.
+
+<h2><a name="license">License conditions</a></h2>
+The FMU is provided by QTronic under the
+<a href="http://www.opensource.org/licenses/bsd-license.html">BSD License</a>.
+</body>
+</html>

BIN
examples/mass_spring_damper/fmusdk/fmu10/src/models/bouncingBall/model.png


+ 38 - 0
examples/mass_spring_damper/fmusdk/fmu10/src/models/bouncingBall/modelDescription_cs.xml

@@ -0,0 +1,38 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<fmiModelDescription
+  fmiVersion="1.0"
+  modelName="bouncingBall"
+  modelIdentifier="bouncingBall"
+  guid="{8c4e810f-3df3-4a00-8276-176fa3c9f003}"
+  numberOfContinuousStates="2"
+  numberOfEventIndicators="1">
+<ModelVariables>
+  <ScalarVariable name="h" valueReference="0" description="height, used as state">
+     <Real start="1" fixed="true"/>
+  </ScalarVariable>
+  <ScalarVariable name="der(h)" valueReference="1" description="velocity of ball">
+     <Real/>
+  </ScalarVariable> 
+  <ScalarVariable name="v" valueReference="2" description="velocity of ball, used as state">
+     <Real/>
+  </ScalarVariable>
+  <ScalarVariable name="der(v)" valueReference="3" description="acceleration of ball">
+     <Real/>
+  </ScalarVariable>
+  <ScalarVariable name="g" valueReference="4" description="acceleration of gravity"
+                  variability="parameter">
+     <Real start="9.81" fixed="true"/>
+  </ScalarVariable>
+  <ScalarVariable name="e" valueReference="5" description="dimensionless parameter"
+                  variability="parameter">
+     <Real start="0.7" fixed="true"/>
+  </ScalarVariable>
+</ModelVariables>
+<Implementation>
+  <CoSimulation_StandAlone>
+    <Capabilities
+      canHandleVariableCommunicationStepSize="true"
+      canHandleEvents="true"/>
+  </CoSimulation_StandAlone>
+</Implementation>
+</fmiModelDescription>