Commit 9bb2a246 authored by Daniel Brown's avatar Daniel Brown
Browse files

first go at putting in plotting functions

parent 5bbaeb98
import pykat
pykat.init_pykat_plotting(mode="display", dpi=100)
from pykat import finesse
from pykat.detectors import *
from pykat.components import *
......@@ -5,7 +8,6 @@ from pykat.commands import *
from pykat.structs import *
import numpy as np
import pylab as pl
code = """
l l1 1 0 0 n1
......@@ -15,10 +17,12 @@ s s2 10 1 n3 n4
m m2 0.5 0.5 0 n4 n5
s s3 10 1 n5 n6
yaxis abs:deg
yaxis re:im
ad circ 0 0 0 n4
pd pd_cav n3
cav c1 m1 n3 m2 n4
attr m1 Rc 1
......@@ -27,7 +31,7 @@ attr m1 Rc 1
kat = finesse.kat()
kat.parseCommands(code)
kat.add(xaxis("lin", [0, 360], kat.m2.phi, 100))
kat.add(xaxis("lin", [0, 360], kat.m2.phi, 500))
kat.m1.Rcx = -1000.0
kat.m1.Rcy = -1000.0
......@@ -37,5 +41,4 @@ kat.m2.Rcy = 1000.0
kat.maxtem = 0
out = kat.run()
out.plot()
fig = out.plot("test_plot.pdf")
......@@ -8,7 +8,9 @@ __version__ = "0.8.1"
# This flag is used to switch on the gui features in pkat at import time
USE_GUI = False
HAS_OPTIVIS = False
import imp
try:
imp.find_module('optivis')
HAS_OPTIVIS = True
......@@ -26,6 +28,6 @@ import pykat.commands as commands
from pykat.optics.gaussian_beams import beam_param
from pykat.plotting import init_pykat_plotting
......@@ -1063,7 +1063,7 @@ class modulator(Component):
self._requested_node_names.append(node1)
self._requested_node_names.append(node2)
self._svgItem = None
self.__f = Param("f", self, SIfloat(f))
self.__f = Param("f", self, SIfloat(f), canFsig=True, fsig_name="fre")
self.__midx = Param("midx", self, SIfloat(midx))
self.__phase = Param("phase", self, SIfloat(phase), canFsig=True, fsig_name="phase")
self.__order = int(order)
......@@ -1171,7 +1171,7 @@ class laser(Component):
self._requested_node_names.append(node)
self.__power = Param("P", self, SIfloat(P), canFsig=True, fsig_name="amp")
self.__f_offset = Param("f", self, SIfloat(f), canFsig=True, fsig_name="f")
self.__f_offset = Param("f", self, SIfloat(f), canFsig=True, fsig_name="freq")
self.__phase = Param("phase", self, SIfloat(phase), canFsig=True, fsig_name="phase")
self.__noise = AttrParam("noise", self, None)
self._svgItem = None
......
......@@ -65,6 +65,7 @@ class BaseDetector(object) :
self._mask = {}
self.__scale = []
self.__removed = False
self.noplot = False
self._alternate_beam = []
self._nodes = []
......
......@@ -240,13 +240,74 @@ class katRun(object):
self.katVersion = None
self.yaxis = None
def plot(self, logy=False):
import pylab
def plot(self, filename=None, show=True):
import matplotlib.pyplot as pyplot
import pykat.plotting as plt
kat = pykat.finesse.kat()
kat.verbose = False
kat.parseCommands(self.katScript)
plot_cmd = None
if "log" in kat.yaxis:
if kat.xaxis.scale == "log":
plot_cmd = pyplot.loglog
else:
plot_cmd = pyplot.semilogy
else:
if kat.xaxis.scale == "log":
plot_cmd = pyplot.semilogx
else:
plot_cmd = pyplot.plot
dual_plot = False
if ":" in kat.yaxis:
fig = plt.figure(width="full", height=1)
dual_plot = True
else:
fig = plt.figure(width="full")
for lbl in self.ylabels:
lbl = lbl.split()[0]
if not dual_plot:
plot_cmd(self.x, np.abs(self[lbl]))
else:
pyplot.subplot(2,1,1)
plot_cmd(self.x, np.abs(self[lbl]))
pylab.plot(self.x, self.y)
pylab.legend(self.ylabels,0)
pylab.xlabel(self.xlabel)
pylab.show()
pyplot.subplot(2,1,2)
plot_cmd(self.x, np.angle(self[lbl]))
if dual_plot:
pyplot.subplot(2,1,1)
pyplot.xlabel(self.xlabel, fontsize=pyplot.rcParams["font.size"])
pyplot.xlim(self.x.min(), self.x.max())
if "abs" in kat.yaxis: pyplot.ylabel("Absolute [au]", fontsize=pyplot.rcParams["font.size"])
if "re" in kat.yaxis: pyplot.ylabel("Real part [au]", fontsize=pyplot.rcParams["font.size"])
pyplot.subplot(2,1,2)
pyplot.xlabel(self.xlabel, fontsize=pyplot.rcParams["font.size"])
pyplot.xlim(self.x.min(), self.x.max())
if "deg" in kat.yaxis: pyplot.ylabel("Phase [deg]", fontsize=pyplot.rcParams["font.size"])
if "im" in kat.yaxis: pyplot.ylabel("Imaginary part [au]", fontsize=pyplot.rcParams["font.size"])
else:
pyplot.xlabel(self.xlabel, fontsize=pyplot.rcParams["font.size"])
pyplot.ylabel(" [au]")
pyplot.xlim(self.x.min(), self.x.max())
fig.tight_layout()
if filename is not None:
fig.savefig(filename)
if show:
pyplot.show(fig)
return fig
def savekatRun(self, filename):
with open(filename,'w') as outfile:
......@@ -916,8 +977,7 @@ class kat(object):
elif(first == "fsig"):
after_process.append((line, self.__currentTag))
elif(first == "noplot"):
obj = line
#self.__blocks[self.__currentTag].contents.append(line)
after_process.append((line, self.__currentTag))
else:
if self.verbose:
print ("Parsing `{0}` into pykat object not implemented yet, added as extra line.".format(line))
......@@ -938,7 +998,7 @@ class kat(object):
# components to exist first before they can be processed
for item in after_process:
line = item[0]
first = line.split(" ",1)[0]
first, rest = line.split(" ",1)
block = item[1]
if first == "gauss" or first == "gauss*" or first == "gauss**":
......@@ -955,6 +1015,11 @@ class kat(object):
elif (first == "variable"):
self.add(pykat.commands.variable.parseFinesseText(line, self), block=block)
elif (first == "noplot"):
if not hasattr(self, rest):
raise pkex.BasePyKatException("noplot command `{0}` refers to non-existing detector".format(line))
getattr(self, rest).noplot = True
elif (first == "scale"):
v = line.split()
......@@ -1264,7 +1329,7 @@ class kat(object):
err="".join((err,str(line, 'utf-8')))
[out,errpipe] = p.communicate()
[out, errpipe] = p.communicate()
if six.PY2:
_out = str(out).split("\n")
......@@ -1286,6 +1351,7 @@ class kat(object):
# get the version number
ix = out.find(b'build ') + 6
ix2 = out.find(b')',ix)
r.katVersion = out[ix:ix2]
r.runDateTime = datetime.datetime.now()
......
......@@ -9,79 +9,87 @@ from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import matplotlib
# Should be either display (showing in windows) or paper (saving for paper/report/etc.)
__mode__ = None
__DPI__ = None
BACKEND = 'Qt4Agg'
matplotlib.use(BACKEND)
from matplotlib import rc
import matplotlib.pyplot as plt
mainpid = -1
def plot1D(run, title=""):
def in_ipython():
try:
cfg = get_ipython()
return True
except NameError:
return False
def init_pykat_plotting(mode="display", dpi=100):
import matplotlib as mpl
rc('font', **pp.font)
rc('xtick',labelsize=pp.TICK_SIZE)
rc('ytick',labelsize=pp.TICK_SIZE)
rc('text', usetex=pp.USETEX)
rc('axes', labelsize = pp.LABEL_SIZE)
__DPI__ = int(dpi)
fig=plt.figure()
fig.set_size_inches(pp.fig_size)
fig.set_dpi(pp.FIG_DPI)
ax1 = fig.add_subplot(111)
ax1.set_xlim(np.min(run.x),np.max(run.x))
traces = ax1.plot(run.x,run.y)
ax1.grid(pp.GRID)
if in_ipython():
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('pdf', 'svg')
ipy = get_ipython()
ipy.magic("matplotlib inline")
ax1.set_xlabel(run.xlabel)
legends = run.ylabels
ax1.legend(traces, legends, loc=0, shadow=pp.SHADOW,prop={'size':pp.LEGEND_SIZE})
if mode == "display":
__mode__ = mode
elif mode == "paper":
__mode__ = mode
mpl.use("pgf")
pgf_with_pdflatex = {
"pgf.texsystem": "pdflatex",
"pgf.preamble": [
r"\usepackage{amsmath, amssymb}",
r"\usepackage{mathtools, siunitx}" ,
r"\usepackage{amsmath}",
r"\usepackage[utf8x]{inputenc}",
r"\usepackage[T1]{fontenc}"
]
}
if pp.PRINT_TITLE:
plt.title(title)
mpl.rcParams.update(pgf_with_pdflatex)
else:
raise(BaseException("Plotting mode must be either 'display' or 'paper'."))
if pp.SCREEN_TITLE:
fig.canvas.manager.set_window_title(title)
mpl.rcParams.update({"figure.figsize": (6, 3.708)})
mpl.rcParams.update({'font.size': 11})
mpl.rcParams.update({'figure.dpi': __DPI__})
mpl.rcParams.update({'savefig.dpi': __DPI__})
mpl.rcParams.update({'font.family': "serif"})
mpl.rcParams.update({'axes.grid': True})
mpl.rcParams.update({'axes.axisbelow': True})
mpl.rcParams.update({'grid.linewidth': 0.25})
mpl.rcParams.update({'grid.linestyle': ":"})
mpl.rcParams.update({'grid.color': (0.7,0.7,0.7,1)})
mpl.rcParams.update({'savefig.bbox': "tight"})
mpl.rcParams.update({'savefig.pad_inches': 0.05})
mpl.rcParams.update({'xtick.labelsize': "small"})
mpl.rcParams.update({'ytick.labelsize': "small"})
mpl.rcParams.update({'axes.formatter.useoffset': False})
def figure(width="full", height=0.618, textwidth=6, **kwargs):
"""
Options:
width: 'full', 'half' (0.49*textwidth) (default: full)
height: relative height to width (default: 1/golden ratio = 0.618)
textwidth: Width of text in inches (default: 9.84252 in = 25 cm )
"""
import matplotlib.pyplot as plt
if width == "full":
fig_size = [textwidth, textwidth*height]
elif width == "half":
fig_size = [textwidth*0.49, textwidth*height*0.49]
else:
fig.canvas.manager.set_window_title('')
raise(BaseException("width must be either 'full' or 'half'."))
#plt.ion()
plt.show()
fig = plt.figure(figsize=fig_size, dpi=__DPI__)
return fig
class pp():
# set some gobal settings first
BACKEND = 'Qt4Agg' # matplotlib backend
FIG_DPI=90 # DPI of on sceen plot
# Some help in calculating good figure size for Latex
# documents. Starting with plot size in pt,
# get this from LaTeX using \showthe\columnwidth
fig_width_pt = 484.0
inches_per_pt = 1.0/72.27 # Convert TeX pt to inches
golden_mean = (np.sqrt(5)-1.0)/2.0 # Aesthetic ratio
fig_width = fig_width_pt*inches_per_pt # width in inches
fig_height = fig_width*golden_mean # height in inches
fig_size = [fig_width,fig_height]
# some plot options:
LINEWIDTH = 1 # linewidths of traces in plot
AA = True # antialiasing of traces
USETEX = False # use Latex encoding in text
SHADOW = False # shadow of legend box
GRID = True # grid on or off
# font sizes for normal text, tick labels and legend
FONT_SIZE = 10 # size of normal text
TICK_SIZE = 10 # size of tick labels
LABEL_SIZE = 10 # size of axes labels
LEGEND_SIZE = 10 # size of legend
# font family and type
font = {'family':'sans-serif','sans-serif':['Helvetica'],'size':FONT_SIZE}
DPI=300 # DPI for saving via savefig
# print options given to savefig command:
print_options = {'dpi':DPI, 'transparent':True, 'bbox_inches':'tight', 'pad_inches':0.1}
# for Palatino and other serif fonts use:
#font = {'family':'serif','serif':['Palatino']}
SCREEN_TITLE = True # show title on screen?
PRINT_TITLE = False # show title in saved file?
\ No newline at end of file
......@@ -3,10 +3,10 @@ from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import pylab as pl
def plotReducedPerformanceData(perfdata, ordered=False):
import numpy as np
import pylab as pl
labels = []
times = []
......
import pylab as pl
#import pylab as pl # removed by DDB 1/12/2015
import scipy.optimize as opt
from pykat import finesse
from pykat.detectors import *
......@@ -7,7 +7,7 @@ from pykat.commands import *
from pykat.structs import *
from numpy import *
# from modematch import modematch
import pykat.utilities.optics.ABCD as abcd
import pykat.optics.ABCD as abcd
import time
......
......@@ -2,9 +2,10 @@ import pykat
import pykat.exceptions as pkex
import copy
import numpy as np
import pylab
def plot_beam_trace(_kat, from_node, to_node):
import pylab
if _kat == None:
raise pkex.BasePyKatException('kat object in None')
......
This diff is collapsed.
This diff is collapsed.
Supports Markdown
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