Hopsan
HCOM Scripting

HCOM is the built-in scripting language in Hopsan. It can control most parts of the program, either from the terminal widget or through external script files. Use the help command to list all available commands or help <command> to get help for a specific command.

Control Flow

When HCOM scripts are loaded from a file, multi-line control flow can be used

If statements

You can use if statements, with one optional else clause.

if( condition_expression )
  .
  .
[else]
  .
  .
endif

Example: Assign b = 1 if a is greater then 4, else assign b = 0

a = 5
if( a > 4 )
  b = 1
else
  b = 0
endif

While loops

You can use a while loop to repeat an expression until the condition is fulfilled

while (condition)
  .
  .
repeat

Example: Loop an expression five times, in this case summing the five first elements from a data vector

sum = 0
i = 0
while (i < 5)
  sum = sum + peek(data_vector, i)
  i = i+1
repeat

Foreach loops

You can use foreach to loop over multiple plot variables matching a filter_pattern Each resolved plot variable name will end up in the loop variable 'var'. Use $var to resolve the matched plot variable name Note! This function only works with plot variables right now

foreach var filter_pattern
  .
  .
endforeach

Example: Take the sum of the average value from all plot variables matching the pattern Step*.out.y

sum = 0
foreach v Step*.out.y
  sum = sum + aver($v)
endforeach

Simulation Commands

sim

Simulates current model (or all open models)
Usage: sim
Usage: sim all
Usage: sim -loadstate file
Usage: sim -loadsv file
-loadsv will load start values from a saved simulation state file
-loadstate will do the same but also offset the simulation time

chss

Change simulation settings
Usage: chss [starttime] [timestep] [stoptime] [samples]
Usage: chss [starttime] [timestep] [stoptime]

chts

Change time step of sub-component
Usage: chts [component] [timestep]

ints

Inherit time step of sub-component from system time step
Usage: ints [component]

Plot Commands

chpv

Change plot variables in current plot
Usage: chpv [leftvar1{s,c,t} leftvar2{s,c,t} ...] -r [rightvar1{s,c,t} rightvar2{s,c,t} ... ]
Usage: chpv [leftvar1{s,c,t} leftvar2{s,c,t} ...]
Usage: chpv -r [rightvar1{s,c,t} rightvar2{s,c,t} ... ]

Line appearance (optional):
Style (s): 1 = solid, 2 = dotted, 3 = dashed, 4 = dash-dotted
Color (c): red, darkblue, lightgreen...
Thickness (t): Thickness of line (integer value)
Symbol (y): 1 = cross, 2 = ellipse, 3=xcross, 4=triangle...

Example:
>> chpv Pump.P1.p -r Pump.P1.q{2,blue,2}

adpv

Add plot variables in current plot
Usage: adpv [leftvar1{s,c,t} leftvar2{s,c,t} ...] -r [rightvar1{s,c,t} rightvar2{s,c,t} ... ]
Usage: adpv [leftvar1{s,c,t} leftvar2{s,c,t} ...]
Usage: adpv -r [rightvar1{s,c,t} rightvar2{s,c,t} ... ]

Line appearance (optional):
Style (s): 1 = solid, 2 = dotted, 3 = dashed, 4 = dash-dotted
Color (c): red, darkblue, lightgreen...
Thickness (t): Thickness of line (integer value)
Symbol (y): 1 = cross, 2 = ellipse, 3=xcross, 4=triangle...

Example:
>> adpv Pump.P1.p -r Pump.P1.q{2,blue,2}

adpvl

Adds plot variables on left axis in current plot
Usage: adpvl [var1{s,c,t} var2{s,c,t} ... ]

Line appearance (optional):
Style (s): 1 = solid, 2 = dotted, 3 = dashed, 4 = dash-dotted
Color (c): red, darkblue, lightgreen...
Thickness (t): Thickness of line (integer value)
Symbol (y): 1 = cross, 2 = ellipse, 3=xcross, 4=triangle...

Example:
>> adpvl Pump.P1.p Pump.P1.q{2,blue,2}

adpvr

Adds plot variables on right axis in current plot
Usage: adpvr [var1{s,c,t} var2{s,c,t} ... ]

Line appearance (optional):
Style (s): 1 = solid, 2 = dotted, 3 = dashed, 4 = dash-dotted
Color (c): red, darkblue, lightgreen...
Thickness (t): Thickness of line (integer value)
Symbol (y): 1 = cross, 2 = ellipse, 3=xcross, 4=triangle...

Example:
>> adpvl Pump.P1.p Pump.P1.q{2,blue,2}

chds

Change diagram size (and position)
Usage: chds [width] [height]
Usage: chds [x] [y] [width] [height]

chdl

Change (and lock) diagram limits in the current plot
Usage: chdl [xLow] [xHigh]
Usage: chdl [xLow] [xHigh] [xTicks]
Usage: chdl [xLow] [xHigh] [xTicks] [ylLow] [ylHigh] [ylTicks]
Usage: chdl [xLow] [xHigh] [xTicks] [ylLow] [ylHigh] [ylTicks] [yrLow] [yrHigh] [yrTicks]
Usage: chdl reset

chdlyl

Change (and lock) diagram left y-axis limits in the current plot
Usage: chdlyl [ylLow] [ylHigh]
Usage: chdlyl [ylLow] [ylHigh] [ylTicks]
Usage: chdlyl reset

chdlyr

Change (and lock) diagram right y-axis limits in the current plot
Usage: chdlyr [yrLow] [yrHigh]
Usage: chdlyr [yrLow] [yrHigh] [yrTicks]
Usage: chdlyr reset

logx

Turn on and off logarithmic x-axis scale
Usage: logx on
Usage: logx off

logyl

Turn on and off logarithmic left y-axis scale
Usage: logyl on
Usage: logyl off

logyr

Turn on and off logarithmic right y-axis scale
Usage: logyr on
Usage: logyr off

sapw

Save the current plotwinow as an image
Usage: sapw [fileName.ext] [width] [height] [dimUnit] [dpi]
Usage: sapw [fileName.ext] [width] [height] [dimUnit]
Usage: sapw [fileName.ext] [width] [height] Pixels size
Usage: sapw [fileName.ext] Use screen size
ext: png, pdf, svg, ps, jpeg
dimUnit: px, mm, cm, in
'dpi' (actually pixels/inch) is ignored for vector formats or when dimunit is 'px' (pixels)

chpw

Changes current terminal plot window
Usage: chpw [name]

dipw

Displays current terminal plot window
Usage: dipw [no arguments]

chpvl

Changes plot variables on left axis in current plot
Usage: chpvl [var1{s,c,t} var2{s,c,t} ... ]

Line appearance (optional):
Style (s): 1 = solid, 2 = dotted, 3 = dashed, 4 = dash-dotted
Color (c): red, darkblue, lightgreen...
Thickness (t): Thickness of line (integer value)
Symbol (y): 1 = cross, 2 = ellipse, 3=xcross, 4=triangle...

Example:
>> chpvl Pump.P1.p Pump.P1.q{2,blue,2}

chpvr

Changes plot variables on right axis in current plot
Usage: chpvr [var1{s,c,t} var2{s,c,t,y} ... ] Line appearance (optional):
Style (s): 1 = solid, 2 = dotted, 3 = dashed, 4 = dash-dotted
Color (c): red, darkblue, lightgreen...
Thickness (t): Thickness of line (integer value)
Symbol (y): 1 = cross, 2 = ellipse, 3=xcross, 4=triangle...

Example:
>> chpvr Pump.P1.p Pump.P1.q{2,blue,2}

chpvx

Changes xdata plot variable in current plot
Usage: chpvx [varname]
Usage: chpvx -c Clear Custom x-data

chto

Change time plot offset for the current or specified generation
Usage: chto [offset] [generation]
Time offset should be given in the unit selected as the default time unit
The generation specifier is optional, you can use c,a,*,h,l specifiers

dito

Display time plot offset of specified generation
Usage: dito [generation]
Time offset will be shown in the chose default time unit
The "ans" variable will be offset in seconds (the base unit)

sapl

Save log variables to file. Filename suffix determins format
Usage: sapl [filepath] [-flags] [variables]
Flags (optional):
-csv Force CSV format
-plo Force PLO format
-h5 Force H5 (HDF5) format

repl

Loads plot files from .csv or .plo
Usage: repl [-flags] [filepath]
Flags (optional):
-csv Force CSV (, or ;) format
-ssp Force CSV (space separated) format
-plo Force PLO format

bode

Creates a bode plot from specified curves
Usage: bode [invar] [outvar] [maxfreq] [windowfunction] [mintime] [maxtime]

nyquist

Creates a Nyquist plot from specified curves
Usage: nyquist [invar] [outvar]

lock

Locks or unlocks all axes in current plot window
Usage: lock [flag] [on/off]
See also: lockyl, lockyr, lockr

lockyl

Locks or unlocks left y-axis in current plot window
Usage: lockyl [on/off]
See also: lock, lockyr, lockr

lockyr

Locks or unlocks right y-axis in current plot window
Usage: lockyr [on/off]
See also: lock, lockyl, lockr

lockx

Locks or unlocks x-axis in current plot window
Usage: lockx [on/off]
See also: lock, lockyl, lockyr

Parameter Commands

dipa

Display parameter value
Usage: dipa
Usage: dipa [parameter]
Usage: dipa [parameter] [condition]

Example: Display all parameters starting with "Mass" and a value greater than 10:
>> dipa Mass* >10

adpa

Add (system) parameter
Usage: adpa [parameter] [value]

chpa

Change parameter value
Usage: chpa [parameter] [value]

sapa

Save model or component parameter values to XML file (.hpf)
Usage: sapa [filepath]
Usage: sapa [filepath] [componentname]
Usage: sapa [filepath] [-c]
Flag -c for current visible system

repa

Load model or component parameters values from XML file (.hpf)
Usage: repa [filepath]
Usage: repa [filepath] [componentname]
Usage: repa [filepath] [-c]
Flag -c for current visible system

File Commands

exec

Executes a script file
Usage: exec [filepath]

wrhi

Writes history to file
Usage: wrhi [filepath]

wrtf

Writes text string to file
Usage: wrtf [-flag] [filepath] ["string"]
Flags (optional):
-a Append at end of file
-e Erase existing contents before writing
Variables can be written by putting them in dollar signs.
Example:
>> wrtf -a output.txt "x=$x$"

pwd

Displays present working directory
Usage: pwd [no arguments]

mwd

Displays working directory of current model
Usage: mwd [no arguments]

cd

Changes present working directory
Path may be relative or absolute and must be contained withing quotes " " if it contains spaces
Usage: cd [directory]
Usage: cd -mwd Switch to current model working directory

mkdir

Creates directory and all parent directories
Path may be relative or absolute and must be contained withing quotes " " if it contains spaces
Usage: mkdir [path]

ls

List files in current directory
Usage: ls Usage: ls [wildcard]

edit

Open file in external editor
Usage: edit [filepath]

Variable Commands

disp

Shows a list of all variables matching specified name filter (using asterisks)
Usage: disp [filter]

peek

Shows the value at a specified index in a specified data variable
Usage: peek [variable] [index]

poke

Changes the value at a specified index in a specified data variable
Usage: poke [variable] [index] [newvalue]

alias

Defines an alias for a variable
Usage: alias [variable] [alias]

rmvar

Removes specified variable
Usage: rmvar [variables]
Usage: rmvar [variables] -n [variables]
Flags (optional):
-n Exclude specified variables -noalias Exclude all alias variables

dihg

Display highest generation
Usage: dihg

sequ

Set quantity on specified variable(s)
Usage: sequ [variable] [quantityname]
Usage: sequ [variable] -
The second example clears the quantity

ivpv

Toggle invert plot of specified variable
Usage: ivpv [variable]

sepl

Set plot label
Usage: sepl [variable] [label]

dlog

Disables logging in specified ports
Usage: dlog [ports]

elog

Enables logging in specified ports
Usage: elog [ports]

Model Commands

dico

Display components Usage: dico
Usage: dico [component]

Example: Display all components starting with "x":
>> dico x*

load

Loads a model file
Usage: load [filepath]

revert

Revert the current model
Usage: revert

loadr

Loads most recent model file
Usage: loadr [no arguments]

save

Saves current model
Usage: save
Usage: save [filepath]
If no file path is specified, current model file is overwritten.

reco

Renames a component
Usage: reco [oldname] [newname]

rmco

Removes specified component(s)
Usage: rmco [component]

chtab

Changes current model tab
Usage: chtab [index]

adco

Adds a new component to current model
Usage: adco [typename] [name] -a [x-coord] [y-coord] [rot-angel]
Usage: adco [typename] [name] -e [other] [east-offset] [rot-angel]
Usage: adco [typename] [name] -w [other] [west-offset] [rot-angel]
Usage: adco [typename] [name] -n [other] [north-offset] [rot-angel]
Usage: adco [typename] [name] -s [other] [south-offset] [rot-angel]

rpco

Replaces a component with a different type
Usage: rpco [name] [typename]

coco

Connect components in current model
Usage: coco [comp1] [port1] [comp2] [port2]

unco

List unconnected ports in current model
Usage: unco [wildcard]

crmo

Creates a new model
Usage: crmo [no arguments]

Other Commands

help

Shows help information
Usage: help [command]

info

Show information about specified variable
Usage: info [variable]

exit

Exits the program
Usage: exit [no arguments]

print

Prints arguments on the screen
Usage: print [-flag] ["string"]
Usage: print [-flag] [expression]
Flags (optional):
-i Info message
-w Warning message
-e Error message
Variables can be included in strings by putting them in dollar signs.
Example:
>> print -w "x=$x$"
Warning: x=12

eval

Evaluate string expression
Usage: eval ["expression"]
Variable evaluation can be included by putting them within dollar signs
Example:
>> eval "chpv Gain$i$.out.y"

set

Sets Hopsan preferences
Usage: set [preference] [value]
Available preferences:
multicore [on/off]
threads [number]
cachetodisk [on/off]
generationlimit [number]
samples [number]
undo [on/off]
backup [on/off]
progressbar [on/off]
progressbarstep [number]

get

Shows current Hopsan preferences
Usage: get [preference]
No argument prints all preferences.
Available preferences:
multicore
threads
cachetodisk
generationlimit
samples
undo
backup
progressbar
progressbarstep

close

Closes current model
Usage: close Usage: close all

fmu

Exports current model to Functional Mockup Unit (FMU)
Usage: fmu [path]

opt

Initialize an optimization
Usage: opt [algorithm] [partype] [parnum] [parmin] [parmax] -flags]
Algorithms: Flags:
complex alpha

call

Calls a pre-defined function
Usage: call [funcname]

echo

Sets terminal output on or off
Usage: echo [on/off]

semt

Change mutli-trheading settings
Usage: semt [on/off] [numThreads] [algorithm]
Usage: semt [on/off] [numThreads]

sleep

Pause execution for a number of seconds
Usage: sleep [seconds]
The sleep argument has millisecond accuracy

Local Functions

abs()

The absolute value of each vector element
Usage: abs(vector)

ans()

Returns the answer from the previous computation
Usage: ans()

aver()

Calculate average value of vector
Usage: aver(vector)

bdf1()

Transforms derivatives in a symbolic expression using the first order backward differentiation formula (implicit Euler)
Usage: e = bdf1(f)

bdf2()

Transforms derivatives in a symbolic expression using the second order backward differentiation formula
Usage: e = bdf2(f)

ceil()

Rounds the value of each vector element to the smallest integer larger than the value
Usage: ceil(vector)

cut()

Removes all samples x[i] for which y[i]<0.5
Usage: cut(x, y)

ddt()

Differentiates vector with respect to time (or to custom vector)
Usage: ddt(vector)
Usage: ddt(vector, timevector)

der()

Differentiates a symbolic expression with respect to another one
Usage: e = der(f1,f2)

eq()

Index-wise fuzzy equal check between vectors and/or scalars (equivalent to "==" operator)
Usage: eq(varName, threshold, eps)
Usage: eq(var1, var2, eps)

esd()

Generates energy spectral density from vector
Usage: esd(vector, [timevector], windowing, [mintime], [maxtime])

euler()

Transforms derivatives in a symbolic expression using the forward Euler method
Usage: e = euler(f)

eval

Evaluates a symbolic expression using local variables
Usage: y = expr(f)

exists()

Returns whether or not specified component exists in model
Usage: exists(name)

expand()

Expands all parentheses in a symbolic expression
Usage: e = expand(f)

expandPowers()

Expands all powers in a symbolic expression to multiplications
Usage: e = expandPowers(f)

expr()

Defines a new symbolic expression
Usage: e = expr(...)

factor()

Factors a symbolic expression with respect to another one
Usage: e = factor(f1,f2)

fc()

Fuzzy compare, returns 1 if the values of the arguments are almost the same
Usage: fc(expr, expr, tolerance)

fd()

Converts variable to frequency domain.
Usage: y = fd(x)

fft()

Generates frequency spectrum plot from vector (deprecated)
Usage: fft(vector, type, windowing, [min], [max])
Usage: fft(vector, [timevector], type, windowing, [min], [max])

floor()

Rounds the value of each vector element to the largest integer smaller than the value
Usage: floor(vector)

gt()

Index-wise greater than check between vectors and/or scalars (equivalent to ">" operator)
Usage: gt(varName, threshold)
Usage: gt(var1, var2)

hg()

Returns highest generation number
Usage: hg()

imax()

Calculate index of maximum value of vector
Usage: imax(vector)

imin()

Calculate index of minimum value of vector
Usage: imin(vector)

int()

Integrates vector with respect to time (or to custom vector)
Usage: int(vector)
Usage: int(vector, timevector)

latex()

Prints a symbolic expression with LaTeX syntax
Usage: latex(e)

left()

Returns the left-hand side of a SymHop equation
Usage: e = left(f)

linearize()

Linearizes a SymHop equation by multiplying with all divisors
Usage: e = linearize(f)

linspace()

Linearly spaced vector
Usage: linspace(min, max, numSamples)

logspace()

Logarithmicly spaced vector
Usage: logspace(min, max, numSamples)

lp1()

Applies low-pass filter of first degree to vector
Usage: lp1(vector, frequency)
Usage: lp1(vector, timevector, frequency)

lt()

Index-wise less than check between vectors and/or scalars (equivalent to "<" operator)
Usage: lt(varName, threshold)
Usage: lt(var1,var2)

max()

Calculate maximum value of vector
Usage:max(vector)

maxof()

Returns the element-wise maximum values of x and y vectors
Usage: maxof(x,y)

maxpar()

Returns the maximum value of specified parameter for specified component type
Usage: maxpar(type,par)

min()

Calculate minimum value of vector
Usage: min(vector)

minof()

Returns the element-wise minimum values of x and y vectors
Usage: minof(x,y)

minpar()

Returns the minimum value of specified parameter for specified component type
Usage: minpar(type,par)

obj()

Returns optimization objective function value with specified index
Usage: obj(idx)

ones()

Create a vector of ones
Usage: ones(size)

optpar()

Returns specified optimization parameter
Usage: optpar(idx)

optvar()

Returns specified optimization variable
Usage: optvar(idx)

peek

Returns vector value at specified index
Usage: peek(vector, idx)

psd()

Generates power spectral density from vector
Usage: psd(vector, [timevector], windowing, [mintime], [maxtime])

rand()

Generates a random value between 0 and 1
Usage: rand()

removeDivisors()

Removes all divisors in a symbolic expression
Usage: e = removeDivisors(f)

right()

Returns the right-hand side of a SymHop equation
Usage: e = right(f)

rms()

Computes the root mean square of given vector
Usage: rms(vector)

rmsd()

Generates root mean square spectral density from vector
Usage: rmsd(vector, [timevector], windowing, [mintime], [maxtime])

round()

Rounds the value of each vector element to closest integer value
Usage: round(vector)

simplify()

Simplifies a symbolic expression
Usage: e = simplify(f)

size()

Calculate the size of a vector
Usage: size(vector)

ssi()

Identifies steady-state for specified variable
Usage: ssi(vector, method, arguments)
Method 0 (rectangular window):
ssi(vector, 0, tolerance, windowlength)
Method 1 (ratio of differently estimated variances):
ssi(vector, 1, tolerance, windowlength, noiseamplitude
Method 2 (ratio of differently estimated variances using weighted moving average):
ssi(vector, 2, tolerance, lambda1, lambda2, lambda3, noiseamplitude)

td()

Converts variable to time domain.
Usage: y = td(x)

time()

Returns last simulation time
Usage: time()

trapezoid()

Transforms derivatives in a symbolic expression using the trapezoid method
Usage: e = trapezoid(f)

vector()

Create a vector with specified values
Usage: vector(1,2,3,4,5,6,...)

x()

Returns the X-vector of the specified variable.
Usage: x(vector)

zeros()

Create a vector of zeros
Usage: zeros(size)