Commit a21d3a2f authored by Andreas Freise's avatar Andreas Freise
Browse files

Merge branch 'master' of gitmaster.atlas.aei.uni-hannover.de:pykat/pykat

parents 25372fae 17b2b0f3
......@@ -11,20 +11,23 @@ s s1 10 1 n1 n2
m m1 1 0 0 n2 n3
pd refl n2
gauss g1 m1 n2 1e-3 0
xaxis m1 r_ap lin 0.1e-3 2e-3 10
"""
kat = finesse.kat()
kat.parseCommands(code)
maxtem = np.linspace(0, 1, 2)
maxtem = np.arange(0, 4)
kat.m1.n2.q = gauss_param(w0=1e-3, z=0)
#kat.m1.n2.q = gauss_param(w0=1e-3, z=0)
kat.verbose = False
for tem in maxtem:
print "Calculating maxtem ", tem, "..."
kat.maxtem = tem
r = kat.run()
pl.plot(r.x/1e-3, r.y, label="maxtem={0}".format(tem))
......
......@@ -8,7 +8,7 @@ import numpy as np
import pylab as pl
code = """
l l1 1 0 0 n1 ### test
l l1 1 0 0 n1
s s1 10 1 n1 n2
m m1 0.5 0.5 0 n2 n3
s s2 10 1 n3 n4
......@@ -25,7 +25,6 @@ attr m1 Rc 1
"""
kat = finesse.kat()
kat.parseCommands(code)
kat.add(xaxis("lin", [0, 360], kat.m2.phi, 100))
......@@ -37,11 +36,6 @@ kat.m2.Rcy = 1000.0
kat.maxtem = 0
out = kat.run(printout=0,printerr=0)
out = kat.run()
out.plot()
pl.figure()
pl.plot(out.x, out.y)
pl.xlabel(out.xlabel)
pl.ylabel("Intensity [W]")
pl.legend(out.ylabels)
pl.show()
import pykat
import pylab
import numpy
import ctypes
import pylibkat
cmd = """
l l1 1 0 n1
s s1 1 n1 n2
m m1 0.99 0.01 0 n2 n3
s s2 999 n3 n4
s s2 1 n3 n4
m m2 0.99 0.01 0 n4 n5
pd circ n3
......@@ -14,6 +18,8 @@ maxtem 0
attr m1 Rc 0
attr m2 Rc 1000
cav c1 m1 n3 m2 n4
retrace force
"""
kat = pykat.finesse.kat()
......@@ -26,3 +32,46 @@ print "n1 qx =", info["n1"].qx
print "Cavity info ", info["c1"]
import numpy
Lengths = numpy.linspace(1, 999, 10000)
g_factors = []
lkat = ctypes.PyDLL("libkat.dylib")
try:
lkat._pykat_preInit() # must always be called, sets up
# exception handling and such no simulation
# specifc code here
# reads in the kat.ini and setups up other parts
lkat._pykat_init()
cmd = "".join(kat.generateKatScript())
lkat._pykat_setup(cmd)
inter = pylibkat.interferometer.in_dll(lkat, "inter")
s2 = inter.space_list[1]
cav = inter.cavity_list[0]
inter.rebuild = 2
inter.retrace = 1
s2.rebuild = 2
for L in Lengths:
s2.L = L
lkat._pykat_step()
g_factors.append(cav.stability_x)
except Exception as ex:
print "Exception caught in python: ", ex.message
finally:
# This should always be called no matter what
lkat._pykat_finish(0)
pylab.plot(Lengths, g_factors)
pylab.show()
......@@ -158,18 +158,18 @@ class xaxis(Command):
raise pkex.BasePyKatException("param argument is not of type Param")
else:
self.__param = param
self.__comp = param._owner().name
self.__comp = param._owner()
@property
def param(self): return self.__param
@param.setter
def param(self, value):
if not isinstance(value, Param):
raise pkex.BasePyKatException("param argument is not of type Param")
else:
self.__param = value
self.__comp = value._owner().name
if not isinstance(value, Param):
raise pkex.BasePyKatException("param argument is not of type Param")
else:
self.__param = value
self.__comp = value._owner()
@staticmethod
def parseFinesseText(text):
values = text.split()
......@@ -188,9 +188,9 @@ class xaxis(Command):
def getFinesseText(self):
# store either the component name of the string provided
comp_name = self.__comp.name if isinstance(self.__comp, Component) else self.__comp
comp_name = self.__comp.name if hasattr(self.__comp, "name") else self.__comp
param_name = self.__param.name if isinstance(self.__param, Param) else self.__param
return '{axis_type} {0} {1} {2} {3} {4} {5}'.format(
comp_name, param_name, self.scale,
min(self.limits), max(self.limits), self.steps, axis_type=self._axis_type);
......
......@@ -170,7 +170,7 @@ class Component(object):
class AbstractMirrorComponent(Component):
__metaclass__ = abc.ABCMeta
def __init__(self, name, R=None, T=None, L=None, phi=0, Rcx=None, Rcy=None, xbeta=None, ybeta=None, mass=None, r_ap=None, Ix=None, Iy=None, zmech=None, rxmech=None, rymech=None):
super(AbstractMirrorComponent, self).__init__(name)
......@@ -203,6 +203,26 @@ class AbstractMirrorComponent(Component):
self.__rxmech = AttrParam("rxmech", self, rxmech)
self.__rymech = AttrParam("rymech", self, rymech)
self.__z = Param("z", self, 0, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="z")
self.__rx = Param("rx", self, 0, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="rx")
self.__ry = Param("ry", self, 0, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="ry")
self.__Fz = Param("Fz", self, 0, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="Fz")
self.__Frx = Param("Frx", self, 0, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="Frx")
self.__Fry = Param("Fry", self, 0, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="Fry")
@property
def z(self): return self.__z
@property
def Fz(self): return self.__Fz
@property
def rx(self): return self.__rx
@property
def Frx(self): return self.__Frx
@property
def ry(self): return self.__ry
@property
def Fry(self): return self.__Fry
@property
def L(self): return self.__L
@L.setter
......@@ -446,7 +466,7 @@ class beamSplitter(AbstractMirrorComponent):
def getQGraphicsItem(self):
if self._svgItem == None:
# FIXME: make proper SVG component for beam splitter
self._svgItem = pykat.gui.graphics.ComponentQGraphicsItem(":/resources/mirror_flat.svg", self ,[(-4,15,self.nodes[0]), (14,15,self.nodes[1])])
self._svgItem = pykat.gui.graphics.ComponentQGraphicsItem(":/resources/mirror_flat.svg", self ,[(-4,24,self.nodes[0]), (-4,6,self.nodes[1]), (14,6,self.nodes[2]), (14,24,self.nodes[3])])
return self._svgItem
......@@ -501,7 +521,7 @@ class space(Component):
self.__gx.value = values[key]
elif key in ["gy", "gouyy"]:
self.__gy.value = values[key]
elif key in ["g, gouy"]:
elif key in ["g","gouy"]:
self.__gx.value = values[key]
self.__gy.value = values[key]
else:
......@@ -572,7 +592,8 @@ class grating(Component):
self.__eta_3 = AttrParam("eta_3", self, SIfloat(eta_3))
self.__rho_0 = AttrParam("rho_0", self, SIfloat(rho_0))
self.__alpha = AttrParam("alpha", self, SIfloat(alpha))
self._svgItem = None
@property
def n(self): return Param('n', self.__n)
@n.setter
......@@ -666,18 +687,19 @@ class grating(Component):
return rtn
def getQGraphicsItem(self):
if self._QItem == None:
self._QItem = pykat.gui.graphics.SpaceQGraphicsItem(self) # TODO: make SVG graphic for grating
if self._svgItem == None:
self._svgItem = pykat.gui.graphics.SpaceQGraphicsItem(self) # TODO: make SVG graphic for grating
return self._QItem
return self._svgItem
class isolator(Component):
def __init__(self, name, node1, node2, node3="dump", S = 0):
def __init__(self, name, node1, node2, S = 0, node3="dump"):
Component.__init__(self, name)
self._requested_node_names.append(node1)
self._requested_node_names.append(node2)
self._requested_node_names.append(node3)
self._svgItem = None
self.__S = Param("S",self,SIfloat(S))
......@@ -698,7 +720,7 @@ class isolator(Component):
if len(values) == 4:
return isolator(values[0], values[2], values[3], values[1])
elif len(values) == 5:
return isolator(values[0], values[2], values[3], values[4], values[1])
return isolator(values[0], values[2], values[3], node3=values[4], S=values[1])
else:
raise pkex.BasePyKatException("Isolator Finesse code format incorrect '{0}'".format(text))
......@@ -711,18 +733,18 @@ class isolator(Component):
return rtn
def getQGraphicsItem(self):
if self._QItem == None:
self._QItem = pykat.gui.graphics.SpaceQGraphicsItem(self) # TODO: make isolator graphic
if self._svgItem == None:
self._svgItem = pykat.gui.graphics.ComponentQGraphicsItem(":/resources/isolator.svg", self ,[(-4,15,self.nodes[0]), (14,15,self.nodes[1]), (14,24,self.nodes[2])])
return self._QItem
return self._svgItem
class lens(Component):
def __init__(self, name, node1, node2, f):
def __init__(self, name, node1, node2, f=1):
Component.__init__(self, name)
self._requested_node_names.append(node1)
self._requested_node_names.append(node2)
self._svgItem = None
self.__f = Param("f", self, SIfloat(f))
@property
......@@ -753,18 +775,18 @@ class lens(Component):
return rtn
def getQGraphicsItem(self):
if self._QItem == None:
self._QItem = pykat.gui.graphics.SpaceQGraphicsItem(self) # TODO: make lens graphic
if self._svgItem == None:
self._svgItem = pykat.gui.graphics.ComponentQGraphicsItem(":/resources/lens.svg", self ,[(-4,15,self.nodes[0]), (14,15,self.nodes[1])])
return self._QItem
return self._svgItem
class modulator(Component):
def __init__(self, name, f, midx, order, modulation_type, node1, node2, phase=0):
def __init__(self, name, node1, node2, f, midx, order, modulation_type='pm', phase=0):
Component.__init__(self, name)
self._requested_node_names.append(node1)
self._requested_node_names.append(node2)
self._svgItem = None
self.__f = Param("f", self, SIfloat(f))
self.__midx = Param("midx", self, SIfloat(midx))
self.__phase = Param("phase", self, SIfloat(phase))
......@@ -815,9 +837,9 @@ class modulator(Component):
v.pop(0) # remove initial value
if len(v) == 7:
return modulator(v[0], v[1], v[2], v[3], v[4], v[5], v[6])
return modulator(v[0], v[5], v[6], v[1], v[2], v[3], v[4])
if len(v) == 8:
return modulator(v[0], v[1], v[2], v[3], v[4], v[6], v[7], phase=v[5])
return modulator(v[0], v[6], v[7], v[1], v[2], v[3], v[4], phase=v[5])
else:
raise pkex.BasePyKatException("Modulator Finesse code format incorrect '{0}'".format(text))
......@@ -830,10 +852,10 @@ class modulator(Component):
return rtn
def getQGraphicsItem(self):
if self._QItem == None:
self._QItem = pykat.gui.graphics.SpaceQGraphicsItem(self) # TODO: make lens graphic
if self._svgItem == None:
self._svgItem = pykat.gui.graphics.ComponentQGraphicsItem(":/resources/modulator.svg", self ,[(-4,15,self.nodes[0]), (14,15,self.nodes[1])])
return self._QItem
return self._svgItem
class laser(Component):
def __init__(self,name,node,P=1,f_offset=0,phase=0):
......@@ -845,6 +867,7 @@ class laser(Component):
self.__f_offset = Param("f", self, SIfloat(f_offset), canFsig=True, fsig_name="f")
self.__phase = Param("phase", self, SIfloat(phase), canFsig=True, fsig_name="phase")
self.__noise = AttrParam("noise", self, None)
self._svgItem = None
@property
def P(self): return self.__power
......
......@@ -145,7 +145,7 @@ class ad(Detector):
if self.mode == None:
rtn.append("ad {name} {f} {node}{alt}".format(name=self.name, f=str(self.f.value), node=self.node.name, alt=alt))
else:
rtn.append("ad {name} {n} {m} {f} {node}{alt}".fomat(name=self.name, n=str(self.mode[0]), m=str(self.mode[1]), f=str(self.f.value), node=self.node.name, alt=alt))
rtn.append("ad {name} {n} {m} {f} {node}{alt}".format(name=self.name, n=str(self.mode[0]), m=str(self.mode[1]), f=str(self.f.value), node=self.node.name, alt=alt))
for p in self._params:
rtn.extend(p.getFinesseText())
......@@ -368,10 +368,6 @@ class qnoised(pd):
def pdtype(self, value):
raise pkex.BasePyKatException("Setting pdtype is not possible with qnoised detectors")
@pd.senstype.setter
def senstype(self,value):
raise pkex.BasePyKatException("qnoised detector has no sensitvity type")
def parseAttributes(self, values):
for key in values.keys():
......@@ -416,7 +412,14 @@ class qnoised(pd):
if alt_beam:
node = node[0:-1]
return qnoised(values[1], demods, node, alternate_beam=alt_beam, **dict)
if values[0].endswith('S'):
sens='S'
elif values[0].endswith('N'):
sens='N'
else:
sens=None
return qnoised(values[1], demods, node, senstype=sens, alternate_beam=alt_beam, **dict)
def getFinesseText(self) :
rtn = []
......@@ -440,7 +443,7 @@ class qnoised(pd):
if senstype == None:
senstype = ""
rtn.append("qnoised {0} {1} {2} {3}{4}".format(self.name, self.num_demods, fphi_str, self.node.name, alt_str))
rtn.append("qnoised{5} {0} {1} {2} {3}{4}".format(self.name, self.num_demods, fphi_str, self.node.name, alt_str, senstype))
if self.scale != None:
rtn.append("scale {1} {0}".format(self.name, self.scale))
......@@ -450,7 +453,7 @@ class qnoised(pd):
return rtn
class qnoised(pd):
class qshot(pd):
def __init__(self, name, num_demods, node_name, alternate_beam=False, **kwargs):
super(qnoised, self).__init__(name, num_demods, node_name, alternate_beam=alternate_beam, pdtype=None, senstype=None, **kwargs)
......@@ -498,8 +501,15 @@ class qnoised(pd):
if alt_beam:
node = node[0:-1]
if values[0].endswith('S'):
sens='S'
elif values[0].endswith('N'):
sens='N'
else:
sens=None
return qnoised(values[1], demods, node, alternate_beam=alt_beam, **dict)
return qshot(values[1], demods, node, senstype=sens, alternate_beam=alt_beam, **dict)
def getFinesseText(self) :
rtn = []
......@@ -523,7 +533,7 @@ class qnoised(pd):
if senstype == None:
senstype = ""
rtn.append("qshot {0} {1} {2} {3}{4}".format(self.name, self.num_demods, fphi_str, self.node.name, alt_str))
rtn.append("qshot{5} {0} {1} {2} {3}{4}".format(self.name, self.num_demods, fphi_str, self.node.name, alt_str,senstype))
if self.scale != None:
rtn.append("scale {1} {0}".format(self.name, self.scale))
......
......@@ -33,6 +33,7 @@ import pickle
import pykat
import warnings
import re
import math
import itertools
import ctypes
......@@ -154,8 +155,17 @@ class katRun(object):
self.ylabels = None
self.katScript = None
self.katVersion = None
self.yaxis = None
def plot(self):
import pylab
def saveKatRun(self, filename):
pylab.plot(self.x, self.y)
pylab.legend(self.ylabels,0)
pylab.xlabel(self.xlabel)
pylab.show()
def savekatRun(self, filename):
with open(filename,'w') as outfile:
pickle.dump(self, outfile)
......@@ -173,10 +183,17 @@ class katRun(object):
if len(idx) > 0:
out = self.y[:, idx]
if self.yaxis == "abs:deg":
out = self.y[:, idx[0]] * np.exp(1j*math.pi*self.y[:, idx[1]]/180.0)
elif self.yaxis == "re:im":
out = self.y[:, idx[0]] + 1j*self.y[:, idx[1]]
out.squeeze()
if out.size == 1:
return float(out)
return out[0]
else:
return out.squeeze()
return out
else:
raise pkex.BasePyKatException("No output by the name '{0}' found in the output".format(str(value)))
......@@ -211,6 +228,7 @@ class katRun2D(object):
else:
raise pkex.BasePyKatException("No output by the name {0} found".format(str(value)))
class Signals(object):
class fsig(object):
def __init__(self, param, name, amplitude, phase):
......@@ -371,6 +389,7 @@ class kat(object):
self.__maxtem = None
self.__noxaxis = None
self.__time_code = None
self.__yaxis = "abs" # default yaxis
if kat_code != None and kat_file != None:
raise pkex.BasePyKatException("Specify either a Kat file or some Kat code, not both.")
......@@ -387,6 +406,17 @@ class kat(object):
@property
def signals(self): return self.__signals
yaxis_options = ["abs:deg","db:deg","re:im","abs","db","deg"]
@property
def yaxis(self): return self.__yaxis
@yaxis.setter
def yaxis(self, value):
if not str(value) in self.yaxis_options:
raise pkex.BasePyKatException("yaxis value '{0}' is not a value option. Valid options are: {1}".format(str(value), ",".join(self.yaxis_options) ))
self.__yaxis = str(value)
@property
def trace(self): return self.__trace
@trace.setter
......@@ -479,11 +509,13 @@ class kat(object):
# check if we have a var/constant in this line
if line.find('$') >= 0:
for key in constants.keys():
if line.find('$'+key) > -1:
if line.find('$'+key+' ') > -1:
constants[key].usedBy.append(line)
line = line.replace('$'+key+' ', str(constants[key].value)+ ' ')
elif line.endswith('$'+key):
constants[key].usedBy.append(line)
line = line.replace('$'+key, str(constants[key].value))
commands_new.append(line)
self.constants = constants
......@@ -560,9 +592,9 @@ class kat(object):
obj = pykat.detectors.ad.parseFinesseText(line)
elif(first[0:2] == "pd" and first != "pdtype"):
obj = pykat.detectors.pd.parseFinesseText(line)
elif(first == "qshot"):
elif(first == "qshot" or first == "qshotS" or first == "qshotN"):
obj = pykat.detectors.qshot.parseFinesseText(line)
elif(first == "qnoised"):
elif(first == "qnoised" or first == "qnoisedS" or first == "qnoisedN"):
obj = pykat.detectors.qnoised.parseFinesseText(line)
elif(first == "xaxis" or first == "xaxis*"):
obj = pykat.commands.xaxis.parseFinesseText(line)
......@@ -578,6 +610,10 @@ class kat(object):
after_process.append(line)
elif(first == "noxaxis"):
self.noxaxis = True
elif(first == "yaxis"):
v = line.split()
self.yaxis = v[-1]
elif(first == "phase"):
v = line.split()
if len(v) != 2:
......@@ -589,9 +625,9 @@ class kat(object):
if len(v) != 2:
raise pkex.BasePyKatException("maxtem command `{0}` is incorrect.".format(line))
else:
if v[1] == "off":
self.maxtem = -1
else:
if v[1] == "off":
self.maxtem = -1
else:
self.maxtem = int(v[1])
elif(first == "trace"):
v = line.split()
......@@ -614,9 +650,15 @@ class kat(object):
elif(first == "gnuterm" or first == "pyterm"):
if self.verbose:
print "Ignoring Gnuplot/Python terminal command '{0}'".format(line)
#elif(first == "fsig"):
# after_process.append(line)
elif(first == "noplot"):
obj = line
self.__blocks[self.__currentTag].contents.append(line)
else:
if self.verbose:
print "Parsing `{0}` into pykat object not implemented yet, added as extra line.".format(line)
obj = line
# manually add the line to the block contents
self.__blocks[self.__currentTag].contents.append(line)
......@@ -659,7 +701,7 @@ class kat(object):
raise pkex.BasePyKatException("pdtype command `{0}` is incorrect.".format(line))
elif(first == "attr"):
v = line.split()
if len(v) < 4:
raise pkex.BasePyKatException("attr command `{0}` is incorrect.".format(line))
else:
......@@ -679,6 +721,21 @@ class kat(object):
comp.parseAttributes(kv)
elif(first == "fsig"):
v = line.split()
if v[2] in self.__components:
comp = self.__components[v[1]]
else:
raise pkex.BasePyKatException("Could not find the component '{0}' for attr command in line '{1}'".format(v[1], line))
#kat.siganls.apply()
else:
raise pkex.BasePyKatException("Haven't handled parsing of '{0}'".format(line))
self.__currentTag = NO_BLOCK
def saveScript(self, filename=None):
......@@ -749,6 +806,7 @@ class kat(object):
else:
r = katRun()
r.yaxis = self.yaxis
r.katScript = "".join(self