Commit 855c482b authored by Daniel Brown's avatar Daniel Brown
Browse files

adding code so far

parents
#
\ No newline at end of file
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 10:43:18 2013
@author: Daniel
"""
class colours:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def disable(self):
self.HEADER = ''
self.OKBLUE = ''
self.OKGREEN = ''
self.WARNING = ''
self.FAIL = ''
self.ENDC = ''
\ No newline at end of file
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 11:58:09 2013
@author: Daniel
"""
import numpy
from numpy import min,max
import exceptions
from components import *
from structs import *
class Command:
def getFinesseText(self):
""" Base class for individual finesse optical components """
raise NotImplementedError("This function is not implemented")
class xaxis(Command):
def __init__(self, kat, scale, limits, comp, param, steps):
if scale != Scale.linear and scale != Scale.logarithmic:
raise exceptions.ValueError("scale is not Scale.linear or Scale.logarithmic")
self.scale = scale
if numpy.size(limits) != 2 :
raise exceptions.ValueError("limits input should be a 2x1 vector of limits for the xaxis")
self.limits = limits
if steps <= 0 :
raise exceptions.ValueError("steps value should be > 0")
self.steps = steps
if not isinstance(comp, Component):
raise exceptions.ValueError("comp is not a Component")
self.__comp = comp
if not isinstance(param, Param) :
raise exceptions.ValueError("param argument is not of type Param")
self._param = param
kat.add(self)
def getFinesseText(self):
return 'xaxis {0} {1} {2} {3} {4} {5}'.format(
self.__comp.name, self._param.name, self.scale,
min(self.limits), max(self.limits), self.steps);
\ No newline at end of file
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 11:10:01 2013
@author: Daniel
"""
import exceptions
import pykat.gui.resources
import pykat
from pykat.gui.graphics import *
from pykat.node_network import *
from PyQt4.QtGui import *
from PyQt4.Qt import *
class Component() :
def __init__(self, name, kat):
self.__name = name
self._svgItem = None
self.__nodes = []
self._kat = kat
if not isinstance(kat,pykat.finesse.kat):
raise exceptions.ValueError("kat argument is not a pykat.finesse.kat object")
kat.add(self)
def getFinesseText(self):
""" Base class for individual finesse optical components """
raise NotImplementedError("This function is not implemented")
def getQGraphicsItem(self):
return None
def _addNode(self, name):
""" Adds a node in sequential order to the component, i.e. add them
n1, n2, n3, n4... etc. by the name of the node"""
n = self._kat.nodes.createNode(name)
if n == None:
raise exceptions.RuntimeError("getNode did not return a node for '{0}'".format(name))
else:
n.connect(self)
self.__nodes.append(n)
return n
def getNodes(self):
""" Returns a copy of the nodes the component has """
return self.__nodes[:]
def __getname(self):
return self.__name
name = property(__getname)
class Param:
def __init__(self,name,value):
self.value = value
self.__name = name
def getname(self):
return self.__name
name = property(getname)
class mirror(Component):
def __init__(self,kat,name,node1,node2,R=0,T=0,phi=0,Rcx=0,Rcy=0,xbeta=0,ybeta=0):
Component.__init__(self,name,kat)
self.node1 = self._addNode(node1)
self.node2 = self._addNode(node2)
self.R = Param('R',R)
self.T = Param('R',T)
self.phi = Param('phi',phi)
self.Rcx = Param('rcx',Rcx)
self.Rcy = Param('rcy',Rcy)
self.xbeta = Param('xbeta',xbeta)
self.ybeta = Param('ybeta',ybeta)
def _getRc(self):
if self.Rcx == self.Rcy:
return self.Rcx
else:
return [self.Rcx, self.Rcy]
def _setRc(self,value):
self.Rcx = value
self.Rcy = value
Rc = property(_getRc,_setRc)
def getFinesseText(self):
rtn = []
rtn.append('m {0} {1} {2} {3} {4} {5}'.format(
self.name, self.R.value, self.T.value, self.phi.value,
self.node1.name, self.node2.name))
if self.Rcx != 0: rtn.append("attr {0} Rcx {1}".format(self.name,self.Rcx))
if self.Rcy != 0: rtn.append("attr {0} Rcy {1}".format(self.name,self.Rcy))
if self.xbeta != 0: rtn.append("attr {0} xbeta {1}".format(self.name,self.xbeta))
if self.ybeta != 0: rtn.append("attr {0} ybeta {1}".format(self.name,self.ybeta))
return rtn
def getQGraphicsItem(self):
if self._svgItem == None:
self._svgItem = ComponentQGraphicsItem(":/resources/mirror_flat.svg",self
,[(-20,0,self.node1),(20,0,self.node2)])
return self._svgItem
class space(Component):
def __init__(self,kat , name, node1, node2, L=0, n=1):
Component.__init__(self,name,kat)
self.node1 = self._addNode(node1)
self.node2 = self._addNode(node2)
self.length = Param('L',L)
self.refractive_index = Param('n',n)
def getFinesseText(self):
if self.refractive_index.value == 1:
return 's {0} {1} {2} {3}'.format(self.name, self.length.value, self.node1.name, self.node2.name)
else:
return 's {0} {1} {2} {3} {4}'.format(self.name, self.length.value, self.refractive_index.value, self.node1.name, self.node2.name)
class laser(Component):
def __init__(self,kat,name,node,P=1,f_offset=0,phase=0):
Component.__init__(self,name,kat)
self.node = self._addNode(node)
self.power = Param('P', P)
self.f_offset = Param('f', f_offset)
self.phase = Param('phase',phase)
def getFinesseText(self):
if self.phase.value == 0 :
return 'l {0} {1} {2} {3}'.format(self.name, self.power.value, self.f_offset.value, self.node.name)
else :
return 'l {0} {1} {2} {4} {3}'.format(self.name, self.power.value, self.f_offset.value, self.phase.value, self.node.name)
def getQGraphicsItem(self):
if self._svgItem == None:
self._svgItem = ComponentQGraphicsItem(":/resources/laser.svg",self,[(70,0,self.node)])
return self._svgItem
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 01 09:09:10 2013
@author: Daniel
"""
import exceptions
import pykat.gui.resources
from pykat.utils import *
from pykat.gui.graphics import *
from pykat.node_network import *
from PyQt4.QtGui import *
from PyQt4.Qt import *
class Detector() :
def __init__(self, name,node,kat):
self.__name = name
self._svgItem = None
self._kat = kat
kat.add(self)
self.__node = kat.nodes.createNode(node)
self.__node.connect(self)
def getFinesseText(self):
""" Base class for individual finesse optical components """
raise NotImplementedError("This function is not implemented")
def getQGraphicsItem(self):
return None
def getNode(self):
return self.__node;
def __getname(self):
return self.__name
name = property(__getname)
class photodiode(Detector):
def __init__(self,kat,name,node) :
Detector.__init__(self,name,node,kat)
if node.find('*'):
self._alternate_beam = True
node.replace('*','')
self.__node = kat.nodes.createNode(node)
def getFinesseText(self) :
if self._alternate_beam:
return "pd {0} {1}".format(self.name, self.__node.name)
else:
return "pd {0} {1}*".format(self.name, self.__node.name)
def getQGraphicsItem(self):
if self._svgItem == None:
self._svgItem = ComponentQGraphicsItem(":/resources/photodiode_red.svg",self,[(-20,0,self.node)])
return self._svgItem
\ No newline at end of file
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 27 09:56:53 2013
@author: Daniel
"""
import os
import exceptions
import subprocess
import tempfile
import numpy as np
from colorama import Fore
from pykat.node_network import NodeNetwork
from pykat.detectors import Detector
from pykat.components import Component
from pykat.commands import Command
from pykat.gui.gui import *
class MissingFinesseEnvVar(Exception) :
def __str__(self) :
return "The environment variable FINESSE_DIR was not defined"
class kat:
def __init__(self):
self.__components = {}
self.__detectors = {}
self.__commands = {}
self.__gui = None
self.nodes = NodeNetwork(self)
# Various
self.phase = None
self.maxtem = None
self.noxaxis = None
def run(self, printout=1, printerr=1, save_output=False, save_kat=False
,kat_name=None) :
""" Runs the current simulation """
# Get the environment variable for where Finesse is stored
self.__finesse_dir = os.environ.get('FINESSE_DIR')
if self.__finesse_dir == None :
raise exceptions.MissingFinesseEnvVar
katfile = tempfile.TemporaryFile(suffix=".kat")
katfile.writelines(self.generate())
katfile.flush()
kat_exec = os.path.join(self.__finesse_dir,'kat {0}'.format(
katfile.name))
p=subprocess.Popen(kat_exec,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
[out,err] = p.communicate()
if printout == 1: print Fore.GREEN + out
if printerr == 1: print Fore.RED + err
[root,ext] = os.path.splitext(katfile.name)
base = os.path.basename(root)
outfile = root + ".out"
[x,y,hdr] = self.readOutFile(outfile)
if save_output:
newoutfile = "{0}.out".format(base)
cwd = os.path.os.getcwd()
newoutfile = os.path.join(cwd,newoutfile)
os.rename(outfile, newoutfile)
print "Output data saved to '{0}'".format(newoutfile)
if save_kat:
if kat_name == None:
kat_name = "pykat_output"
cwd = os.path.os.getcwd()
newkatfile = os.path.join(cwd, kat_name + ".kat")
os.rename(katfile.name, newkatfile)
print "Kat file saved to '{0}'".format(newkatfile)
katfile.close()
return [x,y,hdr]
def add(self, obj) :
if isinstance(obj, Component):
if obj.name in self.__components :
raise exceptions.ValueError("A component with name '{0}' has already been added".format([obj.name]))
self.__components[obj.name] = obj
self.__add_component(obj)
elif isinstance(obj, Detector):
if obj.name in self.__detectors :
raise exceptions.ValueError("A detector '{0}' has already been added".format(obj.name))
self.__detectors[obj.name] = obj
self.__add_detector(obj)
elif isinstance(obj, Command):
# dont error when adding same command, just replace it
#if obj.__class__.__name__ in self.__commands :
# raise exceptions.ValueError("A command '{0}' has already been added".format([obj.__class__.__name__]))
self.__commands[obj.__class__.__name__] = obj
self.__add_command(obj)
else :
raise exceptions.ValueError("Object could not be added")
# now we have added the component we need to update the node
# network
def readOutFile(self, filename):
outfile = open(filename,'r')
# read first to lines to get to header line
outfile.readline()
outfile.readline()
hdr = outfile.readline().replace('%','').replace('\n','').split(',')
data = np.loadtxt(filename,comments='%')
rows,cols = data.shape
x = data[:,0]
y = data[:,1:cols]
return [x, y, hdr]
def generate(self) :
""" Generates the kat file which can then be run """
if len(self.__components) == 0 :
raise exceptions.RuntimeError("No components have been added")
out = []
for key in self.__components:
txt = self.__components[key].getFinesseText()
if txt != None:
if isinstance(txt,list):
for t in txt: out.append(t+ "\n")
else:
out.append(txt + "\n")
for key in self.__detectors:
out.append(self.__detectors[key].getFinesseText() + "\n")
if self.noxaxis != None and self.noxaxis == True:
out.append("noxaxis\n")
for key in self.__commands:
if self.noxaxis == None or (self.noxaxis == True and isinstance(self.__commands[key], xaxis)):
out.append(self.__commands[key].getFinesseText() + "\n")
if self.phase != None: out.append("phase {0}\n".format(self.phase))
if self.maxtem != None: out.append("maxtem {0}\n".format(self.maxtem))
out.append("gnuterm no\n")
out.append("pyterm no\n")
return out
def openGUI(self):
self.__gui = openGUI(self)
def getComponents(self):
return self.__components.values()
def __add_detector(self, det):
if not isinstance(det, Detector):
raise exceptions.ValueError("Argument is not of type Command")
name = det.name
fget = lambda self: self.__get_command(name)
setattr(self.__class__, name, property(fget))
setattr(self, '__det_' + name, det)
def __get_detector(self, name):
return getattr(self, '__det_' + name)
def __add_command(self, com):
if not isinstance(com, Command):
raise exceptions.ValueError("Argument is not of type Command")
name = com.__class__.__name__
fget = lambda self: self.__get_command(name)
setattr(self.__class__, name, property(fget))
setattr(self, '__com_' + name, com)
def __get_command(self, name):
return getattr(self, '__com_' + name)
def __add_component(self, comp):
if not isinstance(comp, Component):
raise exceptions.ValueError("Argument is not of type Component")
fget = lambda self: self.__get_component(comp.name)
setattr(self.__class__, comp.name, property(fget))
setattr(self, '__comp_' + comp.name, comp)
def __get_component(self, name):
return getattr(self, '__comp_' + name)
\ No newline at end of file
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 11:34:58 2013
@author: Daniel
"""
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 01 09:13:03 2013
@author: Daniel
"""
from PyQt4.QtGui import *
from PyQt4.Qt import *
class NodeQGraphicItem(QGraphicsRectItem):
pass
class ComponentQGraphicsItem(QGraphicsSvgItem):
def __init__(self, svgfile, component, nodes):
QGraphicsSvgItem.__init__(self, svgfile)
self.__component = component
item = QGraphicsTextItem(component.name,self)
rect = item.boundingRect()
item.setPos(-0.5*rect.width(),40-0.5*rect.height())
for n in nodes:
node = NodeQGraphicItem(n[0],n[1],8,8,self)
node.setBrush(QBrush(Qt.red))
node.setPen(QPen(Qt.black))
\ No newline at end of file
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 11:35:48 2013
@author: Daniel
"""
from PyQt4 import QtGui, QtCore
from PyQt4.Qt import *
from PyQt4.QtGui import QCursor
from pykat.gui.graphics import *
import qt_gui
def openGUI(kat):
app = QtGui.QApplication([""])
pykatgui = pyKatGUI(kat)
pykatgui.main()
app.exec_()
class pyKatGUI(QtGui.QMainWindow, qt_gui.Ui_MainWindow):
def __init__(self, kat,parent=None):
super(pyKatGUI, self).__init__(parent)
self.setupUi(self)
# create a new scene
self.__scene = QGraphicsScene()
brush = QBrush()
brush.setStyle(Qt.CrossPattern)
brush.setColor(QColor(230,230,230))
self.__scene.setBackgroundBrush(brush)