Commit 47822061 authored by Daniel Armbruster's avatar Daniel Armbruster Committed by thomas.forbriger
Browse files

python tool to plot power spectra

This is a legacy commit from before 2015-03-01.
It may be incomplete as well as inconsistent.
See COPYING.legacy and README.history for details.


SVN Path:     http://gpitrsvn.gpi.uni-karlsruhe.de/repos/TFSoftware/trunk
SVN Revision: 4693
SVN UUID:     67feda4a-a26e-11df-9d6e-31afc202ad0c
parent 813391f7
This is a legacy version of the repository. It may be incomplete as well as
inconsistent. See README.history for details. For the old stock of the
repository copyright and licence conditions apply as specified for versions
commited after 2015-03-01. Use recent versions as a base for new development.
The legacy version is only stored to keep a record of history.
#!/usr/bin/env python2
## @file pspecplot.py
# @brief
#
# -----------------------------------------------------------------------------
#
# $Id: pspecplot.py 616 2012-05-05 00:03:30Z uhcnl $
# @author Daniel Armbruster
# \date 08/02/2012
#
# Purpose: Plot the power spectrum.
#
# ----
#
# 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 3 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/>.
# ----
#
# Copyright (c) 2012 by Daniel Armbruster
#
# REVISIONS and CHANGES
# 08/02/2012 V0.1 Daniel Armbruster
# 04/05/2012 V0.2 Stable for TFSoftware.
#
# =============================================================================
"""
Plot an simple power spectrum using python's matplotlib.
TODO:
* legend not supported yet
* plot multiple datafiles
"""
import sys
import os
import getopt
import string
import matplotlib
import matplotlib.pyplot as plt
__version__ = "V0.2"
__subversion__ = "$Id: pspecplot.py 616 2012-05-05 00:03:30Z uhcnl $"
__license__ = "GPLv2"
__author__ = "Daniel Armbruster"
__copyright__ = "Copyright (c) 2012 by Daniel Armbruster"
# -----------------------------------------------------------------------------
class Error(Exception):
def __init__(self, msg=""):
self.msg = str(msg)
def display(self):
sys.stderr.write("pspecplot (ERROR): " + self.msg + "\n")
class Usage(Error):
def display(self):
usage_text = "Version: "+__version__+"\nLicense: "+__license__+ \
"\n"+__subversion__+"\nAuthor: "+__author__+ """
Usage: pspecplot [-v|--verbose] [--overwrite] [--oformat arg] [--outbase arg]
[-t|--title arg] [--orientation arg] [--nologlog] [-g|--grid]
[--xlabel arg] [--ylabel arg] [--xlim val:val]
[--ylim val:val]
DATAFILE
or: pspecplot -h|--help"""
if 0 != len(self.msg):
sys.stderr.write("pspecplot: " + self.msg + "\n")
sys.stderr.write(usage_text)
if 0 != len(self.msg):
sys.stderr.write("\n")
# -----------------------------------------------------------------------------
def help():
"""
Printing helptext to stdout.
"""
help_text = \
"""
-------------------------------------------------------------------------------
-v|--verbose Be verbose.
-h|--help Display this help.
--overwrite Overwrite output file if existing.
--outbase arg Basename of the output file. If not specified there will
be plotted an interactive plot.
--oformat arg Format of the output file.
Supported formats: emf, eps, jpeg, jpg, pdf, png,
ps (default), raw, rgba, svg, svgz, tif, tiff.
Plot appearance:
-t|--title arg Title of the plot.
--orientation arg Orientation of the plot. Valid arguments are 'landscape'
and 'portrait' (default).
-g|--grid Enable grid.
--xlabel arg x-axis label
--ylabel arg y-axis label
--xlim val:val Set fixed x-limits of the current axis.
--ylim val:val Set fixed y-limits of the current axis.
--nologlog Disable loglog scale of axis
--fit Fit plot to page (only is saving plot to file).
DATAFILE File which contain the data (two columns).\n"""
Usage().display()
sys.stdout.write(help_text)
# -----------------------------------------------------------------------------
def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "hvgt:", ["help", "verbose", \
"overwrite", "title=", "orientation=", "outbase=", "oformat=", \
"xlabel=", "ylabel=", "nologlog", "grid", "fit", "xlim=", "ylim="])
except getopt.GetoptError as err:
raise Usage(err.msg)
# fetch arguments
verbose = False
overwrite = False
plotTitle = ""
orientation = "portrait"
oformat = "ps"
outbase = ""
xlabel = ""
ylabel = ""
nologlog = False
grid = False
fit = None
xlim = []
ylim = []
for opt, arg in opts:
if opt in ("-v", "--verbose"):
verbose = True
elif opt in ("-h", "--help"):
help()
sys.exit()
elif opt in ("--overwrite"):
overwrite = True
elif opt in ("--oformat"):
oformat = arg
elif opt in ("--orientation"):
orientation = arg
if orientation != "portrait" or orientation != "landscape":
raise Usage("Invalid 'orientation' argument.")
elif opt in ("--outbase"):
outbase = arg
elif opt in ("-t", "--title"):
plotTitle = arg
elif opt in ("--xlabel"):
xlabel = arg
elif opt in ("--ylabel"):
ylabel = arg
elif opt in ("-g", "--grid"):
grid = True
elif opt in ("--nologlog"):
nologlog = True
elif opt in ("--fit"):
fit = "tight"
elif opt in ("--xlim"):
try:
xlim = [float(x) for x in arg.split(":")]
if 2 != len(xlim):
raise
except:
raise Usage("Invalid 'xlim' argument.")
elif opt in ("--ylim"):
try:
ylim = [float(y) for y in arg.split(":")]
if 2 != len(ylim):
raise
except:
raise Usage("Invalid 'ylim' argument.")
else:
raise Usage("Unhandled option chosen.")
if 1 == len(args):
datafile = args[0]
else:
raise Usage("Invalid arguments.")
if len(outbase) and os.access(outbase+"."+string.lower(oformat), os.F_OK) \
and not overwrite:
raise Usage(outbase+"."+string.lower(oformat)+" already exists.")
# read data from datafile
if not os.access(datafile, os.F_OK):
raise Error("Invalid path to DATAFILE.")
if 0 == os.stat(datafile).st_size:
raise Error("Given DATAFILE is an empty file.")
if verbose:
sys.stdout.write("pspecplot: Reading DATAFILE ... \n")
try:
x = []
y = []
file = open(datafile, 'r')
for line in file:
col1,col2 = line.split()
x.append(col1)
y.append(col2)
except IOError as err:
raise Error("[Errno "+str(err.errno)+"] "+err.strerror+": "+err.filename)
else:
file.close()
# check data consistency
if len(x) != len(y):
raise Error("Data not consistent.")
# generate plot
if verbose:
sys.stdout.write("pspecplot: Preparing plot ... \n")
# x and y limits
if 2 == len(xlim):
plt.xlim(xlim[0], xlim[1])
if 2 == len(ylim):
plt.ylim(ylim[0], ylim[1])
plt.plot(x, y)
plt.grid(grid)
if not nologlog:
plt.loglog()
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(plotTitle)
if len(outbase):
if verbose:
sys.stdout.write("pspecplot: Saving file ... \n")
try:
plt.savefig(outbase+"."+string.lower(oformat), \
orientation=orientation, format=oformat, bbox_inches=fit)
except ValueError as err:
raise Usage(err.message)
else:
if verbose:
sys.stdout.write("pspecplot: Generating interactive plot ... \n")
plt.show()
except Error as err:
err.display()
return 2
except Usage as err:
err.display()
return 2
# -----------------------------------------------------------------------------
if __name__ == "__main__":
sys.exit(main())
# ----- END OF pspecplot.py -----
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment