HOPSAN Classic User s Guide

User’s guide to Hopsan
An integrated simulation environment
Jonas Larsson
Department of Mechanical Engineering
Linköping University
S-581 83 Linköping, Sweden
20th August, 2002
User’s guide to Hopsan
Contents
1.
Installation ____________________________________________________________ 4
2.
Introduction ___________________________________________________________ 4
3.
Tutorials ______________________________________________________________ 4
3.1 Running a simulation _______________________________________________________ 4
3.2 Modelling a position controlled mass __________________________________________ 6
3.3 Steady-state characteristics __________________________________________________ 9
3.4 Frequency analysis ________________________________________________________ 11
3.5 Modelling a constant pressure hydraulic pump ________________________________ 14
3.6 Optimising the position servo _______________________________________________ 18
3.7 Co-simulation ____________________________________________________________ 20
3.7.1
3.7.2
3.7.3
Matlab co-simulation___________________________________________________________20
Excel co-simulation____________________________________________________________22
Visual Basic co-simulation ______________________________________________________23
3.8 More details on components ________________________________________________ 23
3.8.1
3.8.2
3.8.3
3.8.4
3.8.5
3.8.6
3.8.7
3.8.8
3.8.9
3.8.10
3.8.11
3.8.12
3.8.13
3.8.14
Handling Component Libraries ___________________________________________________23
Adding Components to a Library _________________________________________________24
Deleting and Re-ordering Components in Libraries ___________________________________25
Naming _____________________________________________________________________26
File Reference ________________________________________________________________26
Component- and Argument Types ________________________________________________26
Connectors and Picture _________________________________________________________26
Inserting Components into System Model __________________________________________27
Editing Components in System Model _____________________________________________28
Rotating Components __________________________________________________________29
Copying Components __________________________________________________________30
Changing pictures of components _________________________________________________30
View Source Code for Component ________________________________________________31
Creating new components out of pre-defined ones ____________________________________31
3.9 Using the command line interpreters and scripts _______________________________ 34
4.
Reference ____________________________________________________________ 34
4.1 Simulation _______________________________________________________________ 34
4.1.1
4.1.2
4.1.3
The simulation technique used in Hopsan ___________________________________________34
Communication between the applications ___________________________________________38
The Fortran component subroutines _______________________________________________39
4.2 Optimisation _____________________________________________________________ 41
4.2.1
4.2.2
4.2.3
What happens during an optimisation ______________________________________________42
Results from an optimisation_____________________________________________________42
Optimisation datafile (with a filename ending with ‘.ODAT’) ___________________________42
4.3 Interpreter_______________________________________________________________ 46
4.3.1
4.3.2
4.3.3
4.3.4
4.3.5
4.3.6
4.3.7
4.3.8
Command line ________________________________________________________________46
Variable types ________________________________________________________________47
Variable generations ___________________________________________________________48
Variable names _______________________________________________________________48
Introduction to built-in calculator _________________________________________________49
Operators in the built-in calculator ________________________________________________49
Precedence for operators ________________________________________________________50
Operands in expressions ________________________________________________________51
2(75)
User’s guide to Hopsan
4.3.9
4.3.10
4.3.11
Some rules for assignments ______________________________________________________51
Some hints and warnings________________________________________________________52
Calculations with complex numbers _______________________________________________52
4.4 Scripts __________________________________________________________________ 53
4.4.1
4.4.2
4.4.3
4.4.4
4.4.5
4.4.6
4.4.7
Comments ___________________________________________________________________53
Arguments to scripts ___________________________________________________________54
Flow control _________________________________________________________________54
I/O on screen and on file ________________________________________________________55
Debugging scripts _____________________________________________________________56
Ending execution of scripts ______________________________________________________56
Hints for writing scripts_________________________________________________________56
4.5 Hopsan commands ________________________________________________________ 56
4.5.1
Data input ___________________________________________________________________56
Maindata ___________________________________________________________________________57
Subdata ____________________________________________________________________________58
Log of changes in the datafiles __________________________________________________________59
4.5.2
Simulation, optimisation and frequency analysis _____________________________________60
Simulation (in the time domain) _________________________________________________________60
Optimisation ________________________________________________________________________60
Frequency analysis____________________________________________________________________60
4.5.3
Result handling _______________________________________________________________61
Other post processing _________________________________________________________________61
File operations _______________________________________________________________________61
Properties of result variables ____________________________________________________________63
4.5.4
Graphs ______________________________________________________________________63
Changing variables ___________________________________________________________________63
Changing limits ______________________________________________________________________63
Misc graph commands_________________________________________________________________64
Hardcopies__________________________________________________________________________64
4.5.5
Preferences __________________________________________________________________65
4.6 Co-simulation ____________________________________________________________ 66
5.
Appendix _____________________________________________________________ 68
5.1 License agreement for the Lcc-Win32 C-compiler ______________________________ 68
5.2 Node information _________________________________________________________ 69
Hydraulic ___________________________________________________________________________69
Pneumatic __________________________________________________________________________69
Mechanic linear 1-D __________________________________________________________________70
Mechanic Rotation 1-D ________________________________________________________________70
Electric_____________________________________________________________________________71
Electric AC _________________________________________________________________________71
Magnetic Nodes______________________________________________________________________72
Thermal ____________________________________________________________________________72
5.3 The C source code for HopSim.DLL _________________________________________ 73
3(75)
User’s guide to Hopsan
1.Installation
A password is needed for the installation and can be retrieved through the e-mail address
found on the homepage for Hopsan at http://hydra.ikp.liu.se. Click on the Hopsan download
link at this location and choose open the installation program directly by choosing ‘Open’ or
save it to disk and start it afterwards. Read the license agreement for Hopsan as well as for the
included C compiler and then give the password that you have received through e-mail. You
need to press ‘next’ twice after having entered the password. The input here is case sensitive.
Important: Install Hopsan to a folder that has a path containing no spaces or other special
characters. For information about enabling co-simulation between Hopsan and Matlab, read
ch. 3.7.
If Hopsan does not appear in your start menu, create a shortcut to
‘….\Gdynmoc\Gdynmoc.exe’ which is the main program. It could also be of value then to
make a shortcut to ‘….\HTML\Clib.html’ which is the help file for components.
Hopsan works on all Windows versions, but on Windows 9x/Me, the memory settings for the
batch file ‘MakeHop.bat’ in the ‘HopSim’ folder needs to be changed so that more memory is
allocated.
2.Introduction
Hopsan is a tool used for modelling and simulation of technical systems, mainly hydromechanical ones. It is fast, has support for optimisation and scripts and is accessible directly
through sockets or indirectly via DLL function calls. It is possible to create component models
in Fortran directly and use in Hopsan. This can however be difficult and the authors are
therefore developing tools that make this process easier. See our homepage for updated
information on this.
3. Tutorials
3.1 Running a simulation
Lets begin by executing GDynMoC (the modelling part of Hopsan) from the Hopsan part of
the Start menu as shown in Figure 1. The GDynMoc main window in Figure 2 should appear.
Choose ‘Plot Utility’ so that the application for plotting simulation results starts and is ready
for receiving data from any simulation.
4(75)
User’s guide to Hopsan
Figure 1. Windows start menu.
Figure 2. GDynMoC main window
In the HopsanPlotter window, minimise the ‘Command Window’ so that you will have
something like the left side contents of Figure 3. Later on, the simulation results will show in
the ‘Graphical Window’.
Figure 3. The plotting application.
Now open a model by choosing ‘Models\Open’ in the main GDynMoC window, doubleclicking the folder ‘PSpool_test’ and then double-clicking the file ‘PSpool_test.mod’. Choose
‘Simulation\Simulate’ in the GDynMoC model window and see how the simulation
application is created and run in a black window. If does not show and you are running
Windows 9x/Me, increase the available memory for the ‘…\HopSim\MakeHop.bat’ file by
right-clicking it and selection ‘Properties’ and then ‘Memory…’.
In the plotting application, choose ‘Dialogs\Plotvariables’, mark
‘X_MLOADC_2_NX2’
and
press
‘->Add->’,
mark
‘OUT_STEP_SUB_1’ and press ‘->Add->’, press ‘Plot’ and then
‘Close’. The right side contents of Figure 3 should show.
The variables shown are the reference position and the actual
position for the hydraulic valve-controlled position servo. The
display units are in mm. Now try and change the feedback gain in the component shown to the
right. Double-click the component and change the value for the parameter with name ‘Gain to
error’ (text in blue to the left). The initial value is 3e-3. Press ‘Ok’ and run another simulation.
The results in the plotting application are updated.
Now, let us vary the simulation settings. Choose ‘Settings\Simulation Parameters’ in the
model window. The time step is the most critical parameter in these settings, as you will see
later on. The start time can be negative so that the system can come to rest before the plotting
starts, the time scale is seldom used and the number of samples determines how many samples
are saved for each variable for later plotting. Since Hopsan calculates using a fixed time step,
the user needs to make sure that a small enough time step is used. A large time step results in
large error in simulation and vice versa. If the time step in this case is increased to 1e-1, the
results will look strange. Therefore always start with a large time step and then decrease it
through a number of simulations to make sure that smaller time steps don’t give different
5(75)
User’s guide to Hopsan
results. It is explained in more detail in ch. 4.1.1 how the time step affects simulation accuracy
in Hopsan.
3.2 Modelling a position controlled mass
The system modelled could for instance be part of a hydraulic press or be one of the
controlled pistons acting on a simulator cabin. The position of a piston is compared to a
reference position. The difference is magnified and is used to set the position of a valve spool
through which flow is directed into the piston's two chambers. On the following pages, the
system model will be built and eventually simulated and evaluated.
Start Hopsan as in ch 3.1. and make a new model by choosing ‘Models\New’ and then writing
‘MyServo’ in the dialog box that appears. Press ‘Ok’ and a blank model window appears. The
components needed are part of the libraries ‘Standard’, ‘Sense’, ‘Arithm’ and ‘Libf’. Open
each one of them using ‘Component Libraries\Load’. Now drag components into the model so
that something like the left part of Figure 4 appears.
Figure 4. A constant pressure hydraulic pump
The components needed are:
Library
‘Standard’
‘Arithm’
‘Sense’
‘Libf’
Components
‘PISTON’, ‘MLOADC’, ‘FCSRC’, ‘VALV43’, ‘PCSRC’
‘GAIN’, ‘SUB2’
‘XSENSE’
‘PULSs’
Components are rotated by marking one of them and then choosing ‘Edit\Rotate’. There are
shortcuts for most operations, in this case Ctrl+R could have been pressed instead, as
indicated in the ‘Edit’ menu. By placing the cursor over a component, a short info is given
about its purpose. Look at all components in that way to get an understanding of how this
model works. Save the model now, by choosing ‘File\Save Model’ in the model window.
Save regularly from now on.
Connect the components by pressing at one of the white small boxes (nodes) on one of them
and then on appropriate node on another component. Nodes that are possible to connect are
then marked in blue. Connect in reverse order if it doesn’t seem to work (e.g. between
XSENSE and MKLOAD). The connections can be done through a number of points by
pressing the left mouse button at each point. Right-click to undo the last line drawn. If a
connection has been done between two components it can be marked and then be deleted by
pressing ‘Del’. When creating connections as those between ‘XSENSE’ and ‘MLOADC’, it is
6(75)
User’s guide to Hopsan
useful to know that pressing Ctrl gives vertical lines and pressing Shift gives horizontal lines.
Also, if any line is not perfectly orthogonal, the points connecting two lines can be moved. If
such a point is dropped within a reasonable distance from where the two lines will be
orthogonal, then GDynMoC will make the lines orthogonal.
As you will notice, there are several kinds of nodes. If the mouse cursor is placed over a node,
the node type is shown in the lower part of the model window. The nodes can be connected as
shown below
From node type
‘OutputVariable’
‘HydraulicQNode’
‘MechanicQNode’
‘MechanicSenseNode’
To node type
‘InputVariable’ (to several)
‘HydraulicCNode’ and vice versa
‘MechanicCNode’ and vice versa
‘MechanicQNode’
Every second “physical” component needs to have only Q-type nodes and the other “physical”
components need to have only C-type nodes. This has to do with the way Hopsan performs
simulations, as described in ch. 4.1.1. The ‘physical’ nodes must not be left unconnected.
‘OutputVariable’ type nodes that are not connected is no problem. If a node of type
‘InputVariable’ is left unconnected, the corresponding parameter value specified in the
component is used for the variable. This is e.g. the case for the ‘FCSRC’ where the size of the
force could have been input from the right, but where the parameter value is used instead
since it is not connected in that node.
If you have finished the connections, some parameter values now need to be set to get the
correct model. Double-click on the component you want to change the parameter in and look
at the blue text on the right. It tells you some information on each parameter, output variable
and node. Do the changes shown below where the components are stated from left to right in
the model
Component Parameter
‘GAIN’
‘Multiplier’
‘GAIN’
‘Multiplier’
‘PCSRC’
‘Pressure [Pa]’
‘PISTON’
‘Constants\Piston area 1 [m2]’
‘PISTON’
‘Constants\Piston area 2 [m2]’
‘MLOADC’ ‘Coulomb friction force [N]’
‘FCSRC’
‘Force [N]’
New value
0.2
3e-2
150e+5
5e-3
2.5e-3
0.0
1e+4
According to the parameter values, the reference signal is a pulse that starts at 1.0 s and ends
at 2.0 s with an amplitude of 0.20 m. The error gain in the position feedback loop is 3e-2 and
gravity is applied to the mass due to the force of 1e+4 N. The supply pressure is 150e+5 Pa,
150 Bar or 15 MPa if you like.
If the HopsanPlotter application is not running, choose ‘Plot Utility’ in the GdynMoC main
window. Then choose ‘Simulation\Simulate’ in the model window. A simulation is
performed. Now, we will plot the reference position and the actual position on the left axis of
the graph. To find out the names of the variables, place the mouse cursor over the interesting
nodes and look at the comments. The reference position variable is found be looking at the
right node of the left ‘GAIN’ and the actual position is in the lower node of the ‘XSENSE’.
Choose ‘Dialogs\Plotvariables’ in the HopsanPlotter application and add the variables to the
7(75)
User’s guide to Hopsan
plot list by choosing ‘->Add->’. Press ‘Plot’ when both variables have been transferred and
then ‘Close’ to look at the results. Something like Figure 5 should show.
Figure 5. Reference and actual position shown for the
model
Figure 6. Valve dynamics introduced using filter.
If an error occurs, it is probably located in one of the Fortran files referenced to in the system
model. If the compiler needs files that are not part of the system model, references to them can
be placed in GDynMoC.ini in the GDynMoC directory. In this file there is a label
"FortranFiles". Place the whole path for your missing files here, one for each row, e.g. like in
Figure 7. In this case, MySqrt.for will be compiled and linked into the Hopsan program, even
though the mentioned Fortran file doesn't necessarily contain any subroutine with an interface
to GDynMoC.
Figure 7. Adding references to files to be compiled in the Hopsan simulation program.
To refine the model, the direction valve can be given some dynamics. The ‘VALV43’ can be
replaced by ‘SERVAL’ from the ‘Standard’ library. ‘SERVAL’ contains dynamics of 2:nd
order, i.e. it is not infinitely fast and fast movements are damped out. Between the right
‘GAIN’ and the ‘VALV43’ a filter can be placed to introduce dynamics. In the ‘Filter’ library,
the components ‘LP1s’ and ‘LP2s’ are suitable for this. ‘LP1s’ is a low-pass filter that models
pure “slowness”. Input signals that vary faster than a certain frequency will then not yield
much change in position of the valve. ‘LP2s’ is dynamics of 2:nd order and acts like a massspring system. In it, the break frequency corresponds to the stiffness of the spring and the
damping corresponds to the damper effect. With one of the filters made part of the model, the
model will look like Figure 6. The frequencies are entered in rad/s which is the frequency in
Hz multiplied by 2*pi which is about 6.28.
There is no spring acting on the mass. It that would be needed, it can be done in two different
ways, as shown in Figure 8. The ‘XSENSE’ component can be used to measure the position
of the mass, a ‘GAIN’ is used to multiply with the spring stiffness and the force value is fed
back into a ‘FCSRC’ acting on the mass. The other way is to connect a ‘SPRING’ directly to
8(75)
User’s guide to Hopsan
the mass and a ‘VSRC’ on the right end with a zero value to indicate that the right end of the
spring is standing still. The advantage of the latter approach is that it is more numerically
stable. The first approach is however more flexible, since the force can be treated arbitrarily,
e.g. using user-made components in the loop. The force could then e.g. be activated at a
certain location to model a spring that acts as an end stop.
Positions, velocities, flows etc are measured out from the Q-type components. For the mass
e.g., the right position measured by the ‘XSENSE’ component is positive when the mass has
moved to the right. If we had measured on the left side of the mass, the value would have
become negative during simulation. The mentioned variables are only output from the Q-type
components since it is them that are calculating these.
Figure 8. Two ways of modeling a spring acting on the mass.
3.3 Steady-state characteristics
It is often of interest to study the steady-state characteristics of a system. Here, we will look at
the position error as a function of external force in the ‘MyServo’ model. In order to
investigate this the force can be varied as a soft step. A quarter of a sine wave is very suitable
since it excites a minimum of higher frequencies. By keeping the reference position at a
constant level and varying the force as a soft step, the steady-state characteristic can be plotted
by placing the force on the x-axis in the graph and the piston position on the y-axis.
Modify the ‘MyServo’ model so that it looks like Figure 9. The sinusoidal step is called
‘SINF’ and is found in the library ‘Libf’. Set the parameters as follows in the components
from the left to the right:
Component
‘SUB2’
‘SUB2’
‘GAIN’
‘SINFs’
Parameter
‘Input’
‘Subtractor’
‘Multiplier’
‘Start time of step [s]’
‘Time when step is finished [s]’
9(75)
New value
0.2
100e+3
200e+3
0
50
User’s guide to Hopsan
Figure 9. MyServo prepared for steady-state analysis
Figure 10. Actual position as a function of load
So, the reference position is 0.2 m. To make the simulation go faster, we will set the start
position for ‘MLOADC’ to be just that. Double-click ‘MLOADC’, then double-click the plus
sign in the third column for ‘Load end 2’. Here, all plot-variables for that node are shown.
Each one has a start value and a scaling. Set the start value for ‘Position’ to be 0.2. The scale
is 1000 so this means that if this variable (X_MLOADC_1_NX2) is plotted, it will be shown
in mm instead of meters. Press ‘OK’. Set the simulation end time to 50, save the model and
then run a simulation. As always, make sure the HopsanPlotter application is running. Go to
‘Dialogs\Plotvariables’ in the plotting application and add the position of the mass to the left
axis and the force acting on the right end of the mass on the x-axis. You find the names of
these variables by placing the cursor over the right mechanical node of ‘MLOADC’. The
position could also have been taken from the ‘XSENSE’ component and the force from the
right ‘SUB2’ component. Plot the variables by choosing ‘Plot’ and then ‘Close’. Go to
‘Dialogs\Diagram Limits’ now to add some grid. Change ‘Num Div’ for the x-axis to 4 and
enable ‘Grid’ for the x-axis and left y-axis. Press ‘Apply’ and then ‘close’. Something like
Figure 10 should appear. As you understand, the curves should be vertical lines at static
conditions. If the simulation time is increased as well as the end time of the sinusoidal step,
the curves will become more vertical. It is the different piston areas that cause the nonsymmetry in the graph.
Now we will decrease the supply pressure to 100 Bar and see what happens. Change ‘Pressure
[Pa]’ in the left ‘PCSRC’ to 100e+5. Run a simulation. Choose ‘Dialogs\Plotvariables’ and
enter ‘*.*’ in the ‘Name Filter’ area. Do not press return but rather ‘Update List’ and you will
see plot-variables from old simulations. The expression ‘*.L’ meant that only the last
generation of variables was shown. Add the position from the simulation before the last one to
the left axis, press ‘Plot’ and then ‘Close’. The result might look like Figure 11.
In the ‘Diagram limits’ dialog box it is also possible to zoom on the time axis and the two yaxes, set the number of figures on the axes (‘Num Div’) and making changes permanent by
selecting ‘Locked Limits’. The number of decimals can also be set where ‘-1’ means
automatic choice. The changes are as in the plotvariable dialogue done for a certain graph
since there can be several graph windows in the plotting application at the same time. They
are updated by choosing ‘Diagram\Update all graphs’.
Sometimes it is good to be able to insert graphs into documents. Let us do that with the graph
in Figure 11. Choose ‘File\Export EPSF file’ or ‘File\Export POSTSCRIPT file’. Enter
something like the contents of Figure 13 and press ‘OK’. The picture can be printed on a
10(75)
User’s guide to Hopsan
Postscript printer from e.g. Word or can be edited in drawing tools. Figure 12 shows an edited
graph file.
Actual position with 100 and 150 Bar supply pressure
1.00
0.80
0.60
0.40
0.20
0.00
5
-1.00x10
-5.00x10
4
0.00
5.00x10
4
1.00x10
5
Time [s]
Figure 11. Results from different simulations
Figure 12. An edited graph file
Figure 13. Exporting a graph.
3.4 Frequency analysis
Hopsan can perform frequency analysis on simulation results. The frequency analysis is
carried out using the FFT-algorithm (Fast Fourier Transform). This makes it possible to
extract transfer functions from simulation results. HOPSAN also has the possibility to plot
transfer functions directly.
Let us suppose that we have a linear system
Y (iw ) = G (iw ) X (iw )
where G(iw) is the transfer function, Y(iw) is the Fourier transformed output signal and X(iw)
is the Fourier transformed input signal, w is the frequency in rad/s and i is the square root of
–1. If the FFT algorithm is used for the transformation, the transfer function can be calculated
as
G (iw ) =
FFT (Y (iw ))
FFT ( X (iw ))
The Fourier transformation requires the signals to be analysed to fulfil certain conditions. The
first criterion is that they should have the same value at the beginning as at the end of the
11(75)
User’s guide to Hopsan
simulation. Secondly, the transient must have died out when the simulation ends. A suitable
input signal is therefore a step with an exponential decay. For this, the component ‘EXPFs’
can be used from the ‘Libf’ library. The time constant for the decay in this component should
be about 1% of the simulation time. When a frequency analysis is performed it is important to
realise that the transfer function concept is valid only for linear systems. All hydraulic
systems, however, are non-linear to some degree. In order to avoid non-linearity, it is
important to use only small input signals to the system. It is also advisable to remove known
non-linearities, such as dead band in valves, etc. that otherwise will make small signals very
non-linear.The amplitude of the pulse should however large enough to excite the system.
Another demand is that the number of samples should be 2n where n is an integer, e.g. 1024
samples.
Modify the ‘MyServo’ original model so that it looks like Figure 14. Set the parameters as
follows in the components from the left to the right and set the simulation start time to -1 s
and end time to 3 s. The negative start time is necessary for the position error to start at zero at
plot start time. This has to do with the fact that Hopsan does not resolve algebraic loops. Set
the start position for the load to 0.25 m, as done in ch 3.3.. Run a simulation and plot the
reference value as well as the actual position. The reference variable is found in the right node
of the first ‘SUM2’ from the left in the model. The actual position variable can be seen in the
lower node of the ‘XSENSE’ component. The feedback gain has been lowered since the
original servo was a bit unstable and since no transients should appear at the end of
simulation. Something like Figure 15 should appear.
Component Parameter
‘EXPFs’
‘Time when the step will occur [s]’
‘Time constant of decay [s]’
‘GAIN’
‘Multiplier’
‘SUM2’
‘Input’ (second)
‘GAIN’
‘Multiplier’
‘PISTON’
‘Equivalent load mass [kg]’
‘Dead volume in chamber 1 [m3]’
‘Dead volume in chamber 2 [m3]’
‘Constants\Piston area 1[m2]’
‘Constants\Piston area 2[m2]’
‘Stroke [m]’
‘Leakage coefficient ..’
‘Viscous friction coefficient..’
‘MLOADC’ ‘Mass [kg]’
‘Viscous friction coefficient ..’
‘Upper limit on stroke …’
‘FCSRC’
‘Force [N]’
12(75)
New value
0.1
0.03
1e-3
0.25
3e-3
500
0
0
0.58e-3
0.58e-3
0.5
1e-12
0
500
0
0.5
0
User’s guide to Hopsan
Figure 14. MyServo prepared for frequency analysis
Figure 15. Time-domain simulation results
When a simulation has been performed the transfer function can be obtained by using the
command ”Calculations\Transfer Function Analysis”. Make the command window larger so
that you can start enter some information in it. You are now requested to specify input and
output variable and a variable name that will be assigned to the transfer function. We will start
of with the open loop transfer function. The input variable is then the position error. Find it in
the model window by placing the mouse cursor over the right node of the ‘SUB2’ component.
The output variable is the actual position of the mass. Find it by placing the mouse cursor over
the lower node of the ‘XSENSE’ component. Give the result variable the name ‘GO’. Also
create the closed loop transfer function by using the position reference value as input variable,
the actual position as output and give the result variable the name ‘GC’.
The result variables here cannot be plotted directly in a time-based diagram since the variables
are functions of frequency and contain both a real and an imaginary part. These results can be
plotted in either Bode or Nyquist diagrams instead. Choose ‘Diagram\Bode Diagram’ and
enter ‘GO’ in the command window and then ‘GC’. Then press return to finish the command.
The results should look like Figure 16. If they don’t, plot your input and output variables and
see if they start and end at the same values, don't oscillate at the end and are not too large in
amplitude. The scale on the x-axis is in Hz (not rad/s!), on the left y-axis it is dimensionless
(not dB) and on the right y-axis it is in degrees.
Amplitude of open TF
closed TF
Phase of open TF
Figure 16. Bode diagram of opened and closed
transfer function for position servo
Figure 17. Nyquist diagram of open transfer function
13(75)
User’s guide to Hopsan
By plotting a Nyquist diagram, the imaginary part of the transfer function is plotted against
the real part, as in Figure 17.
The highest frequency that is calculated is determined by the time step while the lowest
frequency is determined by the total simulation time. The highest frequency the FFT
algorithm can work with is determined by the Nyquist frequency which is 1/2T Hz where T is
the time step. In this case where T=0.001, the highest frequency is therefore 500 Hz.
It should be pointed out that the estimate of transfer functions for higher frequencies are still
unreliable. This owes to two things. Firstly, the input spectra usually contains more energy in
the lower part of the spectra, and secondly, non-linearities will scatter the input spectra and
produce higher harmonics that will be found as irregularities in the higher part of the spectra.
3.5 Modelling a constant pressure hydraulic pump
To get a feeling on how basic components can be used to build up hydro-mechanical
controllers in Hopsan, a common kind of hydraulic pump is modelled in this chapter. The
pump shown in Figure 18 is a vane pump. When rotating clock-wise in the figure, the oil is
transported between the vanes from the inlet to the left to the outlet. The pump rotates at a
constant speed in this example. The flow is varied by moving the rotating axis from the centre
point and downwards where the flow is at its maximum. At the centre, an equal flow goes
from inlet to outlet as goes from outlet to inlet, resulting in no total flow. A controller is used
to vary the flow of the pump so that the pressure at the outlet is constant. If the force of the
outlet pressure pp exceeds the spring pretension set in the direction control valve, the spool in
that valve will move to the right and flow will enter the piston. The pressure pc then increases
and makes the piston move upward as well as the rotating axis of the pump. The pump flow
decreases as well as the pressure pp since the pressure through the flow control valve is
proportional to the flow through it. The spool of the direction control valve will then oscillate
round the present position to adjust the pressure pp continuously.
Variable pump
Flow control valve
pp
pL
qp
Piston
pC
Direction
control valve
Figure 18. A constant pressure hydraulic pump
In Figure 19, the model is shown that is supposed to behave like a constant-pressure pump.
Let us create it! First, create a new empty model by choosing ‘Models\New’ in the GdynMoC
main window. Now write ‘PCPump’ in the ‘Project Name’ square and press ‘OK’. An empty
14(75)
User’s guide to Hopsan
model should appear. Now, the components needed are to be dragged into the model from the
various component libraries available. Open the main component library by choosing
‘Component Libraries\Load’ in the GdynMoC main window and double-clicking on
‘Standard.des’. A number of components are shown in a Window named ‘Standard’. Drag
five ‘PCSRC’ into the model and drop them their at appropriate locations. Also drag two
‘ORIFIT’ and one of each following: ‘VPUMP’, ‘VOLUME’, ‘SIGGEN’, ‘FCSRC’,
‘MKLOAD’, ‘PISTON’, ‘VALV33’ and ‘PACT’. Rotate the components by marking a
component and then pressing Ctrl+R.
Figure 19. Model of a constant pressure hydraulic pump
Most components are now in place. The ones missing can be found in the following
component libraries:
Library
‘Arithm’
‘Sense’
‘Sources’
Components
‘GAIN’, ‘SUB2’, ‘DIV2’
‘XSENSE’
‘CONST’
Save the model by choosing ‘File\Save Model’ and do that regularly from now on. Any
unwanted components can be deleted from the model by marking one of them and pressing
‘Del’. Now connect the components as shown in ch 3.2. It is the middle node of the upper left
‘PCSRC’ that is to be connected to the ‘VPUMP’.
If you have made it to the right part of Figure 19, it is now time to set the parameter values of
the model. From the left to the right the following changes need to be made:
Component Parameter
‘CONST’
‘Constant [-]’
‘MKLOAD’ ‘Mass [kg]’
‘Spring stiffness [N/m]’
‘Upper limit of stroke.. [m]’
‘PISTON’
‘Equivalent load mass [kg]’
‘Dead volume in chamber 1 [m3]’
‘Dead volume in chamber 2 [m3]’
‘Constants\Piston area 1 [m2]’
‘Constants\Piston area 2 [m2]’
15(75)
New value
50e-3
1
10000
50e-3
1
1e-5
1e-5
1e-3
5e-4
User’s guide to Hopsan
‘ORIFIT’
‘PACT’
‘SIGGEN’
‘Stroke [m]’
‘Restrictor coefficient ..’
‘Stiffness [Pa/m]’
‘Initial spring force [Pa]’
‘Time constant [s/rad]’
‘Lower limit on position [m]’
‘Upper limit on position [m]’
‘Constants\Basevalue for output’
‘Constants\Amplitude for ramp’
‘Constants\Starttime for ramp’
‘Constants\Stoptime for ramp’
‘Constants\Use RAMP…’
50e-3
25e-8
200e+6
200e+5
1e-2
-2.5e-3
2.5e-3
10e-8
5e-8
0.2
0.2
1
In order to change the parameters named ‘Constants\…’, double-click the minus or plus-sign
in the third column next to the name ‘Constants’ in the component dialog box to close or open
that section of the parameter list. Finally, the simulation parameters are set as in Figure 20 by
choosing ‘Settings\Simulation Parameters’ in the model window.
Figure 20. Simulation settings for the pump model.
Figure 21. Simulation results for the pump model.
Now, make sure that the HopsanPlotter application is running. If it is not on the screen, then
press ‘Plot Utility’ on the GdynMoC main window. Run a simulation using
‘Simulation\Simulate’ in the model window. This time, the simulation will last for a while.
Now, we’ll plot the pressure of the pump outlet on the left side of the graph and the
displacement of the pump on the right side. To get the name of the appropriate variables,
place the mouse cursor over the interesting nodes to see the names appear. In this case, place
the mouse cursor over the left node of the ‘ORIFIT’ connected to the ‘VOLUME’. Find the
name of the pressure variable and add that to the list in the HopsanPlotter application. Do the
latter by choosing ‘Dialogs\Plotvariables’, marking the correct variable and press ‘->Add->’
and then ‘Plot’ to save the changes. The displacement we are to plot is the relative one with a
value between –1 (negative flow) and 1 (maximum, positive flow). Place the cursor over the
upper node of the ‘GAIN’ component close to the ‘VPUMP’. Add this variable to the list but
press ‘Right Axis’ first to put it on the right hand side of the graph. After having pressed
‘Plot’ and ‘Close’, something like Figure 21 should show. The pressure is about 20 MPa,
16(75)
User’s guide to Hopsan
which is correct and it drops momentarily when the flow control valve is opened more at 0.20
s. At that time, the displacement is increased by the controller and the pressure thus rises
again to its reference value. Do the same simulation with a smaller time step: 1e-6, and you
will see that the results changes a bit, as explained in ch 3.1.
The pressure controlled direction control valve can be modelled in several ways. The ‘PACT’
component low-pass filters the pressures that acts on it as set by the ‘Time constant of spool’
parameter. The resulting difference pressure acts on the spring to give a position that can be
sent to a valve such as the ‘VALV33’. The ‘PACT’ component cannot be damped, therefore
‘PISTM1’ or ‘PISTON’ can be used if that is needed.
Figure 22. The direction control valve modelled in two ways.
When using ‘PISTM1’ or ‘PISTON’, the position needs to be measured by ‘XSENSE’ to get
from the physical node to the variable type node of ‘VALV33’. The position of ‘PISTM1’ and
‘PISTON’ cannot be negative, which is needed for the valve. Therefore, half of the stroke
length is subtracted from the measured position. ‘PISTM1’ is a Q-type component and can
therefore as ‘PACT’ be connected directly to ‘VOLUME’, which is a C-type component.
‘PISTON’, however, is a C-type component and needs an ‘ORIFIT’ in between and is
connected to a ‘PSRC’ instead of a ‘PCSRC’ on the upper node. ‘PISTM1’ neglects the spring
effect of the chamber volumes as also ‘PACT’ does. ‘PISTON’ takes this into account.
Damping can in ‘PISTM1’ be introduced by increasing any of the viscous friction or leakage
coefficients. ‘PISTON’ also contains these parameters, but the outside ‘ORIFIT’ also
contributes to the damping effect. ‘PISTM1’ as well as ‘PISTON’ in combination with any
mass model takes the mass inertia into account in contrast to ‘PACT’.
17(75)
User’s guide to Hopsan
3.6 Optimising the position servo
Hopsan is a powerful tool for optimising systems. In the optimisation procedure, Hopsan
minimises an object function by varying a number of chosen parameters. If the object function
is complicated, a script file can be used to calculate it. Scripts are explained in ch. 4.4.
In this case, we'll vary the position error gain and the two restricting areas in the valve in the
model ‘MyServo’ from ch. 3.2 in order to minimise energy consumption and position error.
First save the old model to a new with another name, e.g. MyServoOptim. The object function
is to be minimised and is therefore negated. The integrated absolute position error and the
supplied energy to the piston through the valve (integral of the product of flow and pressure)
are calculated as in Figure 23.
Figure 23. MyServo extended with object function.
The ‘PULSs’ component in the lower left is used so that just a chosen part of the loading
cycle is affecting the object function when it concerns position error. Set ‘Time when the
pulse begins ..’ in that ‘PULSs’ to 0.5 s and ‘Time when pulse ends ..’ to 2 s. This means that
the position error part of the object function will not increase after the reference pulse. Notice
that the two terms of the object functions can be normalised and weighted using the two
‘CONST’ components. In this manner, the user can e.g. set the importance of low energy
consumption compared to precise positioning of the piston, but most importantly the two
terms will be of about the same size and therefore none of them will be neglected.
Set ‘Multiplier’ in the ‘GAIN’ placed to the right of ‘QSENSE’ to -1 (flow from lower left
node on ‘VALV43’ is negative when passing from high pressure source to piston).
Rename the ‘Output’ variable from ‘OUT..’ found in the ‘Alias’ column in the right ‘DIV2’
component to ‘ENERGY’ (see Figure 24). Also change the alias of the ‘Output’ variable of
the left ‘DIV2’ to ‘POSERROR’. In the same way, rename the ‘Output’ variable in ‘SUM2’ to
‘OBJFUNCTION’ and the variable ‘Measured position..’ in ‘XSENSE’ to POSITION. The
alias is what is used internally in Hopsan and is the name that is displayed in the
18(75)
User’s guide to Hopsan
HopsanPlotter application. These names need to be unique, at least for output variables. If the
names of two input variables are the same, they will make use of the same parameter value.
Figure 24. Renaming a variable.
Run a simulation. Plot ENERGY and POSERROR on separate axes as in Figure 25. They are
now of very different sizes. Let us normalise them by dividing them by their final values. Set
the ‘Constant’ parameter in the left ‘CONST’ to 2.25e-2 and the ‘Constant’ parameter in the
right ‘CONST’ to 23e+3. Save the model. Then run a new simulation and make sure the two
terms have about the same size.
Figure 25. Object function terms that haven't been
normalised
Figure 26. An optimisation description.
Now there exists a goal function for Hopsan to minimise. To define which parameters are to
be varied, a ODAT file needs to be created. Choose ‘Simulation\Optimisation\Define
Optimisation’. Edit the file so that it looks Figure 26. Choose ‘File\Save’ in the opened
window to save your changes. ‘K_GAIN_1’ is the alias of the parameter ‘Multiplier’ in the
‘GAIN’ to the left of the ‘VALV43’ component. In your model, the alias could have a slightly
different name, e.g. ‘K_GAIN_2’. The ‘@’ sign in the other parameters referred to means that
the parameter ‘FRAP’ e.g. is part of the parameter section ‘FILENAME_VALV43_1’. These
sections can be shared among components if they use the same name and the parameters part
of them can only be used as constants, not as input variables. More information about defining
optimisation can be found in ch. 4.2.
19(75)
User’s guide to Hopsan
Now, run the optimisation by choosing ‘Simulation\Optimise’. A number of simulations are
carried out while the parameters are varied. After a while, the window stops to scroll. The
optimised parameter values are shown a number of lines upward. To be able to see them, you
need to set screen buffer height for the HopSim.exe window by right-clicking on it, choosing
‘Properties’ and then ‘Layout’ and finally ‘Screen buffer size’. There you set a value of 900
and accept the changes for future windows with the same name. Press return twice when you
want to get out of the command window. Plot POSITION and you will se that it looks quite
nice. Maybe the results aren't exactly like those in Figure 27, but that is because the
optimisation algorithm cannot guarantee that the global optimum is found. Notice that the
optimisation did not care about following the reference after 2 s and there concentrated on
getting an energy-efficient ending. There is more to read about optimisation in ch 4.2.
Figure 27. The optimised servo
3.7 Co-simulation
Sometimes, one simulation tool is not enough and therefore Hopsan has the possibility to
communicate with other tools during simulation. This can be used in a number of ways, one
of them is co-simulation. In co-simulation the different tools co-operate in simulating a model
that is split among the tools. We will in this chapter look at how Matlab/Simulink, Excel and
Visual Basic applications can be made co-operate with Hopsan.
3.7.1 Matlab co-simulation
Load the ‘MyServo’ model that was createn in ch. 3.2. We will now use it towards both
Matlab and Visual Basic. To help the other tools in knowing something about the inputs and
outputs from the model, Hopsan writes information about this to a number of files in the
HopSim folder. The inputs and outputs used are the nodes that are not connected in the model
and are of type ‘InputVariable’ or ‘OutputVariable’. In this case we want to read the spool
position from the outside tool and give back the measured position. Therefore change the
model and save it with a new name so that it looks like Figure 28. The variable nodes on
‘FCSRC’ and the two ‘PCSRC’:s have been hidden. To do this, double-click e.g. ‘FCSRC’,
choose ‘Connectors and Picture’ and drag the right node to the upper left (Figure 29). Then
press ‘OK’ in the two opened windows.
20(75)
User’s guide to Hopsan
Figure 28. ‘MyServo’ prepared for co-simulation
Figure 29. The hidden variable node of ‘FCSRC’
If this has not been done before , copy the files found in ‘..\Interfacing\Matlab’ to the ‘Work’
folder of your Matlab installation. There, run the MakeDLL.bat file. If it does not work, set up
the mex command through running “mex –setup” on the command prompt and choose the
“LCC C …” compiler.
Start Matlab and write ‘hopsan_sys’. You will get an error message saying that the Hopsan
path need to be set. Open ‘Hopsan_sys.m’ and enter the correct path to the HopSim folder.
Save the file and then write ‘hopsan_sys’ again. The window in Figure 30 should appear.
Figure 30. The created Simulink S-block.
Figure 31. The finished model.
Never over-write this Simulink model, since it is used every time this command is given.
Instead, save it now as ‘Test’. Then, always remove the red S-function. Add some blocks from
the ‘View\Show Library Browser’ menu so that the model becomes the one in Figure 31.
Change the gain to 1.5e-2, the initial value of the step to 0.5 and the final value of step to 0.6.
Save the model.
Double click on hopsan_sub and specify a communication interval of 5e-3 s and a Hopsan
time step of 1e-3 s. Ignore the rest of the settings which you seldom need to bother about. The
start values of the output variables are useful sometimes. The communication interval means
that Hopsan will iterate five times for each call. Double click on the scope to make it visible
and change the simulation end time to 2 s by choosing ‘Simulation\Simulation Parameters’ in
the Matlab model window.
21(75)
User’s guide to Hopsan
Before you start the simulation, choose ‘Simulation\Co-Simulate’ in the Hopsan model
window. The Hopsan application must be running before any other tool tries to communicate
with it, otherwise the other tool will wait forever. Something like Figure 32 should show.
Then start the Matlab simulation and see if the results look like Figure 33.
Figure 32. Hopsan is waiting for commands.
Figure 33. The simulation results.
3.7.2 Excel co-simulation
Load the ‘PMServo’ model and choose ‘Simulation\Co-Simulate’. Open ‘Hopsan.xls’ in the
‘Interfacing\Excel’ folder into Excel. Answer ‘yes’ to enable macros. Press on the ‘Start
simulation’ button. The contents of you Excel sheet should be as in Figure 34 and the Hopsan
window should look something like Figure 35.
Figure 34. The Co-simulation Excel sheet
Figure 35. The Hopsan application after co-simulation
initiation
In the B1 cell in the sheet, enter a value and press return. The value is sent to Hopsan that
takes one simulation step of 0.01 s length. Press F2 and press return on the same cell
repeatedly to make the simulation move forward. See how the value returned from Hopsan
changes. The value that is given in B1 is the reference position for the servo and the value
returned is the actual position. To study the programming, choose ‘Tools\Macro\Visual Basic
Editor’.
This simple example shows that most windows programs can communicate with Hopsan, at
least indirectly trough e.g. Excel since the value of B1 could have been updated by another
tool. The value of B1 could also have been a Hopsan command and D4 the returned string,
thereby making Excel a general portal to Hopsan.
22(75)
User’s guide to Hopsan
3.7.3 Visual Basic co-simulation
There exists a Visual Basic project similar to the Excel VB script in ‘Interfacing\Visual
Basic’. Start the ‘PMServo’ model first. Run the Visual Basic project, press ‘Start
Simulation’, move the reference slider and see how the actual position is changed in real-time.
If this application as well as the Excel one had read the information found in the HopSim
folder about inputs and outputs (files ending with ‘.INT’), they would have been useful for
any model. This is easy to achieve.
3.8 More details on components
3.8.1 Handling Component Libraries
There are a number of pre-defined libraries containing models of the most commonly used
hydraulic-, control- and mechanical components. From here on, component means component
model. More information about the component libraries Filter, Standard and Sources can be
obtained in Component Help in the Hopsan part of the Start-menu. If this menu choice doesn’t
exist on your computer, make a shortcut to \Hopsan\HTML\Clib.html instead. Loading predefined libraries is done by selecting ‘Component Libraries\Load’ from the GDynMoC main
window. In the dialog that appears, all component libraries in the folder chosen are shown, as
in Figure 36.
Figure 36. Loading component libraries.
Component libraries can be placed arbitrarily in your file system and GDynMoC remembers
which folder in the system you used the last time. Here follows a list of the pre-defined
libraries and there use.
Arithm
Filter
Libf
Sense
Sources
Standard
Arithmetical operators for subtraction, division and more.
Transfer functions like e.g. low-pass filters
Signal sources and functions for creating dead-bands and more.
At times, measurements of mechanical and hydraulic properties are
useful, for instance in control systems. With these components,
variables are created out of mechanical and hydraulic nodes. These
output variables created can then be connected to any other
components containing nodes of type input variables.
Signal sources, but also sources of force, speed, pressure and flow.
Most commonly used components, such as hydraulic, mechanical and
a few control and signal components.
23(75)
User’s guide to Hopsan
3.8.2 Adding Components to a Library
Components are black boxes receiving input from other components and returning
information to them. The components are shown as icons that resemble the real components.
The components in GDynMoC contain parameters, some nodes for connection purposes, a
reference to the picture and a reference to a file containing its motor; a Fortran subroutine.
One such file is Dorifit.for, shown in Figure 37. It makes a call to another subroutine named
Orifit that calculates flow through a sharp-edged orifice given a flow coefficent. The
subroutine DOrifit simply calculates the latter coefficent from a given orifice diameter. A
detail that makes it possible to make a GDynMoC component out of this file are the
comments
that
begin
with
BeginInterfaceDeclarations
and
ends
with
EndInterfaceDeclarations. These comments form the interface to GDynMoC and defines how
the variables in the argument list are to be treated. In this case the component has two
hydraulic nodes - N1 and N2 - that can be connected to other components. It has also got two
variable nodes that define the orifice diameter and the oil density. More information on how
to write Fortran subroutines for Hopsan can be found in ch. 4.1.3.
Figure 37. Fortran file for DOrifit.
Load component library Standard, choose ‘File\Save As’ and write ‘MyOwn’ to make your
own copy of the library. Never use spaces in file or folder names in GDynmoc. You are now
to add the component described above. Choose ‘Edit\Add components’ in library ‘MyOwn’ or
press Shift+Ins. The dialog in Figure 38 appears. Select ‘Dorifit’ and choose Open.
24(75)
User’s guide to Hopsan
Figure 38. Adding components to a library.
The new component is positioned at the lower left corner of the library window as in Figure
39. The icon is exactly the same as for component Orifit. Why? GDynMoC looks in a
directory called Pictures, situated under the GDynMoC directory, for a Windows Meta File
(WMF) with the same name as the component. In this case the picture of the original Orifit
has already been copied from Orifit.wmf to DOrifit.wmf in the Pictures directory. Choose
‘File\Save’ in the library's menu for saving ‘MyOwn’.
Figure 39. Component library MyOwn with added component DOrifit
It is now possible to use the new component. There is just a little error that can be fixed
according to ch. 3.8.7. The error is that the connectors aren't properly positioned. Before that,
let's have a look at the features of re-ordering and deleting components in the library.
3.8.3 Deleting and Re-ordering Components in Libraries
Suppose we don't want to keep the ‘Ackum’ (an ackumulator) in the library ‘MyOwn’. Place
the mouse cursor over the picture for the component, left-click and press Del. It is also
possible to choose ‘Edit\Delete marked’ component instead of pressing Del. Lets say that
library ‘MyOwn’ is now saved, but you've regreted the changes made. The ‘Ackum’ can then
in this case be transfered from library ‘Standard’. Lets try this. Load ‘Standard’ and drag
‘Ackum’ from ‘Standard’ to an empty space in ‘MyOwn’ (either at the end of a row or
between two components). The component is then placed at the cursor in the ‘MyOwn’
library. Components can be re-ordered in the same manner within a library. Try for instance,
to drag ‘Checkv’ to a place to the right of ‘Dorifit’.
25(75)
User’s guide to Hopsan
3.8.4 Naming
Close library ‘MyOwn’, reload it and then double-click on component ‘Dorifit’. The dialog in
figur 8 appears. ‘Component Name’ and ‘Component Type’ are read from the Fortran file and
can't be changed from within GDynMoC. ‘Component Name’ is the name of the Fortran
subroutine and ‘Component Type’ is declared in the subroutine's interface to GDynMoC. If
your ‘Dorifit.for’ had looked as in Figure 37, then also the comments and default values
would have been set to proper values. Now go through the columns with names ‘Name’ and
‘ParameterValue’ and edit the cells so that your Dorifit becomes as in figure Figure 40. Press
OK on the component and then save the library. Now you will get a message that it is writeprotected. Choose ‘File\Write Protection’ to erase the protection and then choose ‘File\Save’
again.
3.8.5 File Reference
Double-click on ‘Dorifit’ again and choose ‘File\Change References to Source Code Files’ to
see what file the Fortran subroutine resides in. This reference can be changed, but the chosen
file must contain a subroutine that has the identical name, argument list, subdata file and
GDynMoC interface as the original subroutine's Fortran file. This reference is passed to the
Fortran compiler when the simulation program is created.
3.8.6 Component- and Argument Types
The arguments for the subroutine are shown in a list. Their types are declared in the interface
to GDynMoC and are also shown. All inputs are treated as variables in GDynMoC as long as
they are not connected.
Figure 40. Contents of component DOrifit.
3.8.7 Connectors and Picture
Choose Connectors and Picture in the dialogue in Figure 40. Something like Figure 41 shows.
The connector for nodes ‘N1’,’N2’ (hydraulic nodes) and ‘D’ (input variable) must be
positioned properly so that they can be connected. Drag the connectors to their correct
positions. Any connectors placed in the upper left corner will be invisible to the user of the
component. Connector Name shows the comment for the connector that the mouse pointer
points at unless left mouse button is pressed since then the original name is shown (from the
source code).
26(75)
User’s guide to Hopsan
Figure 41. Connectors and picture of Dorifit.
The width and height can be changed. The size of the component picture when dragged into a
model depends on the magnification factor. The purpose of the view scale factor is to get a
large enough picture to work with when positioning connectors in the Connectors and Picture
dialog.
For each press to the button Rotate, GDynMoC searches for files named ‘DOrifit.wmf’,
‘DOrifit_90.wmf’, ‘DOrifit_180.wmf’ and ‘DOrifit_270.wmf’. Those files have already been
copied from component ‘Orifit’, e.g. ‘Orifit_90.wmf’ to ‘DOrifit_90.wmf’.
Press ‘Rotate’. Something like Figure 42 shows. Notice that the connectors are not correctly
positioned. This is a feature and not an error. It is possible to position the connectors
individually for each rotation in a manual fashion. It is also possible to automate this
procedure if the connectors are to be rotated in a normal mathematical sense. Press ‘Rotate’ a
number of times to get back where You started and choose ‘Other\Copy Node Configuration’.
Press ‘Rotate’ and notice that the connectors now have been positioned for the rest of the
rotations according to your change. If this procedure has made some errors, it is easily
corrected by dragging the connectors to the right positions for each rotation. Changes are only
saved if ‘OK’ is chosen both on the ‘Connectors’ and ‘Picture’ dialog and the ‘Component
Info’ dialog. Do just that and save the component library.
Figure 42. First rotation of DOrifit, showing DOrifit_90.wmf.
3.8.8 Inserting Components into System Model
To create a system containing an orifice and two pressure sources, simply drag two ‘Pcsrc’
and one ‘Dorifit’ from library ‘MyOwn’ into the system model window, like in Figure 43.
Place the mouse cursor over the different components and notice that the component name
and the component instance name are shown in the lower part of the window and the first row
27(75)
User’s guide to Hopsan
of the comments for the component at the mouse pointer. The component instances are given
the same names as their library source components, but with an added number to make the
instances unique (which they must be). If the mouse cursor is placed over a connector, the
connector name, alias and type is displayed in the lower part of the window and the comment
is given at the pointer.
Figure 43. System model with a few inserted components.
3.8.9 Editing Components in System Model
Let's give the component instances better names. Double-click on the left Pcsrc. Change the
‘Component Instance’-field to ‘Pump’ (no special characters in this field, e.g. not spaces) and
also set the pressure by clicking in the value field of ‘Pressure’ and enter ‘300e+5’ (300 Bar)
for the pump (Figure 44). Try out the Help menu choice to see what the component achieves.
Figure 44. Changing settings in pressure source component.
Notice the variable name ‘PI_PCSRC_1’ in Figure 44. It is used so that all variables in a
system can be distinguished from each other. This name can be changed manually. The name
is normally created as the name of the argument (in this case ‘PI’) added to the name of the
component instance. Since we have changed the name of the component instance, the variable
alias is no longer of the mentioned format. It can still be used, but can be updated by using
‘Reset Argument Names’. Do that, give the other pressure source the name ‘Tank’ and
pressure ‘1e+5’ (1 Bar) and press ‘Reset Argument Names’ on that component as well.
If a variable name is the same in some components, then the last changed value in any of the
components will determine what the value of the variable having the same name in the other
component will be. The same is true for ‘subdata files’. If two subdata files have the same
28(75)
User’s guide to Hopsan
name, then the last changed subdata file replaces the first one. Subdata files are just a
collection of parameters that can't be changed during the simulation.
Later on, when the simulation takes place, some variables can be plotted. Plottable variables
belong to arguments of types ‘OutputVariables’ and ‘?Qnodes’ (?=Mechanical, Hydraulic and
more). There are therefore four variables that can be plotted for ‘Dorifit’ as in Figure 45.
Temperature and mass flow as well as more node types than hydraulic and mechanical can
only be used if the parameter ‘UseNewNodes’ in the ‘Gdynmoc.ini’ file is set to ‘1’. Their
starting values in the simulation and also their scales when plotted can be set. Double-click on
node ‘Port 1’ and set scale factor for ‘Pressure’ to ‘1e-5’ (Bar instead of MPa). Do the same
for node ‘Port 2’.
Figure 45. Plottable variables in DOrifit.
The pictures can be changed according to ch. 3.8.12. Lets try for instance to make the
‘Dorifit’ picture larger. Double-click on ‘Dorifit_1’, choose ‘Connectors and Pictures’, write
‘2’ in Magnification, press Return and press ‘OK’ in the two dialogs. The results show in
Figure 46.
Figure 46. System after larger magnification of DOrifit.
3.8.10
Rotating Components
Try pressing Ctrl+R after you have clicked on ‘Dorifit’. The component should rotate at each
click. This feature functions as long as four pictures are available for the component, one for
each rotation.
29(75)
User’s guide to Hopsan
3.8.11
Copying Components
By pressing Ctrl+C after have marked a component and then pressing Ctrl+V while placing
the mouse marker somewhere in any system model, the marked component is copied to the
latter position. The component copy can share parameter values with the original component
if so desired, by answering yes to the question that appears (to the left in Figure 47). If the
components contains any subdata file, You also have to specify whether it to is to be shared
between the two components. If both questions are answered with a "yes", GDynmoc will
copy parameter names and subdata file names from the original component to the copied one.
If any parameter value or subdata file value is changed after this copy operation, all
components containing the same parameter names or subdata file names will be updated with
the new values.
Now lets try this. Mark ‘Pump’ and copy it to somewhere in the working space of the system
model. Answer yes to the following question so that parameter values are shared between the
new component and Pump. Now change the pressure ‘PI’ in the new component to 200 Bar,
and look at ‘PI’ for Pump. It has got the same new value! Delete the new component when
finished and change back the pressure to 300 Bar. Components from different models can't
share parameter or subdata values even though the question will pop up. In that case, always
answer No!
Figure 47. Copying component.
3.8.12
Changing pictures of components
Double-click on the right ‘Pcsrc’, choose ‘Connectors and Picture’ and then ‘Picture\Show
Pictures’. Here it is possible to change the picture into another one. The Pcsrc You are
working with now is going to be used as a tank, and therefore a more suitable picture is
‘Pcsrc_pt.wmf’. Mark it in ‘Available Pictures’ and a tank symbol should appear as in Figure
48.
The ‘Complementing Search Library’ and dito drive can be used when You want to be able to
choose from pictures from other places than the ‘Pictures’ library below the GDynmoc library
in your file system.
Now choose ‘OK’ in the picture dialogue. The magnification needs to be adjusted to the new
picture. Set ‘Magnification’ to 2 or 3 depending on your system and drag connector ‘N1’ to a
suitable position. Press ‘OK’ on the two open dialogs.
30(75)
User’s guide to Hopsan
Figure 48. Exchanging picture of Pcsrc.
3.8.13
View Source Code for Component
As described earlier, all components refer to some file containing the source code for the
component. This file can be viewed by marking any component and then choosing
‘Information\View Component Source Code’. Mark ‘Dorifit’ and do the latter. Something like
Figure 49 then shows. If an error message occurs instead, edit GDynmoc.ini and change the
line starting with ‘Viewer’ to an appropriate path to a text file viewer. Gdynmoc needs to be
restarted for changes in Gdynmoc.ini to make any effect.
Figure 49. Source code for DOrifit.
3.8.14
Creating new components out of pre-defined ones
In this chapter, a new component is created using existing ones. It is a signal generator that
outputs a step from an initial constant level. Create a new system model and name it MyPulse.
Bring together components as in Figure 50.
Change following parameter names:
IN2_SUM2_1 in SUM2_1 to DC
T1_PULSS_1 in PULSS_1 to T1
T2_PULSS_1 in PULSS_1 to T2
K_GAIN_1 in GAIN_1 to AMP
31(75)
User’s guide to Hopsan
This is done so that the new component in the following part doesn't get to long parameter
names and also because the parameters then will have other meanings than before. Change
comment on parameter ‘DC’ to ‘DC level of pulse’ and comment on ‘AMP’ to ‘Amplitude of
pulse’. If you want to make sure that some unconnected visible input variables remain
constant during simulation of the created component, make corresponding nodes invisible.
Actually, invisible ones can later be made visible and therefore connectable, so the normal
procedure is to make all unconnected input variables invisible. So, make the connector for
‘DC’ invisible by putting it in the upper left corner of its picture in Connectors and Picture.
Save the model. Choose ‘File\Save as Component’ to create a new GDynMoC component
from the system model. A dialog as in Figure 51 appears. GDynMoC now wants to know in
which component library You want to place the new component. You could also create a new
library for the component. Select ‘Test’.
Figure 50. System model MyPulse.
Figure 51. Selecting component library for new
component MyPulse.
If any of the components would have contained subdata files, these would now had been
shown in the frame ‘Subdata files’ in the window, as in Figure 52. They would then become
subdata files of the new component MyPulse. All parameters, that will say invisible input
variables, of the components appear under ‘Parameters to Subdata File’. Delt_max is a
parameter that is always constructed. It is the maximum time step for the component and is set
to the time step used in the system model. The parameters are placed in a subdata file for the
new component with the name placed over them ‘MyPulse_sda’. If You want to have the
parameter out of the subdata file for later being used as either variables or parameters, doubleclick on them and they are transferred to ‘Global Parameters’ and vice versa. It is very
important to use short names for all parameters, plot variables (output variables, node
variables and more) and subdata files. Otherwise, the simulation program will have
difficulties in processing the names. Transfer all parameters except ‘DELT_MAX’ to ‘Global
Parameters’ so that the user later can have the choice of varying these during simulation.
Figure 52. Configuring the new component MyPulse.
32(75)
User’s guide to Hopsan
In the ‘Free Nodes’ part of the window, all nodes that can be connected to are shown. These
will be the nodes of the new component. In this case only one node exists; the output node of
the reference signal. Change the node's name to ‘OUT’. You also have to shorten the name of
the subdata file to e.g. ‘MyPulse_S’.
Press ‘OK’. Instantly the component library ‘Test’ is loaded and in it lies the new component
‘MyPulse’. The picture of it has been created as a snapshot of the system model (not in
Hopsan 1.2.0.6 and later, where the figure will be distorted, use WMFGDyn.exe to get a better
picture).
Now, let's look at the new component. Figure 53 shows that it is of type Ctrl1. That means
that none of its nodes is of Q- or C-type. It is important to know when creating new
components in this manner, that components cannot have both Q- and C-nodes. Therefore all
free nodes must be either of Q- or C-type. Free nodes of variable type does not present any
problem and can consequently be used combined with the Q- and C-types. Delt_max has been
set to the time step used in the system model ‘MyPulse’.
Choose ‘Connectors and Picture’ and then ‘Picture\Show Pictures’ and select ‘Pulss.wmf’.
Drag the connector ‘Output’ to an appropriate position and choose ‘OK’ in the two open
dialogs. Save the library ‘Test’.
Figure 53. The new component MyPulse.
3.8.14.1
Creating a MetaFile
A useful feature, e.g. when it concerns documenting the system model, is the ability to create
Windows Enhanced Meta Files (EMF-files). They can easily be imported into other Windows
programs such as Microsoft Word for Windows. Also, they can be put in the Pictures
directory, serving as icon pictures for any components, given that appropriate names are used.
In our example, the EMF-file would look like figur 20. GDynMoC 1.3 cannot produce these
images, instead execute WMFGDyn.exe in the ‘..\Gdynmoc’ folder and choose ‘Misc\Create
MetaFile’.
Figure 54. WMF-file of system model.
33(75)
User’s guide to Hopsan
3.9 Using the command line interpreters and scripts
In ch. 3.4 we saw that the command window of the plotting application could be used to
perform some commands. To access the command line in the plotting application, choose
‘Calculations\Command Inputs’. If you open the command window, you will then see a
prompt like ‘Hopsan>’ and a black cursor. In the plotting application, most commands shown
in the reference in ch. 4.5 can be used, but not any commands that initiates simulations, e.g.
‘Sidy’, ‘Simdyn’, ‘Consimdyn’, ‘Optim’, ‘Peekl’ and ‘Listen’. These can only be performed
in the simulation application (the black window). To access the command line of that
application, write a script that contains no ‘quit’ statement and run it. To do that, choose
‘Simulation\Script\Define Script’, make the file contain just a simple ‘end’, save it and choose
‘Simulation\Script\Run Script’. Then, the black window will appear and you will have the
‘Hopsan>’ prompt showing again. In this window, all commands dealing with plotting has no
effect, e.g. ‘Chpv’ and ‘Replot’. However, if the HopsanPlotter application is running and a
‘Sidy’ command is entered, the results are read by the HopsanPlotter application and can be
plotted there. The ‘quit’ command exits the application.
The normal usage would be to use the command line of the simulation application and plot the
results in the plotting application. Let us try that. Start the HopsanPlotter application if it is
not running. Write an empty script except for the ‘end’ line and run it. Write ‘repa
HopSim.dat’ to read the parameter values from the model in GdynMoC into the simulation
application. Then write ‘sidy’ to perform a simulation. Plot a variable in the plotting
application. After an optimisation, the ‘sidy’ is automatically performed. A tip for making the
feedback in the simulation application look nicer is to go to the properties for HopSim.exe
window and widen the screen buffer to 300 characters. Save the changes for future windows.
The Hopsan commands are described in ch. 4.5.
If you want perform some commands often, put them in a script by choosing
‘Simulation\Script\Define Script’ and run it. Scripts can also be executed from the command
line in the two applications by using the ‘exec’ command. Since the simulation and plotting
applications run in the HopSim folder, just make sure that the exec command finds the script
you want to run. If you have created a script for the ‘MyServo’ model named SaveData.hcom
and Hopsan is installed in d:\Hopsan, the exec command would be:
‘exec d:\hopsan\gdynmoc\samples\myservo\SaveData.hcom’. There is more to read about
scripts in ch. 4.4.
4.Reference
4.1 Simulation
4.1.1 The simulation technique used in Hopsan
Hopsan makes use of the properties of loss-less transmission lines to perform efficient
simulation. It is shown in this chapter what the favourable properties are and how to make use
of them to get a simulation. The transmission line could be hydraulic, electrical, pneumatic,
etc. In Figure 55, a line is shown with the flow- and intensity variables q and p. In electrical
systems, as this chapter deals with, p is voltage and q current.
34(75)
User’s guide to Hopsan
q1
q2
p1
p2
Figure 55: Transmission line where p and q are intensity- and flow variables respectively.
If losses are ignored, such as resistance in this case, the line can be looked upon as an infinite
number of simple structures as in Figure 56 connected in series [1]. If the total capacitance of
the line is C, then the capacitance of each capacitor is C/2n since every microstructure
contains two. The inductance of each structure is in the same manner I/n.
qL
pL
qR
pR
I
n
C
2n
C
2n
Figure 56: Microstructure for the ideal transmission line. The inductance of the spool is denoted I and C is
capacitance. There are n structures in a transmission line.
If the equation system is solved for the microstructure, Eq. (1) is gained. In this equation, s is
the derivative operator.
IC
é
1 + 2 s2
é pL ù ê
2n
2
êq ú = êC
ë L û ê s + IC s 3
4n 3
ën
I
ù
s ú p
é Rù
n
ú
êq ú
IC
-1 - 2 s2 úë R û
2n
û
-
(1)
If the middle matrix in Eq. (1) is raised to the power of n and n goes to infinity, a number of
power series are produced that can be summed yielding the expression in Eq. (2) as shown in
e.g. [1].
é
é p1 ù ê
=
ê q ú êë 1û
ë
cosh IC s
- I / C sinh IC s ù é p ù
ú 2
1
sinh IC s
cosh IC s
ú êë q2 úû
I /C
û
(2)
Eq. (2) can also be written
p1 =
(
p2
e
2
q1 = -
p2
2
IC s
+ e-
(
1
e
I /C
IC s
IC s
) - q2
(
2
- e-
I /C e
IC s
)+ q2 (e
2
IC s
- e-
IC s
IC s
+ e-
)
IC s
(3)
)
(4)
Eq. (3)+ I / C (4) and Eq. (3)- I / C (4) transformed into the time domain gives [2]:
35(75)
User’s guide to Hopsan
p1 (t ) = Z c q1 (t ) + p 2 (t - T ) + Z c q 2 (t - T ) where Z c = I / C and T = IC
(5)
p 2 (t ) = Z c q 2 (t ) + p1 (t - T ) + Z c q1 (t - T )
(6)
An equal result has been derived in [3] in the case of fluid transmission lines by regarding
conservation of mass and momentum.
If the old information from the other end of the line is denoted c, Eq. (5) and (6) can be
written as
p1 (t ) = Z c q1 (t ) + c1 (t )
(7)
p 2 (t ) = Z c q 2 (t ) + c 2 (t )
(8)
where the waves of information from one end of the line to the other, the characteristics [2],
are written as
c1 (t ) = p 2 (t - T ) + Z c q 2 (t - T )
(9)
c 2 (t ) = p1 (t - T ) + Z c q1 (t - T )
(10)
The following list of properties is also sufficient to yield Eq. (5) and (6)
·
There is a time delay T for all information propagating through the line
·
Symmetry
·
Flows entering the line produce an increase in pressure in steady state
·
Linear dynamics
If Eq. (9) and (10) are combined with (5) and (6), the characteristics c1 and c2 can be
calculated as
c1 (t ) = c 2 (t - T ) + 2Z c q 2 (t - T )
(11)
c 2 (t ) = c1 (t - T ) + 2Z c q1 (t - T )
(12)
Eq. (11) and (12) are illustrated in Figure 57, where with respect to the left end of the line, c1
is an incident wave and c2 a reflected one. If the left end is closed, q1 is zero and the reflected
wave c2 will be equal to c1; no energy has been added or lost. If an orifice had been placed on
the left end and it was connected to tank, a negative q1 would have been the effect. The wave
c2 would then have smaller amplitude than c1 after reflection. The latter means that energy
would have been lost in the view of the transmission line.
36(75)
User’s guide to Hopsan
c2
q1
q2
c1
Figure 57: Transmission line and the waves of information; c1 and c2
So a method of solving networks of components connected to each other with transmission
lines can now be stated. Eq. (11) and (12) are used in each transmission line to calculate the
information waves. Eq. (5) and (6) are then used between the lines, e.g. in an orifice, to
calculate the flows that the lines need to calculate the reflected waves. This particular way of
dealing with the information wave in the form of characteristics is called the method of
characteristics [2].
Combining the expressions for Zc and T in (5) yields
T2
T
I=
and Z c =
C
C
(13)
Now, if some transmission lines are used in a simulation, a certain time step h will be used. Zc
can then be calculated as in Eq. (13) with T replaced with h so that the correct capacitance is
gained. The inductance will then be correct if h is equal to T and be e.g. larger if a larger time
step is used. This is called a parasitic inductance. This is how the Hopsan simulation package
is implemented [2]. The transmission lines are there used as pure capacitance’s connecting
other components such as orifices and pumps. The time step used in the simulation is then
chosen with regard to the parasitic inductance so that it is kept on an arbitrary low level. This
error is to be compared to the numerical error introduced in centralised solvers where the error
has no physical meaning.
Since the transmission lines makes it possible for each adjacent component to calculate its
state variables independently of state variables in other components, the simulation will
become fast. Taking a component containing a certain number of state variables and solving
that with a central numerical solver, the size of the problem grows more than linear to the
number of states in that component. Using transmission lines, the time needed for a simulation
is directly proportional to the number of states in that component.
References
[1]
AUSLANDER D.M., “Distributed System Simulation with Bilateral Delay-Line Models”, Journal
of Basic Engineering, Trans. ASME, pp. 195-200, June 1968
[2]
KRUS P., JANSSON A., PALMBERG J-O and WEDDFELT K, “Distributed Simulation of
Hydromechanical Systems”. Presented at Third Bath International Fluid Power Workshop, Bath,
UK 1990.
[3]
POLLMEIER K., “Parallel simulation of complex fluid power systems – A new method to reduce
the communication between processors”, Proceedings Part I, Journal of Systems and Control
Engineering, ImechE, Vol. 210, No 14, pp. 221-230, 1996
37(75)
User’s guide to Hopsan
4.1.2 Communication between the applications
Hopsan is a tool for modelling and simulating systems containing e.g. hydraulic-, control- and
mechanical components. The user specifies how component models are to be connected and
what parameter values they should hold. The graphical part of Hopsan, GdynMoC, then
creates an executable simulation program out of the information that the system model
contains. In the created program, the system is simulated and variables such as e.g. pressures,
flows and velocities are transferred to a plotting program where the user can study them.
A component in a component library has three references and one of them points to a file that
contains a Fortran subroutine with the same name as the component. The subroutine makes up
the behaviour of the component. If you double-click on a component instance in a model and
choose ‘File\Change References to Source Code Files’ you will see that some Fortran file is
pointed at. Often, the components point to ‘Clib.for’. This contains most of the subroutines
needed for the ‘Standard’ component library. Also, the component has information about the
interface to the subroutine; inputs, outputs, subdata files and more. This information is not
linked to the subroutine file and can thus become out of date. In that case, a compile error or
at least run-time error will occur.
So, GdynMoC knows which Fortran files are needed to generate a simulation application.
GdynMoC writes information to ‘HopSim.DMC’ about how the component instances are
connected and to ‘HopSim_sub.f’ about the interfaces to the subroutines. The application
‘Dynmoc’ in the ‘Bin’ folder in the Hopsan installation reads the two files and generates
‘HopSim.f’ which is a subroutine that can call the different component subroutines during
simulation. One subroutine can be called several times each time step if several instances exist
in the model of the component that refers to the subroutine. GdynMoC then generates a
makefile and runs that through the ‘MakeHop.bat’ batch file. Then, ‘HopSim.f’, ‘HopMain.f’
(main program), ‘HopCern.lib’ (Hopsan cernel), a library for sockets, a general C library as
well as all files referred to in the GdynMoC model are compiled and linked together into
‘HopSim.exe’. ‘Clib.for’ is part of ‘HopCern.lib’ and is therefore not part of the makefile.
Any changes to ‘Clib.for’ therefore don’t give any effect. The output from the make operation
goes to the file ‘MakeResult’. If you suspect a compile error (e.g. if the simulation doesn’t
run), look in this file to see the error, then send the ‘MakeResult’ file to the person responsible
for Hopsan so that he can make GdynMoC complain about the error. Finally, the ‘HopSim’
program is executed. It reads the ‘COM.HCOM’ file and performs any commands in it. One
of the various script files (ending with ‘HCOM’) in the HopSim folder is copied onto the
‘COM.HCOM’ script before each simulation. ‘COM_optim’ is used for optimisation,
‘COM_sim’ for simulation, ‘CoSim’ for co-simulation and ‘User’ for the user-defined default
script.
If a ‘sidy’ command is done in HopSim, a plot file is saved named ‘HopSim.PLO’ at the same
time as the contents of ‘HopSim_sig.txt’ is changed to a number of value 1. The
HopsanPlotter application constantly reads the latter file to see when the normal value of 0
changes to 1. When it finds out, it executes ‘HopSim.HCOM’. As default, this file tells
HopsanPlotter to read the ‘HopSim.PLO’ file.
38(75)
User’s guide to Hopsan
4.1.3 The Fortran component subroutines
A typical beginning of a Hopsan component Fortran subroutine would be the following
C================================================================
C
SUBROUTINE PISTM1(ML,BL,KL,FILENAME,N1,N2,NX,NO)
IMPLICIT NONE
SAVE
INCLUDE 'bondsize.inc'
C
C#
BeginInterfaceDeclarations
C#
BeginComment
C---------------------------------------------------------------C# This is a model that represents a piston with an inertia load.
C# The capacitances in the chambers are neglected.
C#
C# Written by Petter Krus 911119
C#
C#
I
I
C#
Q(N1) I
Q(N2) I
X(NX1)
C#
I
I I----------->I
C#
I-------------------------I
______I
C#
I
I I____________I______I
I
F(NX1)
C#
I P(N1),A1 I I___________________I ML I<-------C#
I
CIP I=I P(N2),A2
I
I_____I
C#
I-------------------------I
I/////I
C#
KL,BL
C#
EndComment
C
C#
ComponentType Q-Type,hydraulic
C#
ComponentNumbers
INTEGER NO
C#
HydraulicQNodes
INTEGER N1 !Cylinder port 1
INTEGER N2 !Cylinder port 2
C#
InputVariables
REAL ML
!Inertia/Inertial moment (kg). Default value=0.05
REAL BL
!Viscous friction coefficient (Ns/m). Default value=0
REAL KL
!Stiffness (N/m). Default value=1000
C#
MechanicQNodes
INTEGER NX !Piston
C#
SubdataFiles
CHARACTER*(*) FILENAME !Constants
C#
EndInterfaceDeclarations
The Fortran subroutine takes a number of arguments. In Fortran these are not regarded as
inputs or outputs, but can be used as both, i.e. their values can be changed by the subroutine.
‘IMPLICIT NONE’ tells the compiler not to assume anything about the types of the Fortran
variables. ‘SAVE’ causes all variables to be saved between calls to the subroutine.
‘INCLUDE’ reads the specified file and makes it part of the source code. The file
‘bondsize.inc’ contains declarations of node variables that are used to exchange node
information between the subroutines. Then, the Hopsan comments start with
‘BeginInterfaceDeclarations’. A comment for the GdynMoC component follows. The
‘ComponentType’ could be any of:
Component type
Source
Ctrl1
Ctrl2
C-type, mechanic
C-type, hydraulic
Q-type, mechanical
Q-type, hydraulic
Comment
Signal generator
Controller type 1
Controller type 2
Mechanical C-type
Hydraulic C-type
Mechanical Q-type
Hydraulic Q-type
39(75)
Example
XFEEDB
PISTON, SPRING
VOLUME
MLOAD
VPUMP
User’s guide to Hopsan
The component type determines in what order the subroutines will be called in the simulation
application HopSim.f . ‘Source’ is first and ‘Q-type…’ is last. ‘C-type’ and ‘Q-type’ refers to
the discussion about the method of characteristics in ch. 4.1.1. The ‘C-type’ components
calculate the waves c and characteristic impedance Z and the ‘Q-type’ components calculate
the flow- and effort variables. The ‘mechanic’ or ‘hydraulic’ part of can also be mechanicRot,
electric, pneumatic, electricAC, magnetic and thermal.
Then, the nodes are declared. ‘N1’ and ‘N2’ are pointers into the arrays named p and q e.g.
that are pressure and flow in the hydraulic nodes. The latter are declared in ‘bondsize.inc’.
The ‘InputVariables’ nodes do not point into any arrays but are pure subroutine arguments.
The mechanic node follows the principles of the hydraulic nodes. ‘SubdataFiles’ is a special
construction that is used to reduce the number of arguments to the Fortran subroutine. The
variable ‘FILENAME’ contains a name of a file that in turn holds a number of constants and
their values. They are read during the first time step of each simulation as follows where ISR
indicates whether it is the first time step in the simulation or not.
C
C
Initialization
IF(ISR .EQ. 1)THEN
Input from file.
CALL PARINI(FILENAME,5,PAR)
A1(NO)
= PAR(1) !Piston area 1 (m2). Default value = 1e-4
A2(NO)
= PAR(2) !Piston area 2 (m2). Default value = 1e-4
SL(NO)
= PAR(3) !Stroke (m). Default value = 1e-2
CIP(NO)
= PAR(4) !Leakage coefficient between the piston chambers (m3/sPa).
Default value = 0
BP(NO)
= PAR(5) !Viscous friction coefficient of piston (Ns/m). Default
value = 0.
IF(ISR0.EQ.1)THEN
N = N + 1
NO = N
ENDIF
ENDIF
‘ComponentNumbers’ is used to distinguish between several instances of the same
component. There could be several ‘PISTM1’ running in the same simulation and the most
recent position etc. therefore needs to be stored for each instance. The ‘NO’ parameter in this
case tells the subroutine which instance to deal with at the moment. In the shown part of
above of the subroutine, ‘NO’ is updated each time the subroutine is called on the first
simulation since the simulation application was started (indicated by ISR0). ‘N’ is initially set
to zero.
Below is a summary of the information above and some other node types not mentioned.
Except hydraulic and mechanic nodes, also mechanicRot, electric, pneumatic, electricAC,
magnetic and thermal node exist. Study ‘Clib.for’ and the other Fortran files in
‘..Gdynmoc\ForLib’ to see how components can be written.
40(75)
User’s guide to Hopsan
Table: Node types and other component interface information
In each ‘physical’ node, like the hydraulic one, a number of variables exist that are accessible
to all component subroutines. There are flow-, effort-, characteristic waves- and characteristic
impedance variables as shown in ch. 5.2.
4.2 Optimisation
The optimisation built-in in HOPSAN is based on the Complex method. The basic idea is to
use an already developed simulation model and apply the optimisation algorithm on that.
Typical things to optimise are pump and valve sizes and control parameters. To optimise it is
necessary to write a file describing the object function and the parameters to optimise along
with some settings for the optimisation algorithm. The format of this file is described below.
The command for starting the optimisation is then OPTIM OPTFIL or just optim which
causes HOPSAN to prompt for a optimisation filename.
41(75)
User’s guide to Hopsan
4.2.1 What happens during an optimisation
The normal procedure for optimisation is outlined in Figure 58. First is the initial parameters
set, normally by a rectangular random distribution within the constraints.
Figure 58. Optimisation procedure
4.2.2 Results from an optimisation
These are separated into two parts: the trace of the parameters and the simulation result. The
trace of the optimised parameters and the corresponding value on the object function is saved
in a special generation of plot-variables with the number of performed simulations (NofCalcs)
as the independent variable.
4.2.3 Optimisation datafile (with a filename ending with ‘.ODAT’)
This file describes the object function and the parameters to optimise along with some settings
for the optimisation algorithm. Lines beginning with a # are ignored. The lines beginning with
a % contains keywords. After a line with a keyword the arguments to this keywords are listed.
The keywords and their arguments are:
·
OPTIMISE [THESE PARAMETERS]. (Only OPTIMISE is necessary) After this keyword
the parameters are listed with their name, min and max values, optional is here the
word LOG which tells the optimisation algorithm that the parameters should be chosen
in a logarithmic fashion. (EX: GAIN 0.01 1 0 LOG). The parameters in subdata files
can also be subject to optimisation. The name is then the subdata parameter name
followed
by
@
and
the
subdata
filename.
(Ex. DP@PUMP 10e-6 100 1e-6 LOG)
42(75)
User’s guide to Hopsan
·
COMMAND. Max
·
OBJECT [FUNCTION].
Here is the object function specified as an expression which is
input to the built-in calculator. The result of this expression better be a scalar value
and not a plot-variable. If there is a plot-variable called P1 and another called Q1 and
one wants to optimise on the power (ie Q1*P1) it is thus necessary to write:
AVER(Q1*P1) or MAX(Q1*P1) or some-other operation resulting in scalar value (see the
appendix about the built-in calculator). The optimisation is done as a maximisation
and it is therefore to consider if the object-function results in a positive or a negative
value. If the power is to be minimised it is recommended that one uses AVER(ABS(Q1)*P1) as an object function. It is of cause possible to calculate the
object-function in the simulation model, this will reduce the time taken. Another
advantage with doing so is that it is possible to calculate more complex objectfunctions in that way. Implicit restraints can, for instance, be added as penalty
functions.
·
METHOD. At
·
METHOD PARAMETERS. Here are the method specific parameters defined. There are also
some concerned with convergence. The settings for convergence for the complex
method are:
10 lines of normal HOPSAN commands, including execution of scripts,
to be performed before each object function calculation. These commands replace the
default command -- simulation. If your object function evaluation needs a simulation,
add that as a command as well.
present is COMPLEX and GA available.
Convergence relative
or convergence absolute (default is relative)
The convergence is specified as:
conv_cond = value
(Ex. conv_cond = 0.001) (default 0.01)
·
ALPHA. The reflection parameter.
·
RFAK. A factor that adds some random moves to the normal reflection steps
according to
Default value (and probably best) is 1.3.
If set to zero is the normal complex used. Default value = 0.
·
A startvalue for the random number generator. If set to zero is a new
random number given. If set 0<SEED<1 is the random number generator started
at this value which is nice for repeatable optimisations.
·
MAXNOSIM
·
Size of the complex. The minimum and default value is the number
of parameters plus one.
·
GASEED
SEED.
Max number of function evaluations (simulations).
Nofpoints
The seed for the random number generator used for the genetic
algoritm. A negative value reseeds the generator. Default value -1000.
43(75)
User’s guide to Hopsan
·
GAMAXGEN
·
GARESTART A restart possibility exists. Probably not yet wise to use. Default
value 0.0 which means a new optimisation, 1.0 would result result in a restart.
·
GAPMUTATE
·
GAPCROSS
The probability for crossover. Default value 0.5.
·
GAPCREEP
The probablity for creep mutation. Default value 0.
·
GAPOPSIZE
·
Uniform or single point crossover. GAUNIFORM=0 for single-point
crossover and GAUNIFORM=1 for uniform crossover; uniform crossover is
recommended. Default value 1.
·
GANICHE
·
GANPOSSIBLE
The max number of generations to be calculated. Default value 100.
The probability for mutations. Default value 0.001.
The size of the population. Default value 50.
GAUNIFORM
Niching or or not. GANICHE=1 for niching GANICHE=0 for no
niching. Default value 1.
Number of discrete levels each parameter is divided into. Default
1024.
·
GAMICRO
·
GACHILDREN
If set to 1, use micro GA. If zero don't. Default value 0.
Number of children per pair of parents. One or two. Default value
2.
·
GAELITE
·
GACREEP
·
If the best value has been the same during GACONVERG
generations, consider the optimisation to be converged. Default value 100.
·
GASAVEALL
Use elitism (or not). This means that the best individual always is
kept unaltered. Default is to use elitism (1).
Use creep mutation (or not). Default is to use creep mutation (1).
GACONVERG
If one (1) save trace of all individuals. If zero save only the best in
each generation. Default is to save all (1).
·
Remove old generation direct. This has to with HOPSAN and its memory
management. If the argument is YES no generations are saved during the optimisation.
The plotvariables are removed directly after evaluating the object function. If it is set
to NO (which is the default) no variables are removed until necessary, this will increase
the overhead time, but some more results will be saved.
·
SILENT. If set to YES the optimisation is performed with less diagnostic output and no
results are plotted after each simulation. The default is NO, that is, some diagnostic
output are printed and a replot is performed after each simulation.
44(75)
User’s guide to Hopsan
Table: Method parameters for complex and GA
Below is a simple indatafile shown for optimisation of feedback gain for the control and
pressure level in a servo control circuit.
Example without commands
% optimise these parameters
gain 0.001 0.09 0 log
PIP_PCSRC 25e5 500e5 0
% object function
(-max(integ(abs(x2-yr),time) + integ(x2>0.25105,time)))
% method
complex
% method parameters
convergence relative
conv_cond = 0.005
maxnosim = 100
nofpoints = 4
% Remove old generation direct
YES
% Silent
45(75)
User’s guide to Hopsan
no
Example with commands
% optimise these parameters (syntax: parameter minvalue maxvalue conv.tol
[log])
kp
0.01 100 0 log
ki
1e-6 100 0 log
kd
1e-8 10 0 log
% command (max 10 lines)
frequency:c=logspace(0.1,100,511)
s:c=frequency*2*3.1415*sqrt(-1)
go:c=(kp + kd*s + ki/s)/s/( (s/wh)**2 + 2*dh*s/wh + 1)
gc:c = go/(1+go)
amph gc
bode gc
func:c=sum((abs(s)<0.5*wh)*(abs(abs(gc)-1)))
func:c=func+ sum((real(go)<(-0.8))*(abs(imag(go))<10)*(abs(s)<30))*100
% object function
(-func)
% method
complex
% method parameters
convergence absolute
conv_cond = 0.0001
maxnosim = 500
nofpoints = 10
seed = 0.54
% Remove old generation direct
no
% Silent
yes
4.3 Interpreter
4.3.1 Command line
In ch. 4.5, commands that can be given on the command-line or in a script are listed. The
arguments in sharp brackets are optional. If no arguments are sent to a command, the
command enters an interactive mode, asking for the necessary arguments as they are needed.
It must be noted, however, that options are usually not asked for in the interactive mode. This
means that the interactive mode is somewhat less powerful for some commands. This also
means that the command-line way to give a command can do very much damage if one does
not completely understand the command. Use the interactive mode first, and learn what a
command can do, then use the command-line options. An example:
chpa delt 2.e-3
is the same as first typing chpa and then answering the questions, as in:
--------- Change parameters --------Parameter name: delt
Old DELT: 1.0000E-03
New value or CR:>2e-3
Parameter name:
The command-line offers several special functions, such as doing something with all
46(75)
User’s guide to Hopsan
parameters/variables matching a certain wild-carded string. The following will set all
parameters beginning with ``P'' to 1e5.
chpa p* 1e5
Another function the command-line offers is the possibility of using expressions when setting
the values on parameters/variables. This is done by enclosing the expression in parenthesis.
This can be used when a number is to be input, for instance, when setting parameter values,
scalings, start-values or time-limits. It is for example possible to do:
chpa p* (aver(p2))
This will of course set all parameters beginning with a p to the average of the plotvariable p2.
The parenthesis are a signal to the command interpreter to calculate something. The result of
this calculation better be a scalar value and not a vector (plot variable), or an error message
will be printed and the command ignored.
4.3.2 Variable types
In HOPSAN there are five (six) types of plot variables, namely: "T", "R", "I", "C", "A", "P".
where
T
Time domain. The default type. If no type is specified time domain is assumed.
R
Real. Real part of a frequency domain plot variable. For instance, created by a FFT
analysis. The frequency will also have this type.
I
Imaginary. Imaginary part of a frequency domain plot variable.
C
Complex. A way to specify both real and imaginary parts as a unit. Meaningful for
calculations with complex variables and saving of complex results. Not meaningful for
plotting.
A
Amplitude. Amplitude for a frequency domain variable. Calculated using Real and
Imaginary.
P
Phase. Phase for a frequency domain variable. Calculated using Real and Imaginary.
The different types are restricted in their use in the following ways. It is not permitted to mix
time domain variables with frequency domain variables in diagrams, i.e. "T" can never be
plotted in the same diagram as "R", "I", "A", "P". The frequency domain variables are
possible to mix as one pleases. The built-in calculator can calculate with complex variables
only if it is told that the result is complex, e.g.. S:C = frequency*2*3.1415*SQRT(-1). The
C informs the calculator that the result and the used variables are complex. The type of a
variable is specified using a colon (:). As an example, the time domain result after a
simulation is P1, (remember that T is the default type!). If an FFT analysis is conducted on
that variable the result will end up in four variables with the same base name but with
different types: P1:R, P1:I, P1:A and P1:P. There is one special character to use instead of a
type, the wild card "*" matches all types, which can be handy sometimes.
47(75)
User’s guide to Hopsan
4.3.3 Variable generations
Since simulation often is an iterative process is it useful to have the opportunity to compare
the latest simulation with others, done with other parameters. This is in HOPSAN done by
saving each simulation in a separate generation. A generation is a set of plot variables
obtained from the same simulation, or results obtained from these variables, i.e. FFT. The
generation number is increased each time the user does any of:
·
Time domain simulation.
·
Frequency domain simulation.
·
Loading of a plot file (not always, see this command).
·
Loading a frequency domain variable from file.
·
NEWGEN - a command for scripts.
The generation number is reset only if the command for removing all plot variables is
performed. The generation of a variable is specified using a decimal point, i.e. SXP.1.
There are some rules regarding generations:
·
the last generation is the default
·
a "*" matches all generations
·
an "L" is interpreted as the last
·
at present it is not permitted to mix different generations in calculations other when
making an average of a transfer function for several simulations/ measurements. This
rule may change.
4.3.4 Variable names
Some commands (such as ‘Chpa’ ) ask for variable names. In almost all cases, it is possible to
give only a part of the name plus a special character, a wild card. As an example, if we have
several plot variables starting with a ``P'' and want a plot where all these variables are present,
it is possible to give ``P*'' as input. The special character ``*'' matches all strings, also the
empty ones. There is another special character, ``%'' which matches one character, if ``P%'' is
the input this will match all variables which starts with a ``P'' followed by a single character.
The comparison is made case insensitive. Input with ``wild cards'' in names works in most
cases where a variable or a parameter name is to be specified. One exception is the built-in
calculator, since the ``*'' has a mathematical meaning... When HOPSAN wants a
parameter/variable name it is mostly so, that a question-mark will list available variables to
choose from. An exception is `` Remove Some Plot Variables'' where a question-mark causes
a memory information dialogue box to be shown.
48(75)
User’s guide to Hopsan
4.3.5 Introduction to built-in calculator
The built-in calculator (interpret) can do calculations on plot variables in the time and
frequency domain together with parameters in the main data file. A typical expression is
[OutputVariable.Generation=] Arithmetic expression ;
(E.g.: PL.1 = P1 - P2;)
If calculations are to be made in the frequency domain a C is needed as a type on the result, to
specify that the result of the calculation is to be a complex number. If the variable S is defined
as a complex number it is possible to type
GLP2:C = 1/(S*S/100 + 2*0.1*S/10 + 1);
to obtain the real (GLP2:R) and imaginary (GLP2:I) parts of the transfer function for a second
order lowpass filter. (If the amplitude and phase is required use the command AMPH) It is not
permitted to use variables from the time domain in an expression resulting in a complex
variable, and vice versa. The generation specified for the output variable is the generation
valid for all variables in an expression. If no generation is specified is the last used. It is
possible to mix different generations in an expression by adding a generation to one or more
of the operands. It is thus permitted to write
PD.1 = P1 - P1.2
to obtain the difference between P1 in the first generation and P1 in the second generation.
The result is in this case put in generation 1. It is necessary that all generations have the same
number of samples (and the same timespan). The ending semi-colon is not required.
4.3.6 Operators in the built-in calculator
Unary minus is not fully implemented. 2*-3 will not work, instead write 2*(-3).
These operators returns a vector if at least one of the operands are a vector.
+,-,*,/
LOG(x)
10 logarithm
Addition, Subtraction,
Multiplication, Division
LN(x)
Natural (e) logarithm
**,^
Exponent: x**y (or x^, y) , can not
handle negative x's
EXP(x)
Natural exponent ()
SQRT(x)
SIN(x)
Square root
Sine
ABS(x)
COS(x)
Absolute value
Cosine
REAL(x)
TAN(x)
Real part
Tangent
IMAG(x)
ASIN(x)
Imaginary part
Arc sine
49(75)
User’s guide to Hopsan
ACOS(x)
COSH(x)
ATAN(x)
TANH(x)
Arc cosine
Hyperbolic Cosine
Arc tangent
Hyperbolic Tangent
SINH(x)
Hyperbolic Sine
Some specials. Can only operate on vectors and the return value is a scalar.
maximum of the imaginary part
returned.
SUM(x)
The sum of the elements in x.
AVER(x)
IMIN(x)
MIN(x)
IMAX(x)
Returns the index to the minimum
value of x.
Average of the variable over the
length of the vector.
Returns the index to the max value
of x.
Min value of the variable in the
vector. For a complex variable is
maximum of the real part and
maximum of the imaginary part
returned.
PEEK(x,n)
Picks the nth value out of the vector
x. PEEK(x,IMIN(x)) is thus the
same as MIN(x).
MAX(x)
Max value of the variable in the
vector. For a complex variable is
maximum of the real part and
Other specials. Results in real vectors
y as vector, returns a scalar if both
x and y is scalars. Operate only on
real variables.
LINSPACE(MIN,MAX,NO)
Linearly spaced vector from MIN
to MAX with NO samples
RAND(size)
LOGSPACE(MIN,MAX,NO)
Returns a vector with size SIZE
with random values.
RNDSEED(SEED) seeds the
random generator with SEED ( 0 <
SEED < 1).
Logarithmicly spaced vector from
MIN to MAX with NO samples
MAXOF(x,y)
Returns the largest values in x and
Logical and relational (return values as in C: 1 for true and 0 for false) The return value is a
vector if at least one of the operands are a vector, if both are scalars the return value is scalar
too.
<
<=
Less than. (operates only on real
part for complex numbers)
==
50(75)
Less than or equal. (operates only
on real part for complex numbers)
Equal
User’s guide to Hopsan
!=
>=
>
NOT(x)
Not equal
Returns 0 if x<>0 and 1 if x=0
(operates only on real part for
complex numbers)
Greater than or equal. (operates
only on real part for complex
numbers)
&&
Greater than. (operates only on real
part for complex numbers)
||
Logical AND. (operates only on
real part for complex numbers)
Logical OR. (operates only on real
part for complex numbers)
Filters. Can only operate on real vectors and the result is a real vector.
FILT(y,f,TIME)
First order time discrete lowpass filter without phase lag (phase=0 deg) See Bode plot.
y: Variable to filter (Vector)
f: Break frequency (approx. Hz) (Scalar)
TIME: Independent variable (Time) (Vector)
DDT(y,TIME)
Bandlimited differentiation with phase=90 deg. See Bode plot.
y: Variable to differentiate (Vector)
TIME: Independent variable (Time) (Vector)
INTEG(y,TIME)
Integration (trapezoidal rule)
y: Variable to integrate (Vector)
TIME: Independent variable (Time) (Vector)
LP1(y,f,TIME)
First order time discrete lowpass filter. Bilinear transform of a first order lowpass
filter.
y: Variable to filter (Vector)
f: Break frequency (Hz) (Scalar)
TIME: Independent variable (Time) (Vector)
4.3.7 Precedence for operators
The precedence is in falling order:
Exponentiation (** or ^)
Multiplication, Division (*, /)
Addition, Subtraction ( +, -)
Relational operators (<, <=, ==, !=, >= , >)
Logical operators (&&, ||)
Parenthesis is of course OK to use.
50(75)
User’s guide to Hopsan
4.3.8 Operands in expressions
With operands we here mean the actual variables or constants that we operate on in
expressions. For instance are A, B, C and 1.22 operands in the expression ``C=A+B+1.22''
Input
Plot variables, called ‘Vectors’ in the operator list
Parameters in the main data file, called ‘Scalars’ in the operator list
Parameters in subdata files, (‘Scalars’). They are accessed as Parname@Subdatafile. For
instance, the parameter A1 in the subdata file PISTON is accessed as A1@PISTON.
Internal parameters, called ‘Scalars’ in the operator list
Digits, decimal point not necessary called ‘Scalars’ in the operator list
Outputs, (left side of the assignment)
Existing plot variables
New plot variables will be created if the output variables do not exist
Parameters in main data file (for complex numbers will only the real part be put in a
parameter)
Parameters in subdata files, (Scalars). They are accessed as Parname@Subdatafile. For
instance, the parameter A1 in the subdata file PISTON is refered to as A1@PISTON.
Internal parameters (for complex numbers will only the real part be put in a parameter)
SCR, screen output. (Quite boring if it is a 1024 samples plot variable, but try it anyway)
No output variable specified results in that the result is written on screen, (if it is a scalar.)
Internal parameters
There is a possibility to create new scalar variables. If an expression returns a scalar value it is
put into a scalar variable. These can be used in all expressions, exactly as main data
parameters. An example how to make use of internal parameters can be as intermediary result
such as
DELTAH = KC0*SQRT(BETAE*JT/VT)/DM
OMEGAH = SQRT( 4.*BETAE*DM*DM/(VT*JT) )
GO:C = KV/((S/OMEGAH)**2 + 2*S*DELTAH/OMEGAH + 1)
There is a command RMPAR (not in the menus at the present) that removes a specified internal
variable.
4.3.9 Some rules for assignments
There are some rules concerning the assignments. A scalar value can not be assigned to a plot
variable (a vector), and a vector can of course not be assigned to a scalar. As an example to
the first rule, and a way to avoid it, we can consider the following expression, assuming that
SXP is a plot variable and TEMP does not exist as a parameter.
TEMP.L = AVER(SXP);
The function AVER returns a scalar value and this can not be assigned to the plot variable TEMP.
51(75)
User’s guide to Hopsan
The result will therefore be put in the internal parameter TEMP. A way to trick the calculator to
create a plot variable, would be to write
TEMP.L = AVER(SXP) + SXP*0.;
This will fool the calculator into creating a plot variable since the result of the multiplication
SXP*0. returns a vector and the addition AVER(SXP) + SXP*0. must therefore return a vector
(plot variable).
4.3.10
Some hints and warnings
Remember that all calculations are made over the complete length of a plot variable and that
most of the operators and functions return a vector with the same length as the longest
operand. As an example, the expression TEMP= (P1 > 2.E5) creates a plot variable TEMP (if
P1 is a plot variable) which has the value 1.0, where P1 is greater than 2e+5 , and 0.0
otherwise. Thus we can not obtain a plot variable with only the samples that are greater than
2e+5. If we want to limit a plot variable downward to 2e+5, the expression would be like
P1 = P1*(P1>2.E5) + 2.E5*(P1 <= 2.E5)
The result would be that all values that are less than or equal to 2e+5 would be substituted by
2e+5. Another example is the expression
SCR=SUM(P1)
which returns the sum of all values in the plotvariable P1, while
SCR=SUM(P1>2e5)
will return the number of points in the plotvariable P1 which are greater than 2e+5. This is
because that the expression P1>2e5 is 1.0 for the points where the condition is valid and 0.0
otherwise.
The calculator can be quite handy for transfer function analysis of step responses. FFT
analysis is not usable directly when the variable to be analysed is a result of a step response
since it does not start and end at the same value. If we differentiate both input and output it
would probably be possible to make a transfer function analysis. The calculator can also be
used for creating windows for FFT analysis purposes.
4.3.11
Calculations with complex numbers
By using scripts it is possible to plot transfer functions in a more flexible way then when
using frequency simulation with a FORTRAN subroutine (FREMOD). One way to perform
this would be to put some initial data in one script (script 1 below) to define some internal
parameters that can be used in the transfer functions. The calculation of the transfer functions
can be put in the same script, or a separate script may be a better solution. (se script 2)
52(75)
User’s guide to Hopsan
A typical session would be to first execute DATA.HCOM and then execute FREQ.HCOM. Then
look at some Bode plots and realise that the gain is to large. Reduce it by typing GAIN =
GAIN/100. Then execute FREQ.HCOM to obtain a new set of transfer functions etc. It is of
course not necessary to make scripts for calculating transfer functions, it can however save
you from some typing.
A little warning - do not forget the command AMPH after a new transfer function has been
calculated if you want to make a Bode plot. This is necessary since the calculator only
calculate the real and imaginary parts, not amplitude and phase.
4.4 Scripts
EXEC [Filename [arg1] [arg2] ]
This command executes a script (a file with name ending with .HCOM). The filename is either
sent in the first argument or is interactively prompted for. It is also possible to start execution
of a script by giving only the filename (without extension) and necessary arguments. The
script can contain all commands used in HOPSAN, including exec. Some caution must be
taken when using exec in a script since each invocation requires some memory, it is therefore
possible to run out of memory if one nest many scripts.
There are some commands in HOPSAN that are useless in scripts. All commands that do not
take all arguments from the command-line are unwise to start from within a script. Examples
on such commands are: crdf, adjdf and crsd. See the list of commands in the end of this
chapter.
There are some additional commands that only can be used from within a script to control the
execution. These are: while, if () then...endif, goto statements.
4.4.1 Comments
# means that the rest of the line is a comment.
53(75)
User’s guide to Hopsan
4.4.2 Arguments to scripts
There is a mechanism for sending arguments to scripts, $1, $2 ... $9 is placeholders for
arguments. A $1 is substituted by the first argument following the filename, $2 with the
second, etc. It is also poosible to input the whole command line (excluding the command)
with $argv. Example on the use of arguments: The script foo.hcom have the following
content:
QAZ = $1**2
END
The script is started with the command foo p1 and results in a plotvariable qaz which is
p1**2
Assume that the script dtran.HCOM have the content shown in the program below
The command ‘dtran xe xp go‘then results in a plot of the transfer-function
4.4.3 Flow control
There are four statements for flow control: while, foreach, if and goto The syntax for a
while loop is:
while (condition)
:
repeat
Example:
while (i<10)
i=i+1
repeat
The foreach statement is practical for doing things with several plotvariables and parameters.
The first argument ( var) is a string variable which will be set to each expansion of the
second argument pattern in the commands between the foreach and the endforeach. The
syntax is:
foreach var pattern
:
endforeach
54(75)
User’s guide to Hopsan
A typical example is the following, which will print the average of a variable on screen, plot
the variable and save the plot as a EPS file with a filename as the variable with the extension
eps. This will be done for all variables beginning with a "p", e.g. p1:t.1,p1:t.3, p2:t.1....
foreach a p*:t.*
print "aver($a) = " ( aver( $a ))
chpv $(a)
epsf $(a).eps "Time" "$(a)"
endforeach
The IF statement is:
if (condition) then
:
[else]
:
endif
An alternative if statement
is:
if (condition) statement
where "statement" can be anything except a while or an if
The condition in the while and the if statements is an expression that evaluates to a scalar
value that can be zero or not zero. The value zero is considered as false, and any other value is
true. A possible condition would be max(p1) > 1e5 which is evaluated to 1 if it is true and 0
(zero) if the expression is false.
The goto statement is:
goto label
where label is a string of max 5 characters defined. The label is defined by putting an and sign
"\&" as the first character on a line followed by the name of the label. Example:
goto repa
:
&repa
repa datafile.dat;1
A label may be put on any line, but be careful. The safest is to put it on a line alone.
4.4.4 I/O on screen and on file
A special command is the print command. It prints the arguments on the screen. This can be
useful for debugging scripts and also for progress information. The arguments to print are
interpreted as:
print "delt" => delt
print "delt =" (delt) => delt = 1.e-3
print "delt/2 =" (delt/2) => delt = 0.5 e-3
One sees that if the argument is enclosed in double quotes it is printed as is. If it is enclosed in
parenthesis it is calculated and the result is printed.
There exists also a possibility to get the output on a file. This is accomplished by using the
fopen, fprint and fclose commands.
55(75)
User’s guide to Hopsan
fopen foo.out
fprint "delt =" (delt)
fclose
This will open a file (only one file at the time is possible) and then print the string delt =
on that file, and then close the file. The fopen command opens the file for writing in
append mode if the file exists.
1.00e-3
4.4.5 Debugging scripts
There is a flag cmdtrace which, if set, results in some extra information being dumped on the
screen. Before execution the script is printed on the screen with line-numbers on each line and
comments removed, labels substituted with the right line-number, dummy argument
substituted, etc. Each command is also echoed before it is executed, as Executing> command
4.4.6 Ending execution of scripts
There are two ways of ending the execution of a script; a jump to the last line, or a stop
command. A stop command ends the execution of the script. If the user wants to interrupt the
execution of a script from the keyboard it is possible by pressing `` Command-0'' . If this is
done during a simulation it is however necessary to press `` Command-0'' twice, once for
interrupting the simulation and a second time for interrupting the script. This way of
interrupting script may change! And is valid only for Macintosh
The last line of a script must consist of a single end statement, and a line-feed. Lines
following the end command are ignored.
4.4.7 Hints for writing scripts
When writing scripts there are several things to consider. If the script will do many
simulations, is it enough room in the memory for these? If not, it is necessary to delete the old
ones. This can easily be handled if the command ‘set delold‘ is in the beginning of the
script. The result of this command is that when a simulation is started and there isn't enough
room for the result the oldest generation is automatically deleted. This behaviour is the same
for all commands that will generate variables in a new version. It will not work for commands
that analyse old results, for instance FFT or TRAN. If one wants to be certain that HOPSAN
doesn't run out of memory the commands that removes plotvariables (‘nepl –f‘ or ‘rmvar’)
are also useful.
4.5 Hopsan commands
4.5.1 Data input
Since all simulations need some kind of numerical values on parameters this is an important
part of the simulation environment. There are a number of commands dealing with file
handling, changing parameter values etc.
56(75)
User’s guide to Hopsan
Maindata
File handling
CRDF - Create datafile.
This command will prompt for parameter values, startvalues and scale factors for
plotvariables and time limits for simulation.
Usage:CRDF accepts no arguments -- do not use in scripts
ADJDF - Adjust datafile.
Do this whenever PARAME or DYNVAR has been changed. If in doubt, do this
whenever the model has changed. Removes unused parameters/plotvariables and prompts
for new values on new ones. This command does not read the subdata files contained in
the main datafile. If you would prefer to incorporate them in the adjusted datafile -- use
REPA first. The new datafile is not saved until you explicitly save it!
Usage:ADJDF accepts no arguments -- do not use in scripts
REPA - Recover parameter from a file.
Load the specified datafile into memory. The subdata files contained in the file is also
loaded into memory. If no datafile is given on the command line, it prompts for a data file
to read.
Usage: repa [datafile]
SAPA - Save parameters to a file.
If no datafile is given on the command line, it saves with the same name with the version
count increased. Saves all subdata files in the main datafile if the option ``Save all data in
one file'' (SAVEALL) is set (using the SET command, or preferences in the menus)
Usage: sapa [datafile]
SAPAS - Save parameters to a file as a new file.
Prompts user for a new name on the datafile to save. The name can be specified with or
without extension. Otherwise same as SAPA command.
Usage: sapas datafile
Parameters
Parameters in the main datafile can be displayed and changed using either a dialogue box (on
PC) or with the following commands which can be accessed either through menus or with
command line. There is also the possibility to use the calculator (see ch. 4.3.9) to set
parameters. Please observe that no values are saved on disk until an explicit save command is
performed
CHPA - Change parameter.
Use this command to change values on parameters in the main datafile. Can handle
wildcards on parameter names.
Usage: chpa [parname parvalue [parname parvalue]...]
DIPA - Display parameter.
Shows a list with all (or selected) parameters.
Usage: dipa [par]
57(75)
User’s guide to Hopsan
Startvalues and scale factors in the datafile
CHSV - Change startvalue.
All plot variables has startvalues which are set before each simulation starts. This is the
command to change these.
Usage: chsv [parname parvalue]
DISV - Display startvalues.
Usage: disv [var]
SASV - Save endvalues as startvalues.
A command that saves the final results from a simulation as startvalues for the plot
variables. Practical if it is difficult to find correct start values for a given system. In that
case, we simulate with constant input signals and let the system find the steady state by
itself, and then give this command.
Usage: sasv
CHDFSC - Change datafilescaling for plot variables.
When variables are plotted they are first multiplied with this factor. A typical scale factor
for a pressure is 10e-6 which transforms the basic pressure unit Pa to the more suitable
MPa. This command sets the default scaling for plot variables. When a simulation is
started these default values are set for each plot variable. To change scaling for an existing
plotvariable, see the CHSC command.
Usage: chdfsc [parname parvalue]
DIDFSC - Display datafilescaling for plot variables.
Usage: didfsc [var]
Simulation settings
CHTI - Change time limits for simulation.
The simulation starts at the time TMIN. The results are being saved from the time TMINP
up to TMAX where the simulation ends. At most MAXNOS number of samples are saved.
If more are calculated these are interpolated to yield MAXNOS samples. There are also a
mode where the results are picked each second, each third etc. instead of using simulation.
This mode is set by SET MEASURE.
Usage: chti [tmin tminp tmax [maxnos]]
Subdata
This kind of parameters are typically local to a specific component. The component can use
subdata if they call a subroutine named PARINI. If the subdata file have been loaded earlier
these parameter values are used. This is typically done if the subdata file was packaged into a
main datafile. If the named subdata file cannot be found HOPSAN looks on disk for a file
with the extension ``.SDAT'' in the current directory. HOPSAN may also look in a directory
named ``compdata'' in the main HOPSAN directory.
File operations
CHLIB - Change simulation library.
Changes the fortran file where CRSD looks for components. The default value for the
58(75)
User’s guide to Hopsan
library is the standard library CLIB.F (or CLIB.FOR on PC's).
Usage: chlib [library-file-sourcecode]
CRSD - Create subdata file.
Asks for a name on a new subdatafile and what component it is used in. Looks for this
component in the Fortran file set by the command CHLIB and prompts the user for values
on the parameters.
Usage: crsd accepts no arguments -- do not use in scripts
RESD - Restore subdata parameters.
from the files they came from. Reverts all changes on subdata parameters not saved to
disk to the values saved to disk.
Usage: resd
Parameters
Parameters in the subdatafiles can be accessed through either a dialogue box (on PC) or with
the following commands. There is also the possibility to use the calculator (see chapter 4.3) to
set subdata parameters.
CHSD - Change sub data parameter.
Asks for a subdatafile, a parameter and a value for this parameter. If used with command
line arguments it is possible to set several parameters in several subdata files
simultaneously. For instance, if used as chsd * a1 1.0e-3 it will change parameters
named a1 in all subdata files to 1.0e-3. Another possibility is chsd valve* xvmax 5e-3
which would set all parameters named xvmax in the subdatafiles beginning with valve to
5e-3.
Usage: chsd [filename [parname parvalue]]
DISD - Display sub data parameter.
Lists the named subdatafile on screen with parameter names and values and possibly also
the comments for each parameter. Also possible to specify what subdata parameters to
display. For instance disd * a1 will show the parameter named a1 in each subdata file.
Usage: disd [subdatafile [parname]]
Using the calculator. To set the parameter A1 in the subdata file PISTON you could write
something like:
A1@PISTON = 1.5E-3
A1@PISTON = A2@PISTON
where the latter would set the value on A1 to the same value as A2 in the same subdata
file.
Log of changes in the datafiles
HOPSAN maintains a log of the commands that changes parameter- and startvalues. In this
log information is also saved telling when simulations are started, files are read and saved and
miscellaneous other commands needed to recreate a simulation experiment. The log is
maintained in a format which should possible to execute as a script. At most the last 100
changes are remembered.
59(75)
User’s guide to Hopsan
DIHI - Display parameter history.
Shows the most recent commands that change the state of the datafiles, currently all
commands that changes parameters and startvalues. The length of the log is restricted to
the last 100 changes.
Usage: dihi
WRHI - Write history on file.
Write the history on file, this file has the same format as a script file and it should
normally be possible to execute it as a script.
Usage: wrhi [filename]
4.5.2 Simulation, optimisation and frequency analysis
Simulation (in the time domain)
SIDY - Starts a time domain simulation.
Subroutine DYNMOD is called once at the beginning, then DYNCON is called none,
twice or four times every time step depending on the settings. DYNSAM is called once
every time step. DYNEND is called once after the last time step. It is on some platforms
possible to interrupt a simulation. On Macintosh this is done by pressing ``Command-0'',
on Unix by pressing ``Ctrl-Z''.
CONSIM - Continue simulation.
If the simulation is interrupted by use of the keyboard or with the ``StopFlag'' described in
the appendix ``Common blocks in HOPSAN'', it is possible to continue the simulation.
Never continue if the cause of the interrupt was an error. There are things we should not
do before continuation of an interrupted simulation. One sure way to cause a major error is
to change either the time step DELT, or the time limits, and then continue a simulation.
Optimisation
The command for starting the optimisation is OPTIM OPTFIL or just optim which causes
HOPSAN to prompt for a optimisation filename.
Frequency analysis
FFT - Frequency analysis using Fast Fourier Transform.
Computes the FFT of a specified variable. The result is put in a complex variable with the
same name as the input within the same generation of plot variables. A frequency variable
is also computed. When specifying the input variable it is possible to negate it with a
minus sign. The FFT can only be done on variables with samples. The analysed variable
should start and end on the same value, with steady state at beginning and end.
TRAN - Transfer function analysis.
Calculates the transfer function (using FFT) from the first specified variable (in the time
domain) to the second variable (also in the time domain) and puts the transfer function in a
complex variable with a specified name. It is only possible to calculate a transfer function
between variables belonging to the same generation.
FSERIE - Fourier series analysis.
Makes a numerical Fourier series analysis of a plot variable in the time domain. The result
60(75)
User’s guide to Hopsan
is put in a complex variable with the same name as the input within the same generation of
plot variables. The frequency and the harmonics numbers are also saved in variables
called ``Frequency'' and ``Harmonics'', both of type ``R''. Amplitude and phase are also
computed.
IFFT - Inverse Fast Fourier Transform.
IDFT - Inverse Discrete Fourier Transform.
4.5.3 Result handling
Other post processing
It is possible to use a fairly powerful scripting language to perform miscellaneous operations
on results. This is described in ch. 4.4.
File operations
There are several possible formats for result files.
·
The old format which only support time based results with one generation per file. The
file contains a small hreader with information on the number of varaiables and the
number of samples followed by space separated columns with the name of the
plotvariables at the top followed by the scale factor and then the actual data.
·
The new HOPSAN format support time based (real) variables, complex variables, and
unlimited number of generations per file. It starts with small header identifying the file
as a HOPSAN file followed by the plotvariables. The plotvariables are saved in a
single column with some identifying and size information as headers. This is the
recommended format to use.
·
The Matlab format supports the same features as the new Hopsan format, ie it can save
any number of generations and both complex and timebased variables. This under the
constraint that it is necessary to expand the variable names with type and generation.
For instance a time variable X2 in generation 2 is saved as X2_T_2 and a complex
variables with the same name is saved as X2_C_2. Saving is done with the command
SAMAT and reading is performed with REMAT. At present, only Matlabfiles with the
same byteorder as that of the current platform can be read. Ie files made on an Intel
machine can only be read on a Intel machine. The files must consist of vectors, not
matrices.
·
There also exist a write-only format where the data is saved in tab-delimited columns.
This format can be useful for exporting data to spreadsheet programs such as Excel.
The file contains a 5 lines header which in that case should deleted. These lines
consists of some info about the size of the file and the variables saved. These lines
begin with a ``#''. This enables the use of the graphing program Gnuplot without any
changes to the file. The format does not allow for variables with different length. The
saved results are truncated to the length of the shortest variable. The commands
handling this format are TSAPL and TABWRITE
61(75)
User’s guide to Hopsan
·
There also exists a format which only can handle frequency dependent (complex)
plotvariables. This format can only handle one variable per file and only save the real
and imaginary parts of the variable along with the frequency. The commands dealing
with this format are SAGF and REGF.
Saving results
SAPL - Save plot file.
Saves time based variables in a file with name xxx.PLO. The datafiles are appended to the
end of the plotfile. If no version is specified the last (*.l) version is saved. This file format
only supports time-based results, ie no complex variables.
Usage: sapl [plotfile [version-to-save]]
SAPL2 - Save plot file, new format.
Save variables in a file with name exactly as specified. Only the variables that are
specified are saved. This format can handle any number of generations and can save
timebased and complex variables. Only real and imaginary part of the complex variables
are saved.
Usage: sapl2 [plotfile variables-to-save]]
SAMAT - Save variables to a matlab file.
Max 4096 samples for Mac. No limits for PC and Unix. The variable name in Matlab is
the variable name in Hopsan with type and generation added as in: X_T_2 where X is a
time based variable of generation 2, X_C_2 where X is a complex variable (typically
frequency dependent). If -NOEXT is given the Matlab name is the Hopsan name only, it is
thus a bad idea to save several generations in the same file if -NOEXT is specified.
Usage: samat [-NOEXT] [filename var1 var2....]
SAGF - Save a frequency dependent variable on file.
Saves a frequency dependent (complex) variable to a file along with the frequency
variable. Only real and imaginary parts are saved along with the frequency.
Usage: sagf [cmplxvar freqfile]
TSAPL - Save plot file in tabdelimited file.
Saves time based variables in a file with name xxx.TAB. Saves a complete generation in a
file with tab-delimited columns. This is a write-only format, HOPSAN cannot read this
file.
Usage: tsapl [plotfile [version-to-save]]
TABWRITE - Save plot file in tabdelimited file.
Saves time based variables in a file with name xxx. Saves only the specified variables in a
file with tab-delimited columns. Can save any type of variables from any generation. The
columns are truncated to be of the shortest length of any variable specified. This is a writeonly format, HOPSAN cannot read this file.
Usage: tabwrite [plotfile [var-1 var-2 ... var-n]]
Recovering results
REPL - Read plot file.
The (optional) generation sets the generation of the variables in the plotfile. Existing
variables with that generation are replaced.
Usage: repl [plotfile [generation]]
62(75)
User’s guide to Hopsan
REPL2 - Read plot file, new format.
The (optional) generation sets the start generation of the variables in the plotfile. Consider,
for instance, a plotfile which contains varibles with generations 1 and 3. If ``generation'' is
specified as 2, the variables from the file will get generation numbers 2 and 4. If no
generation number is given the results will be put in the next generation. Existing
variables are replaced.
Usage: repl2 [plotfile [generation]]
REMAT - Read variables from a matlab file.
Max 4096 samples for Mac. No limits for PC and Unix. If the variables are saved with
generation numbers from Hopsan, the generation number from the file is added to the
generation specified or to the latest generation. If no generation number exists on variables
in file the results are put in the generation specified (or a new).
Usage:remat filename [generation-to-put-vars-in]
REGF - Restore a frequency dependent variable.
A new generation is created with the variable read from file and the frequency.
Usage: regf [freqfile]
Properties of result variables
CHSC - Change plot variable scalefactors.
Changes the scale factor for existing plot variables. The command CHDFSC changes the
default value.
Usage: chsc [varname scaling]
DISC - Display plot variable scalefactors.
This command takes a list of result variables and display the size, creator, scalefactor etc
for them.
Usage: disc [varname-1 varname-2 ... varname-n]
4.5.4 Graphs
Changing variables
CHPV - Change plot variable.
Prompts for plotvariables on right and left side of diagram
Usage:chpv [var1left var2left .. [-r var1right var2right ..]]
CHPVL - Change plot variable left axis.
Changes only the variables on the left side of the diagram.
Usage:chpvl [var1 var2 ...]
CHPVR - Change plot variable right axis.
Changes only the variables on the right side of the diagram.
Usage:chpvr [var1 var2 ...]
Changing limits
CHDL - Change diagram limits.
Sets the diagram limits and number of major grid points (kx, kyl,kyr). If any of the y-axis
63(75)
User’s guide to Hopsan
is to be changed the x-axis limit needs to be specified, Look below for commands that
change left or right axis. If the number of divisions is specified as 0 (zero) an autoscaling
is performed that sets the diagram limits so that the graphs utilise the diagram to a
maximum.
Usage:chdl [xmin xmax kx [ylmin ylmax kyl] [ylmin ylmax kyl]]
CHDLYL - Change diagram limits left y-axis.
Usage:chdlyl ylmin ylmax kyl
CHDLYR - Change diagram limits right y-axis.
Usage:chdlyr ylmin ylmax kyl
Misc graph commands
CHDS - Change diagram size.
Sets the diagram size in centimetres. The size specified is the size of the diagram without
the legends and axis. It may or may not change the size of the diagram on screen, it will
definitely change the diagram size on diagrams saved as Encapsulated Postscript files.
Usage:chds xsize ysize
CHPAT - Change pattern on lines.
SET LABEL - Add text to the diagram.
Puts a (short) label at the specified point in a diagram. As with SET ARROW the
coordinate system used is the x-axis and the left y-axis of the diagram.
Usage:SET LABEL no "Text" AT x y
Hardcopies
For PC and Macintosh there are two ways to get a graph on paper, either a machine dependent
format is used, MacPaint or PICT for Mac or a Windows bitmap for PCs. These formats are
not suitable for high quality diagrams. The other (and best) way is to use the two PostScript
commands described below since this produce high quality hardcopies which utilises the
higher resolution on a PostScript printer. The drawback using PostScript is that it is difficult
to manipulate the graphs afterwards, it is for instance normally not possible to use a drawing
program to add extra text to the graph. This must be handled in HOPSAN with the commands
SET ARROW and SET LABEL. Other drawbacks is that it is necessary to have access to a
Postscript printer (or a suitable converter program) to print the curves.
EPSF - Save diagram as Encapsulated Postscript File.
Saves the current graph as an Encapsulated Postscript File. This format is suitable for
inclusion in word processing documents and such. On PC and Unix no preview picture is
saved, which means that you can not see the graph on screen in, for instance, a Word
document. If the document is printed on a Postscript printer it will come out (hopefully).
Usage: epsf [filename [X-Label [Left Y-Label [Right Y-Label]]]]
POST - Save diagram as Postscript File.
This format is meant for sending to a Postscript printer. The graph is scaled to fill a A4
paper in landscape orientation regardless of any previous CHDS commands.
Usage: post [filename [X-Label [Left Y-Label [Right Y-Label]]]]
64(75)
User’s guide to Hopsan
4.5.5 Preferences
The behaviour of HOPSAN can be modified to some extent. The most important command
for that is set which has many different usages. The general syntax is: SET prefs value
There are two major types of settings; logical and numerical. For the logical there are only
two legal values: on or off. In the table below the logical settings and in the one after that, the
numerical settings are shown along with their default values. The SET command is also used
for setting labels in graphs. This is described in ch. 4.5.4.
Table: On/off settings.
65(75)
User’s guide to Hopsan
Table: Numeric settings.
4.6 Co-simulation
Hopsan has the possibility to communicate with other software using so called sockets. The
‘Listen’ command is then used to make Hopsan listen to a certain port on the computer as
specified as the argument to the mentioned command. Other software can establish a socket
connection to Hopsan after that and send normal commands and return answers in form of
strings. A number of special commands have been developed for this purpose that are faster
than usual. These are ‘Simdyn’, ‘Consimdyn’ and ‘Peekl’. ‘Simdyn’ initiates a simulation
with the start time as argument. ‘Consimdyn’ continues the simulation to another time that is
given as argument. The latter command is used repeatedly to make the simulation go step by
step. ‘Peekl’ gets the last value of the plotvariable that is given as argument. ‘Peekl’ does not
work in combination with ‘Sidy’.
Every time a simulation is performed, three files are written to the HopSim folder that deal
with co-simulation. ‘Inputs.int’ contains names (both alias and comments) on input variables
whose nodes are visible and not connected. ‘Outputs.int’ contains names and start values of
output variables whose nodes are visible and not connected. Finally ‘Simset.int’ contains the
latest time step used in the model, the computer name (could be empty this field) and the port
number that is probably used. The port number will always say ‘1000’ regardless of the
argument to the ‘Listen’ command, so it only works to use this if the default port number to
‘Listenl is used. The width of the names are the same so that some applications can read the
files easier.
Apart from the direct socket connection, calls to Hopsan can be made through the
HopSim.DLL file that is installed to the Windows system folder at the same time as Hopsan.
To declare the functions part of the DLL in a C program, write the following
extern int
APIENTRY Init(char *Host,int HostPort);
extern char* APIENTRY Send(char *command);
In Visual Basic, instead write
Private Declare Function Init Lib "HopSim.dll" Alias "_Init@8"
(ByVal Host As String, ByVal HostPort As Integer) As Integer
66(75)
User’s guide to Hopsan
Private Declare Function VBSend Lib "HopSim.dll" Alias “_VBSend@8”
(ByVal a As String, ByVal b As String) As Double
More information on how to use these functions can be found in the source code in the
‘Interfacing’ folder in the Hopsan installation. In short, the ‘Init’ function initiates the sockets
and the ‘Send’ command sends a normal Hopsan command with a ‘|’ character at the end and
returns a string with the answer that Hopsan normally would have output on the screen. The
‘VBSend’ command has the same principle but returns the Hopsan answer in the second
argument, which needs to be initiated to be a string filled with null characters. The source
code for the DLL file is found in ch. 5.3.
67(75)
User’s guide to Hopsan
5.Appendix
5.1 License agreement for the Lcc-Win32 C-compiler
The authors of this software are Christopher W. Fraser, David R. Hanson, and Jacob Navia.
Christopher Fraser and David Hanson wrote the original lcc compiler. Jacob Navia has added several
enhancements to the sources, and wrote all the rest of the compiler system: assembler, linker,
resource compiler, editor, debugger, etc.
The copyright is then shared between two holders:
1. The original lcc compiler's copyright (Addison Wesley)
2. The compiler system/lcc enhancements copyright (Jacob Navia)
Permission to use, and modify this software for any purpose, subject to the provisions described
below, without fee is hereby granted, provided that this entire notice is included in all copies of any
software that is or includes a copy or modification of this software and in all copies of the supporting
documentation for such software.
THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR AT&T MAKE ANY
REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY OF
THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
lcc is not public-domain software, shareware, and it is not protected by a `copyleft' agreement, like the
code from the Free Software Foundation.
lcc is available free for your personal research and instructional use under the `fair use' provisions of
the copyright law.
You may not sell lcc or any product derived from it in which it is a significant part of the value of the
product. Using the lcc front end to build a C syntax checker is an example of this kind of product.
Note for CDROM vendors: Including lcc-win32 in a CD needs explicit agreement from the authors. You
may NOT include lcc-win32 in a CDROM or in other products that will be sold without explicit
agreement from the authors.
Programs compiled with lcc-win32 remain the property of their authors. They can be sold without any
obligations to the authors of lcc-win32. All this copyright statement applies only to lcc-win32, NOT to
the programs compiled with it.
For more information concerning the licenses for the system contact
Jacob Navia
Logiciels/Informatique
41 rue Maurice Ravel
93430 Villetaneuse
France
Tel: 33-1-48-23-51-44
----Chris Fraser / [email protected]
David Hanson / [email protected]
Jacob Navia / [email protected]
68(75)
User’s guide to Hopsan
5.2 Node information
Hydraulic
Hydraulic variables
p
Pressure
q
Flow
c
Characteristic, q to p
Zc
Characteristic impedance
Thyd
Temperature
dQhyd
Heat flow
Hydraulic nodes
HydraulicQNodes
HydraulicCNodes
HydraulicWNodes
HydraulicSenseNodes
Pneumatic
Pneumatic variables
pgas
Pressure
qmgas
Mass flow
cgas
Characteristic, dotE to pgas
Zcgas
Characteristic impedance
Tgas
Temperature
dEgas
Energy flow
Pneumatic nodes
PneumaticQNodes
PneumaticCNodes
PneumaticWNodes
PneumaticSenseNodes
69(75)
User’s guide to Hopsan
Mechanic linear 1-D
Mechanic variables
f
Force
x
Position
sx
Speed
cx
Characteristic sx to f
Zx
Characteristic impedance
Mechanics nodes
MechanicQNodes
MechanicCNodes
MechanicWNodes
MechanicSenseNodes
Mechanic Rotation 1-D
Mechanic rotation variables
Mrot
Moment
Thetarot
Angle
dThetarot
Rot. speed
crot
Moment characteristic, dotThetarot to Mrot
ZThetarot
Characteristic impedance
Mechanic rotation nodes
MechanicRotQNodes
MechanicRotCNodes
MechanicRotWNodes
MechanicRotSenseNodes
70(75)
User’s guide to Hopsan
Electric
Electric variables
Uel
Voltage
Iel
Current
cel
Characteristic, Iel to Uel
Zcel
Characteristic impedance
Electric nodes
ElectricQNodes
ElectricCNodes
ElectricWNodes
ElectricSenseNodes
Electric AC
This is nodes for alternate current (ac) nodes for use in systems where the alternating
frequency is high compared to other system dynamics.
Electric AC variables
Uelac
Effective Voltage
Ielac
Effective Current
welac
frequency
celac
Characteristic, Ielac to Uelac
Zcelac
Characteristic impedance
Electric AC nodes
ElectricACQNodes
ElectricACCNodes
ElectricACWNodes
ElectricACSenseNodes
71(75)
User’s guide to Hopsan
Magnetic Nodes
Magnetic variables
ThetamagX, ThetamagY
PsimagX, PsimagY
cmagX, cmaxY
Characteristic
ZmagX, ZmagY
Characteristic impedance
Magnetic nodes
MagneticQNodes
MagneticCNodes
MagneticWNode
MagneticSenseNodes
Thermal
Thermal variables
Th
Temperature
dQth
Heat flow
cth
Characteristic, dotQh to Th
Zcqth
Characteristic impedance
Thermal nodes
ThermalQNodes
ThermalCNodes
ThermalWNodes
ThermalSenseNodes
72(75)
User’s guide to Hopsan
5.3 The C source code for HopSim.DLL
/* --- The following code comes from d:\programs\lcc\lib\wizard\dll.tpl. */
#include <windows.h>
#include <string.h>
#include <stdio.h>
#include <winsock.h>
WORD version = MAKEWORD(1,1);
WSADATA wsaData;
int nRet;
// Get information about the server
LPHOSTENT lpHostEntry;
// Create client socket
SOCKET theSocket;
// Fill an address struct with the server's location
SOCKADDR_IN saServer;
int firstCall=1;
__declspec(dllexport) __stdcall int APIENTRY Init(char* Host,int HostPort) {
if (firstCall==1){
// Init Winsock
WSAStartup(version, &wsaData);
lpHostEntry = gethostbyname(Host);
if (lpHostEntry == NULL) {
//printf("Error at gethostbyname()");
//return 0;
}
theSocket = socket(AF_INET,
SOCK_STREAM,
IPPROTO_TCP);
if (theSocket == INVALID_SOCKET) {
//printf("Error at socket()");
//return 0;
}
// Go over TCP/IP
// Socket type
// Protocol
saServer.sin_family = AF_INET;
saServer.sin_addr = *((LPIN_ADDR)*lpHostEntry->h_addr_list);
// ^ Address of the server
saServer.sin_port = htons(HostPort);
// Connect to the specified address and port
nRet = connect(theSocket,
(LPSOCKADDR)&saServer,
// Server address
sizeof(struct sockaddr));
// Length of address structure
if (nRet == SOCKET_ERROR) {
//printf("Error at connect()");
//return 0;
}
}
firstCall=-1;
return 0;
}
__declspec(dllexport) __stdcall APIENTRY char* Send(char *f) {
nRet = send(theSocket,
// Pretend this is connected
f,
// Our string buffer
strlen(f),
// Length of the data in the buffer
0);
// Most often is 0, but see end of tutorial for options
if (nRet == SOCKET_ERROR) {
//printf("Error on send()");
return "-1.0";
}
char myBuf[1000];
nRet = recv(theSocket,
// Pretend this is connected
myBuf,
// Our string buffer
sizeof(myBuf), // Length of the data in the buffer
0);
// Most often is 0, but see end of tutorial for options
if (nRet == SOCKET_ERROR) {
//printf("Error on send()");
return "-1.0";
}
char *Test;
Test=calloc(strlen(myBuf),sizeof(char));
strcpy(Test,myBuf);
return Test;
}
73(75)
User’s guide to Hopsan
__declspec(dllexport) __stdcall APIENTRY double VBSend(char *f, char * f2) {
nRet = send(theSocket,
// Pretend this is connected
f,
// Our string buffer
strlen(f),
// Length of the data in the buffer
0);
// Most often is 0, but see end of tutorial for options
if (nRet == SOCKET_ERROR) {
//printf("Error on send()");
return -1.0;
}
char myBuf[1000];
nRet = recv(theSocket,
// Pretend this is connected
myBuf,
// Our string buffer
sizeof(myBuf), // Length of the data in the buffer
0);
// Most often is 0, but see end of tutorial for options
if (nRet == SOCKET_ERROR) {
//printf("Error on send()");
return -1.0;
}
strcpy(f2,myBuf);
return 1.0;
}
/*-----------------------------------------------------------------------Procedure:
LibMain ID:1
Purpose:
Dll entry point.Called when a dll is loaded or
unloaded by a process, and when new threads are
created or destroyed.
Input:
hDllInst: Instance handle of the dll
fdwReason: event: attach/detach
lpvReserved: not used
Output:
The return value is used only when the fdwReason is
DLL_PROCESS_ATTACH. True means that the dll has
sucesfully loaded, False means that the dll is unable
to initialize and should be unloaded immediately.
Errors:
------------------------------------------------------------------------*/
BOOL WINAPI LibMain(HINSTANCE hDLLInst, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
// The DLL is being loaded for the first time by a given process.
// Perform per-process initialization here. If the initialization
// is successful, return TRUE; if unsuccessful, return FALSE.
break;
case DLL_PROCESS_DETACH:
// The DLL is being unloaded by a given process. Do any
// per-process clean up here, such as undoing what was done in
// DLL_PROCESS_ATTACH. The return value is ignored.
closesocket(theSocket);
// Shutdown Winsock
WSACleanup();
break;
case DLL_THREAD_ATTACH:
// A thread is being created in a process that has already loaded
// this DLL. Perform any per-thread initialization here. The
// return value is ignored.
break;
case DLL_THREAD_DETACH:
// A thread is exiting cleanly in a process that has already
// loaded this DLL. Perform any per-thread clean up here. The
// return value is ignored.
break;
}
return TRUE;
}
74(75)