File size: 9,213 Bytes
5a600cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#!/bin/sh
#------------------------------------------------------------------------------
# =========                 |
# \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
#  \\    /   O peration     | Website:  https://openfoam.org
#   \\  /    A nd           | Copyright (C) 2015-2025 OpenFOAM Foundation
#    \\/     M anipulation  |
#------------------------------------------------------------------------------
# License
#     This file is part of OpenFOAM.
#
#     OpenFOAM is free software: you can redistribute it and/or modify it
#     under the terms of the GNU General Public License as published by
#     the Free Software Foundation, either version 3 of the License, or
#     (at your option) any later version.
#
#     OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
#     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
#     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
#     for more details.
#
#     You should have received a copy of the GNU General Public License
#     along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.
#
# Script
#     foamMonitor
#
# Description
#     Displays graphs to monitor data from files written by OpenFOAM, e.g.
#     by functionObjects. Requires gnuplot to be installed.
#
#------------------------------------------------------------------------------

usage() {
    cat<<USAGE

Usage: ${0##*/} [OPTION] <file>
options:
  -ascii    | -a         show the graph by printing ascii in the terminal
  -columns  | -c <cols>  display specified columns, comma-separated, e.g. "2,4"
  -flip     | -f         plot data on x-axis, independent variable on y-axis
  -help     | -h         print the usage
  -logscale | -l         plots data (y-axis) on log scale, e.g. for residuals
  -once     | -o         print a graph one time without refreshing
  -refresh  | -r <time>  refreshes display every <time> sec (default 10s)
  -size     | -s <size>  set the size of the output plot, format "640,480"
  -title    | -t <title> set the graph title (default "Data Monitoring")
  -yrange   | -y <range> sets data (y-axis) range, format "[0:1]"

Displays graphs to monitor data from files written by OpenFOAM, e.g. by
functionObjects. Requires gnuplot to be installed.

Graphs are plotted from column data files written by OpenFOAM, where column 1 is
the independent variable, e.g. time, plotted on the horizontal axis by default.
The other columns are the dependent data, plotted on the vertical axis by
default. The data can be plotted within a specified range, using the '-r' option
and/or on a log scale using the '-l' option. The default axes can be flipped by
the '-f' option (with data plotted on the horizontal axis).

In standard monitoring mode, graphs are refreshed (default: every 10s).
Graphs can also be printed one time without refreshing using the '-o' option.

Examples:
+ Monitor residuals on a log scale, running in background ('&')
    foamMonitor -l postProcessing/residuals/0/residuals.dat &
+ Monitor probed pressure values from column 2, also in background
    foamMonitor -c 2 postProcessing/probes/0/p &
+ Plot force coefficients from column 3 once, e.g. after the simulation stops
    foamMonitor -o -c 3 postProcessing/forces/0/forceCoeffs.dat

USAGE
}

error() {
    exec 1>&2
    while [ "$#" -ge 1 ]; do echo "$1"; shift; done
    usage
    exit 1
}

howMany() ( echo "$1" | awk '{ print NF }' )

isInt() {
    [ "$1" -eq "$1" ] 2> /dev/null
}

flip() {
    [ "$AXIS" = y ] && echo "$1" && return 0
    echo "$1" | awk -F: '{print $2 ":" $1}'
}

# Check gnuplot is installed
command -v gnuplot >/dev/null 2>&1 || error "Gnuplot not installed"

# Variables used globally
AXIS="y"

# Variables used locally
term="$(echo show term | gnuplot 2>&1 | sed -n \
's/[ ]\+terminal type is \([^ ]\+\) .*/\1/p') \
 1 linewidth 1.5 noraise"
size="default"
logscale="no"
range="none"
title="Data Monitoring"

refresh=10
once=""
columns=""

# Options
while [ "$#" -gt 0 ]
do
    case "$1" in
    -a | -ascii)
        term="dumb"
        shift 1
        ;;
    -c | -columns)
        [ "$#" -ge 2 ] || error "'$1' option requires an argument"
        columns=$(echo "$2" | tr , " ")
        for c in $columns
        do isInt "$c" || error "Argument of '$1' is not an integer: '$c'"
        done
        shift 2
        ;;
    -f | -flip)
        AXIS="x"
        shift 1
        ;;
    -h | -help)
        usage && exit 0
        ;;
    -l | -logscale)
        logscale="yes"
        shift 1
        ;;
    -o | -once)
        once="yes"
        shift 1
        ;;
    -r | -refresh)
        [ "$#" -ge 2 ] || error "'$1' option requires an argument"
        isInt "$2" || error "Argument of '$1' is not an integer: '$2'"
        refresh="$2"
        shift 2
        ;;
    -s | -size)
        [ "$#" -ge 2 ] || error "'$1' option requires an argument"
        size="$2"
        shift 2
        ;;
    -t | -title)
        [ "$#" -ge 2 ] || usage "'$1' option requires an argument"
        title=$2
        shift 2
        ;;
    -y | -yrange)
        [ "$#" -ge 2 ] || error "'$1' option requires an argument"
        range="$2"
        shift 2
        ;;
    -*)
        error "unknown option: '$*'"
        ;;
    *)
        break
        ;;
    esac
done

# Check input file
[ $# -eq 1 ] || error "Incorrect arguments specified"
[ -f "$1" ]  || error "File $1 does not exist"
file=$1

# Get keys from file header, removing space between the column names and units
keys=$(grep -E '^#' "$file" | sed 's/ *\[/\[/g' | tail -1 | tr -s " ")

# If no header, use 'Step' to describe column 1
[ "$keys" = "" ] && keys="# Step"

n_keys=$(howMany "$keys")
n_cols=$(tail -1 "$file" | awk '{ print NF }')

# With full column labels, n_keys = n_cols + 1, since it includes "#"
# If n_keys > n_cols + 1, REMOVE EXCESS keys
n_cols_pone=$(( n_cols + 1 ))
[ "$n_keys" -gt "$n_cols_pone" ] && \
    keys=$(echo "$keys" | cut -d" " -f1-$n_cols_pone)
n_keys=$(howMany "$keys")

# If n_keys < n_cols + 1, create keys 'data1', 'data2', etc
i=0
while [ "$n_keys" -le "$n_cols" ]
do
    i=$(( i + 1 ))
    keys="$keys data$i"
    n_keys=$(howMany "$keys")
done

# Remove starting "#"; set 'n_keys' finally
keys=$(echo "$keys" | cut -d " " -f2-)
n_keys=$(howMany "$keys")

# Set 'label' to column 1 key
label=$(echo "$keys" | awk '{print $1}')

# Set columns to display
[ "$columns" ] || columns="$(seq 2 "$n_keys")"

# Check the highest column is not out of range
highest_column="$(echo "$columns" | xargs -n 1 | \
                  sort -n | xargs | awk '{print $NF}')"
[ "$highest_column" -gt "$n_keys" ] && \
    error "Data does not extend to specified column '$highest_column'"

# Last column
# shellcheck disable=SC2086
last_col="$(echo $columns | awk '{print $NF}')"

# Generate the gnuplot commands to set up the plot
gnuplotSetup() {
    _ticFormat="%g"
    [ "$logscale" = yes ] && _ticFormat="%1.e"
    _otherAxis="$([ "$AXIS" = x ] && echo y || echo x)"

    printf "set term %s" "$term"

    # if '-size' specified, scale the font size to a sensible compromise
    # assumes approximate defaults of window size 600x400 and font size 12
    ! [ "$size" = default ] && \
        _fontsize="$(awk \
            -v x="$(echo "$size" | cut -d, -f1)" \
            -v y="$(echo "$size" | cut -d, -f2)" \
            'BEGIN {x/=600; y/=400; printf "%i", 12*(x < y ? x : y)**0.8}')" && \
        printf " size %s" "$size" && \
        printf " font \",%i\"" "$_fontsize"

    printf "\n"

    [ "$logscale" = yes ] && printf "set logscale %s\n" "$AXIS"
    [ "$range" = none ] || printf "set %srange %s\n" "$AXIS" "$range"
    printf "set %stics format \"%s\"\n" "$AXIS" "$_ticFormat"
    printf "set title \"%s\"\n" "$title"
    printf "set %slabel \"%s\"\n" "$_otherAxis" "$label"
}

# Generate the gnuplot plot command
gnuplotPlot() {
    echo "plot \\"
    for col in $columns
    do
        # Reinstate the space between the column name and units
        field="$(echo "$keys" | awk -v c="$col" '{print $c}' | sed 's/\[/ \[/')"
        plot_line="    \"$file\" using $(flip "1:${col}") with lines title \"$field\""
        [ "$col" -ne "$last_col" ] && plot_line="$plot_line, \\"
        echo "$plot_line"
    done
}

# Generate the full gnuplot command for a single plot
gnuplotOnce() {
    cat << EOF
$(gnuplotSetup)
$(gnuplotPlot)
EOF
}

# Generate the full gnuplot command for repeated plots
gnuplotRepeated() {
    cat << EOF
$(gnuplotSetup)
stop = 0
bind Close "stop = 1"
while !stop {
$(gnuplotPlot)
pause $refresh
}
EOF
}

# Call gnuplot. Run in the background unless this is a dumb/ascii terminal. If
# plotting once then keep the plot open until the user closes the window. If we
# ever add support for more terminals here, this might need extending.
if [ "$once" ]
then
    if [ "$term" = "dumb" ]
    then
        gnuplot << EOF
$(gnuplotOnce)
EOF
    else
        gnuplot << EOF &
$(gnuplotOnce)
pause mouse close
EOF
    fi
else
    if [ "$term" = "dumb" ]
    then
        gnuplot << EOF
$(gnuplotRepeated)
EOF
    else
        gnuplot << EOF &
$(gnuplotRepeated)
EOF
    fi
fi

#------------------------------------------------------------------------------