This file is indexed.

/usr/bin/freefoam-log is in freefoam 0.1.0+dfsg+1-3.

This file is owned by root:root, with mode 0o755.

The actual contents of the file can be viewed below.

  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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#! /usr/bin/python
#-------------------------------------------------------------------------------
#               ______                _     ____          __  __
#              |  ____|             _| |_  / __ \   /\   |  \/  |
#              | |__ _ __ ___  ___ /     \| |  | | /  \  | \  / |
#              |  __| '__/ _ \/ _ ( (| |) ) |  | |/ /\ \ | |\/| |
#              | |  | | |  __/  __/\_   _/| |__| / ____ \| |  | |
#              |_|  |_|  \___|\___|  |_|   \____/_/    \_\_|  |_|
#
#                   FreeFOAM: The Cross-Platform CFD Toolkit
#
# Copyright (C) 2008-2012 Michael Wild <themiwi@users.sf.net>
#                         Gerber van der Graaf <gerber_graaf@users.sf.net>
#-------------------------------------------------------------------------------
# License
#   This file is part of FreeFOAM.
#
#   FreeFOAM 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.
#
#   FreeFOAM 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 FreeFOAM.  If not, see <http://www.gnu.org/licenses/>.
#
# Script
#     freefoam-log
#
# Description
#     Extracts info from log file
#
# Bugs
#     -solution singularity not handled
#------------------------------------------------------------------------------

"""Usage: freefoam log [options] <log>

Extracts xy files from Foam logs.

Options
-------
-case <case_dir> Case directory (defaults to $PWD)
-n               Produce single-column data files
-s               Operate silently
-l               Only list extracted variables
-h, -help        Print this help message
<log>            Log file from which to extract data. If <log> is not an
                 absolute path, it is relative to the specified case directory.

The default is to extract for all the 'Solved for' variables the initial
residual, the final residual and the number of iterations. On top of this a
(user editable) database of standard non-solved for variables is used to
extract data like Courant number, execution time.

The -l option shows all the possible variables but does not extract them.

The program writes a set of files, <case_dir>/logs/<var>_<subIter>, for every
<var> specified, for every occurrence inside a time step.

For variables that are 'Solved for' the initial residual name will be <var>,
the final residual will get name <var>FinalRes,

The files are a simple xy format with the first column Time (default) and the
second the extracted values. Option -n creates single column files with the
extracted data only.

The query database is a simple text format containing Python regular
expressions. The regular expression must capture the queried value in a group
with the values name (i.e. using (?P<name>...) syntax). Lines where the first
non-blank character is a # will be ignored. The database will either be
<case_dir>/foamLog.db, $HOME/.FreeFOAM/foamLog.db or
/usr/share/freefoam/foamLog.db, whichever is found first.

Option -s suppresses the default information and only prints the extracted
variables.

"""


import os
import os.path
import sys
import re
# want to be future proof
sys.path.insert(0, '/usr/lib/python2.7/site-packages')
from FreeFOAM.compat import *

class PrintLog:
   def __init__(self, verbose):
      self.verbose = verbose
   def __call__(self, *args):
      if self.verbose:
         echo(*args)

class InvalidRegex(Exception):
   """Raised if a regex fails to compile"""
   def __init__(self, regex, i, msg):
      """Initialize with the error message `msg`, thefailed regex `regex` in
      line `i`"""
      Exception.__init__(self, regex, i, msg)

   def __str__(self):
      return 'Failed to compile regular expression "%s" in line %d:\n  %s'%self.args


def getSolvedForRegex(logf):
   """Extracts from the file object `logf` the solved-for variables and
   generates a list of regular expression objects to extract them or `None`."""
   p = logf.tell()
   logf.seek(0, 0)
   vars = set()
   for l in logf:
      m = re.search(r'Solving for\s+(?P<varname>\w+)', l)
      if m:
         vars.add(m.group('varname'))

   result = None
   if len(vars):
      result = []
      for v in vars:
         result.append(re.compile((''.join([
            'Solving for\s+%(var)s,\s+',
            'Initial residual = (?P<%(var)s>\S+),\s+',
            'Final residual = (?P<%(var)sFinalRes>\S+),\s+',
            'No Iterations (?P<%(var)sIters>\S+)']))%{'var': v}))
   logf.seek(p, 0)
   return result

def getDbRegex(logf, dbf):
   """Extracts from the file object `dbf` the contained regular expression
   strings and returns a list with regular expression objects that match any of
   the lines in the file object `logf` at least once."""
   pl = logf.tell()
   logf.seek(0, 0)
   pd = dbf.tell()
   dbf.seek(0, 0)

   # read db file
   allRegex = {}
   i = 0
   for l in dbf:
      i += 1
      # try to compile the line (discarding empty and comment lines)
      if not re.match(r'^\s*(#|$)', l):
         try:
            rc = re.compile(l[:-1])
         except re.error:
            e = sys.exc_info()[1]
            raise InvalidRegex(l[:-1], i, str(e))
         allRegex[i] = rc

   # try to match the regexes and tranfer the succesful ones into `result`
   result = []
   keys = list(allRegex.keys())
   for l in logf:
      for i in keys:
         r = allRegex[i]
         if r.search(l):
            result.append(r)
            keys.remove(i)
      if not len(keys):
         break
   dbf.seek(pd, 0)
   logf.seek(pl, 0)

   return result

def resetCounters(counters):
   """Reset the sub-iter counters"""
   for i in counters.keys():
      counters[i] = 0

#-----------------------------
# Main
#-----------------------------

# parse options
noTime = False
silent = False
listOnly = False
logName = None
caseDir = os.getcwd()
args = sys.argv[1:]
while len(args) > 0:
   a = args[0]
   if a == '-s':
      silent = True
      del args[0]
   elif a == '-n':
      noTime = True
      del args[0]
   elif a == '-l':
      listOnly = True
      del args[0]
   elif a == '-h' or a == '-help':
      echo(__doc__)
      sys.exit(0)
   elif a == '-case':
      if len(args) < 2:
         sys.stderr.write('Error: -case requires argument\n')
         sys.stderr.write(__doc__+'\n')
         sys.exit(1)
      caseDir = args[1]
      del args[:2]
   elif a[0] == '-':
      sys.stderr.write('Error: unknown option "%s"\n'%a)
      sys.stderr.write(__doc__+'\n')
      sys.exit(1)
   else:
      logName = a
      del args[0]

plog = PrintLog(not silent)

if not logName:
   sys.stderr.write('Error: No log file specified')
   sys.stderr.write(__doc__+'\n')
   sys.exit(1)

if not os.path.isabs(logName):
   logName = os.path.join(caseDir, logName)

if not os.path.isfile(logName):
   sys.stderr.write('Error: No such file "%s"\n'%logName)
   sys.exit(1)

# find foamLog.db
dbName = None
for n in (
      caseDir,
      os.path.expanduser('~/.FreeFOAM'),
      os.path.normpath('/usr/share/freefoam')
      ):
   n = os.path.join(os.path.normpath(n), 'foamLog.db')
   if os.path.isfile(n):
      dbName = n
      break
if not dbName:
   sys.stderr.write('Error: Failed to find foamLog.db\n')
   sys.exit(1)

# open the db and log file
logFile = open(logName, 'rt')
dbFile = open(dbName, 'rt')

# fetch all the regexes
regex = getSolvedForRegex(logFile)
regex.extend(getDbRegex(logFile, dbFile))
dbFile.close()

# get all the variable names, create data and counter container
vars = []
data = {}
counters = {}
for r in regex:
   for n in r.groupindex.keys():
      vars.append(n)
      data[n] = []
      counters[n] = 0
vars.sort()

# check uniqueness
if len(vars) != len(set(vars)):
   cnt = {}
   for v in vars:
      if not v in cnt:
         cnt[v] = 0
      cnt[v] += 1
   for v, n in cnt.items():
      if n > 1:
         sys.stderr.write(
               'Error: multiple regular expressions for variable "%s"\n'%v)
   sys.exit(1)

# if -l specified, list variables
if listOnly:
   echo('\n'.join(vars))
   sys.exit(0)

logsDir = os.path.join(caseDir, 'logs')

plog('Using:')
plog('  log      : %s'%logName)
plog('  database : %s'%dbName)
plog('  files to : %s'%logsDir)
plog('')

if not os.path.isdir(logsDir):
   if os.path.exists(logsDir):
      sys.stderr.write('Error: `%s` exists but is not a directory\n'%logsDir)
      sys.exit(1)
   os.mkdir(logsDir)

# loop over lines, extract data
splitRegex = re.compile(r'\s*Time\s*=\s*(?P<time>\S+)')
iteration = 0
resetCounters(counters)
time = []
for l in logFile:
   # check for splitting regex
   m = splitRegex.match(l)
   if m:
      time.append(m.group('time'))
      resetCounters(counters)
      iteration += 1
   for r in regex:
      # check for data regex
      m = r.search(l)
      if m:
         for n, v in m.groupdict().items():
            while len(data[n]) <= counters[n]:
               data[n].append([])
            data[n][counters[n]].append(v)
            counters[n] += 1
logFile.close()

# loop over data and write
tLen = max(map(len, time))
for n, v in data.items():
   for i in xrange(len(v)):
      f = open(os.path.join(logsDir, '%s_%d'%(n, i)), 'wt')
      for j in range(min(len(time), len(v[i]))):
         if not noTime:
            f.write(('%-'+str(tLen)+'s  ')%time[j])
         f.write('%s\n'%v[i][j])
      f.close()
plog('Generated XY files for:')
plog('\n'.join(vars))

# ------------------- vim: set sw=3 sts=3 ft=python et: ------------ end-of-file