croposplot.py 5.62 KB
Newer Older
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
#!/usr/bin/env python
# this is <croposplot.py>
# ----------------------------------------------------------------------------
# 
# Copyright (c) 2019 by Thomas Forbriger (BFO Schiltach) 
# 
# create graphical diagram from output of croposp
#
# ----
# This program 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 2 of the License, or
# (at your option) any later version. 
# 
# This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
# ----
#
# REVISIONS and CHANGES 
#    31/01/2019   V1.0   Thomas Forbriger
# 
# ============================================================================
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
__version__ = "croposplot 2019-01-31 V1.0"
__author__ = "Thomas Forbriger"
# ----------------------------------------------------------------------------
# backend
# -------
# For screen-plots an appropriate backend must be chosen. This should be done
# by an entry in ~/.config/matplotlib/matplotlibrc like
# backend : qt5agg
# 
# Alternatively the first two statements may be set to:
#
#   import matplotlib
#    matplotlib.use('qt5agg')
#
# However, the backend then would be hardcoded, which is not desired.
43
#
44
45
46
47
48
49
# ----------------------------------------------------------------------------

import sys
import os
import getopt
import string
50
import re
51
52
53
54
55
56
57
58
59
import numpy as np
import matplotlib.pyplot as plt

# ============================================================================
def usage():
  """
  print usage information
  """
  print(__version__)
60
61
  print('Usage: '+sys.argv[0]+' [-v]')
  print('       [-o file] [-g|--grid] [--nologlog] [--nologx] [--nology]')
62
  print('       [--lfontsize s] [--title t]')
63
  print('       file [file [file ...]]')
64
65
66
67
68
69
70
71
72
73
74
75
76
77
  print('   or: '+sys.argv[0]+' --help|-h')


# ----------------------------------------------------------------------------
def help():
  """
  print online help
  """
  usage()
  print(
  """
  Read multicolumn output files of spectral values as written by croposp and
  create graphical diagrams.

78
79
80
81
82
83
84
85
  file ...        multicolumn spectral data output of croposp
  -v              be verbose
  -o file         write to file
  --xlabel l      set label "l" on x-axis
  -g|--grid       plot grid
  --nologlog      plot on linear scales
  --nologx        use linear scale for x-axis
  --nology        use linear scale for y-axis
86
  --lfontsize s   set font size for legend
87
  --title t       set plot title
88
89
90
91
92
93
94
95
96
97
98
99
100
  """)

# ============================================================================

def main(argv=None):
  """
  main body of program
  evaluate command line options and control processing
  """
  if argv is None:
    argv=sys.argv

  try:
101
    opts, args=getopt.getopt(sys.argv[1:], 'hvo:g', ['help', 'nologlog',
102
    'nologx', 'nology', 'grid', 'xlabel=', 'lfontsize=', 'title='])
103
104
105
106
107
108
109
110
  except getopt.GetoptError as err:
    print(err.msg)
    exit(0)

  verbose=False
  global DEBUG
  DEBUG=False
  outfile='x11'
111
112
113
114
  nologlog = False
  nologx = False
  nology = False
  grid = False
115
  xlabel = 'frequency / Hz'
116
  opt_legendfontsize='xx-small'
117
  opt_title = None
118
119
120
121
122
123
124
125

  for (opt, arg) in opts:
    if opt == '-v':
      verbose=True
    elif opt == '-D':
      DEBUG=True
    elif opt == '-o':
      outfile=arg
126
127
    elif opt in ('--xlabel'):
      xlabel=arg
128
129
    elif opt in ('--lfontsize'):
      opt_legendfontsize=arg
130
131
    elif opt in ('--title'):
      opt_title=arg
132
133
134
135
136
137
138
139
    elif opt in ("-g", "--grid"):
      grid = True
    elif opt in ("--nologlog"):
      nologlog = True
    elif opt in ("--nologx"):
      nologx = True
    elif opt in ("--nology"):
      nology = True
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
    elif (opt == '-h') or (opt == '--help'):
      help()
      exit(0)
    else :
      usage()
      exit(0)

  if DEBUG:
    print(opts)
    print(args)

  if len(args) < 1 and len(opts) < 1:
    usage()
    exit(0)

  print(__version__)
  print("Read croposp output files and create diagram")

  Figure=plt.figure()

160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
  plt.grid(grid)
  # using logscale if desired
  if nologx and nology:
    nologlog = True

  if nology and not nologlog:
    if verbose:
      sys.stdout.write("specplot: Using log scaling for x-axis ... \n")
    plt.semilogx()
  elif nologx and not nologlog:
    if verbose:
      sys.stdout.write("specplot: Using log scaling for y-axis ... \n")
    plt.semilogy()
  elif not nologlog:
    if verbose:
      sys.stdout.write("specplot: Using loglog scaling  ... \n")
    plt.loglog()
  else:
    if verbose:
      sys.stdout.write("specplot: Disable logscale ... \n")

181
182
  plt.xlabel(xlabel)

183
184
185
  for specfile in args:
    if verbose:
      print('read file %s' % specfile)
186
187
188
189
# read trace labels
    labellines=list(filter((lambda x: re.match('^# #',x)), 
      open(specfile).readlines()))
# read trace data
190
    data=np.loadtxt(specfile, unpack=False)
191
    for i in range(1,len(data[0,:])):
192
      label=re.sub('^# #\d+: ', '', labellines[i-1].strip())
193
      if verbose:
194
195
        print('plot curve %d: %s' % (i, label))
      plt.plot(data[:,0], data[:,i], label=label)
196
      plt.legend(fontsize=opt_legendfontsize)
197

198
199
200
    if opt_title is not None:
      plt.title(opt_title)

201
202
203
204
205
206
207
208
209
210
  if outfile=='x11':
    plt.show(True)
  else:
    plt.savefig(outfile, papertype='a4', orientation='landscape')

  return 0

# ============================================================================
if __name__ == '__main__':
  sys.exit(main())
211
212

# ----- END OF croposplot.py -----