components.py 12.4 KB
Newer Older
Daniel Brown's avatar
Daniel Brown committed
1
2
3
4
5
6
7
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 11:10:01 2013

@author: Daniel
"""
import exceptions
8
import pykat.exceptions as pkex
Daniel Brown's avatar
Daniel Brown committed
9
10
import pykat
from pykat.node_network import *
Daniel Brown's avatar
Daniel Brown committed
11
12
13
14

import pykat.gui.resources
import pykat.gui.graphics
from pykat.gui.graphics import *
Daniel Brown's avatar
Daniel Brown committed
15

16
17
18
19
20
21
22
23
24
25
26
27
28
29
next_component_id = 1

class NodeGaussSetter:
    def __init__(self, component, node):
    
        if not isinstance(component, Component):
            raise pkex.BasePyKatException("Value passed is not a Component")
        
        if not isinstance(node, Node):
            raise pkex.BasePyKatException("Value passed is not a Node")        
            
        self._comp = component
        self._node = node
        
30
class Component(object) :
31
    def __init__(self, name):
Daniel Brown's avatar
Daniel Brown committed
32
33
        self.__name = name
        self._svgItem = None
34
        self._nodes = None
35
36
        self._requested_node_names = []
        self._kat = None
37
38
39
40
41
42
43
        
        # store a unique ID for this component
        global next_component_id
        self.__id = next_component_id
        next_component_id += 1
        
    def _on_kat_add(self, kat, node_array):
44
        """
45
46
47
48
        Called when this component has been added to a kat object.
        kat is the finesse.kat object which it now belongs to and
        node_array is an array specific to this object which contains
        references to the nodes that are attached to it.
49
        """
50
51
52
        if self._kat != None:
            raise pkex.BasePyKatException("Component has already been added to a finesse.kat object")
            
53
54
55
        self._kat = kat
        
        for node_name in self._requested_node_names:
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
            node = self.__addNode(node_name)
        
        # now that we have changed what our nodes are we need to
        # update stuff...
        self._on_node_change()
        
    def _on_node_change():
        # need to update the node gauss parameter setter members 
        self.__update_node_setters()
        
    def __update_node_setters(self):
        # check if any node setters have already been added. If so we
        # need to remove them. This function should get called if the nodes
        # are updated, either by some function call or the GUI
        key_rm = [k for k in self.__dict__ if k.startswith("__nodesetter_", 0, 13)]
        # now we have a list of which to remove
        for key in key_rm:
            ns = self.__dict__[key]
            detattr(self, '__nodesetter_' + ns._node.name)
            delattr(self.__class__, ns._node.name)
    
        for node_name in self.getNodes():
            self.__add_node_setter(NodeGaussSetter(self, node))
        
    def __add_node_setter(self, ns):

        if not isinstance(ns, NodeGaussSetter):
            raise exceptions.ValueError("Argument is not of type NodeGaussSetter")
        
        name = ns.__class__.__name__
        fget = lambda self: self.__get_node_setter(name)
        
        setattr(self.__class__, name, property(fget))
        setattr(self, '__nodesetter_' + name, ns)                   

    def __get_node_setter(self, name):
        return getattr(self, '__nodesetter_' + name)   
93
94
95
96
        
    @staticmethod
    def parseFinesseText(text):    
        raise NotImplementedError("This function is not implemented")
97
98
99
    
    def setAttr(name, value):    
        raise NotImplementedError("This function is not implemented")
Daniel Brown's avatar
Daniel Brown committed
100
101
102
103
104
105
106
107
        
    def getFinesseText(self):
        """ Base class for individual finesse optical components """    
        raise NotImplementedError("This function is not implemented")
        
    def getQGraphicsItem(self):    
        return None      
        
108
    def __addNode(self, name):            
Daniel Brown's avatar
Daniel Brown committed
109
110
111
        n = self._kat.nodes.createNode(name)
        
        if n == None:
112
            raise exceptions.RuntimeError("createNode did not return a node for '{0}'".format(name))
Daniel Brown's avatar
Daniel Brown committed
113
        else:
114
            n.connect(self)
115
                        
Daniel Brown's avatar
Daniel Brown committed
116
117
118
119
        return n
        
    def getNodes(self):
        """ Returns a copy of the nodes the component has """
120
121
122
123
124
125
126
127
128
        return self._kat.nodes.getComponentNodes(self)        
    
    @property    
    def name(self): return self.__name      
    
    @property
    def id(self): return self.__id
    
    
Daniel Brown's avatar
Daniel Brown committed
129
    
130
131
132
133
class Param(float):
    def __new__(self,name,value):
        return float.__new__(self,value)
         
Daniel Brown's avatar
Daniel Brown committed
134
135
136
    def __init__(self,name,value):
        self.__name = name
        
137
138
    name = property(lambda self: self.__name)
           
Daniel Brown's avatar
Daniel Brown committed
139
class mirror(Component):
Daniel Brown's avatar
Daniel Brown committed
140
    def __init__(self,name,node1,node2,R=0,T=0,phi=0,Rcx=0,Rcy=0,xbeta=0,ybeta=0,mass=0, r_ap=0):
Daniel Brown's avatar
Daniel Brown committed
141
        
142
        Component.__init__(self,name)
Daniel Brown's avatar
Daniel Brown committed
143
        
144
145
        self._requested_node_names.append(node1)
        self._requested_node_names.append(node2)
Daniel Brown's avatar
Daniel Brown committed
146
147

        self.__r_ap = float(r_ap)        
148
        self.__mass = float(mass)
149
150
151
152
153
154
155
        self.__R = float(R)
        self.__T = float(T)
        self.__phi = float(phi)
        self.__Rcx = float(Rcx)
        self.__Rcy = float(Rcy)
        self.__xbeta = float(xbeta)
        self.__ybeta = float(ybeta)
156
    
Daniel Brown's avatar
Daniel Brown committed
157
158
159
160
161
    @property
    def r_ap(self): return Param('r_ap', self.__mass)
    @r_ap.setter
    def r_ap(self,value): self.__aperture = float(value)

162
163
164
165
166
    @property
    def mass(self): return Param('mass', self.__mass)
    @mass.setter
    def mass(self,value): self.__mass = float(value)
    
167
    @property
168
    def R(self): return Param('R', self.__R)
169
    @R.setter
170
171
    def R(self,value): self.__R = float(value)
    
172
173
174
    @property
    def T(self): return Param('T', self.__T)
    @T.setter
175
    def T(self,value): self.__T = float(value)
176
177
178
179
        
    @property
    def phi(self): return Param('phi', self.__phi)
    @phi.setter
180
    def phi(self,value): self.__phi = float(value)
181
182
183
184
    
    @property
    def Rcx(self): return Param('Rcx', self.__Rcx)
    @Rcx.setter
185
186
    def Rcx(self,value): self.__Rcx = float(value)
    
187
188
189
    @property
    def Rcy(self): return Param('Rcy', self.__Rcy)
    @Rcy.setter
190
    def Rcy(self,value): self.__Rcy = float(value)
191
192
193
194
    
    @property
    def xbeta(self): return Param('xbeta', self.__xbeta)
    @xbeta.setter
195
    def xbeta(self,value): self.__xbeta = float(value)
196
    
197
198
199
    @property
    def ybeta(self): return Param('ybeta', self.__ybeta)
    @ybeta.setter
200
    def ybeta(self,value): self.__ybeta = float(value)
201
202
203
    
    @property
    def Rc(self):
Daniel Brown's avatar
Daniel Brown committed
204
205
206
207
208
        if self.Rcx == self.Rcy:
            return self.Rcx
        else:
            return [self.Rcx, self.Rcy]
    
209
210
    @Rc.setter
    def Rc(self,value):
211
212
        self.Rcx = float(value)
        self.Rcy = float(value)
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    
    @staticmethod
    def parseFinesseText(text):
        values = text.split(" ")

        if values[0] != "m":
            raise exceptions.RuntimeError("'{0}' not a valid Finesse mirror command".format(text))

        values.pop(0) # remove initial value
        
        if len(values) != 6:
            raise exceptions.RuntimeError("Mirror Finesse code format incorrect '{0}'".format(text))

        return mirror(values[0], values[4], values[5], R=values[1], T=values[2], phi=values[3])
Daniel Brown's avatar
Daniel Brown committed
227
228
229
        
    def getFinesseText(self):        
        rtn = []
230
231
232
233
234
        nodes = self.getNodes()
        
        if len(nodes) != 2:
            raise exceptions.RuntimeError("Not enough nodes for mirror")
            
Daniel Brown's avatar
Daniel Brown committed
235
        rtn.append('m {0} {1} {2} {3} {4} {5}'.format(
236
                self.name, self.__R, self.__T, self.__phi,
237
                nodes[0].name, nodes[1].name))
Daniel Brown's avatar
Daniel Brown committed
238
239

        if self.r_ap != 0: rtn.append("attr {0} r_ap {1}".format(self.name,self.__r_ap))            
240
        if self.mass != 0: rtn.append("attr {0} mass {1}".format(self.name,self.__mass))
241
242
243
244
        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))
Daniel Brown's avatar
Daniel Brown committed
245
246
247
248
249
        
        return rtn
        
    def getQGraphicsItem(self):
        if self._svgItem == None:
250
            nodes = self.getNodes()
Daniel Brown's avatar
Daniel Brown committed
251
252
            self._svgItem = pykat.gui.graphics.ComponentQGraphicsItem(":/resources/mirror_flat.svg", self ,[(-4,15,nodes[0]), (14,15,nodes[1])])
            
Daniel Brown's avatar
Daniel Brown committed
253
254
255
256
        return self._svgItem
   
   
class space(Component):
257
258
    def __init__(self, name, node1, node2, L=0, n=1):
        Component.__init__(self,name,)
Daniel Brown's avatar
Daniel Brown committed
259
        
260
261
        self._requested_node_names.append(node1)
        self._requested_node_names.append(node2)
Daniel Brown's avatar
Daniel Brown committed
262
        
263
264
        self.__L = float(L)
        self.__n = float(n)
265
266
267
268
269
        self._QItem = None
        
    @property
    def L(self): return Param('L', self.__L)
    @L.setter
270
    def L(self,value): self.__L = float(value)
271
272
273
    @property
    def n(self): return Param('n', self.__n)
    @n.setter
274
    def n(self,value): self.__n = float(value)
275
    
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
    @staticmethod
    def parseFinesseText(text):
        values = text.split(" ")

        if values[0] != "s":
            raise exceptions.RuntimeError("'{0}' not a valid Finesse space command".format(text))

        values.pop(0) # remove initial value
        
        if len(values) == 5:
            return space(values[0],values[3],values[4],L=values[1],n=values[2])
        elif len(values) == 4:
            return space(values[0],values[2],values[3],L=values[1])
        else:
            raise exceptions.RuntimeError("Space Finesse code format incorrect '{0}'".format(text))
        
Daniel Brown's avatar
Daniel Brown committed
292
    def getFinesseText(self):
293
294
        nodes = self.getNodes()
        
295
        if self.__n == 1:
296
            return 's {0} {1} {2} {3}'.format(self.name, self.__L, nodes[0].name, nodes[1].name)            
Daniel Brown's avatar
Daniel Brown committed
297
        else:
298
            return 's {0} {1} {2} {3} {4}'.format(self.name, self.__L, self.__n, nodes[0].name, nodes[1].name)            
Daniel Brown's avatar
Daniel Brown committed
299
       
300
301
    def getQGraphicsItem(self):
        if self._QItem == None:
302
            self._QItem = pykat.gui.graphics.SpaceQGraphicsItem(self)
303
304
305
        
        return self._QItem  

306
307
308
309
310
311
312
313
    def changeNode(self, node_old, node_new):
        '''
        Called when a space's node has been connected
        to another components node
        '''
        node_new.connect(self)
        node_old.disconnect(self)
        
Daniel Brown's avatar
Daniel Brown committed
314
315
        if self._nodes[0] == node_old:
            self._nodes[0] = node_new
316
        
Daniel Brown's avatar
Daniel Brown committed
317
318
        if self._nodes[1] == node_old:
            self._nodes[1] = node_new
319
320

    
Daniel Brown's avatar
Daniel Brown committed
321
class laser(Component):
322
323
324
325
    def __init__(self,name,node,P=1,f_offset=0,phase=0):
        Component.__init__(self,name)
        
        self._requested_node_names.append(node)
Daniel Brown's avatar
Daniel Brown committed
326
        
327
328
329
        self.__power = float(P)
        self.__f_offset = float(f_offset)
        self.__phase = float(phase)
Daniel Brown's avatar
Daniel Brown committed
330
        
331
332
333
    @property
    def power(self): return Param('P', self.__power)
    @power.setter
334
    def power(self,value): self.__power = float(value)
335
336
337
338
    
    @property
    def f_offset(self): return Param('f', self.__f_offset)
    @f_offset.setter
339
    def f_offset(self,value): self.__f_offset = float(value)
340
341
342
343
    
    @property
    def phase(self): return Param('phase', self.__phase)
    @phase.setter
344
    def phase(self,value): self.__phase = float(value)
345
    
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
    @staticmethod
    def parseFinesseText(text):
        values = text.split(" ")

        if values[0] != "l":
            raise exceptions.RuntimeError("'{0}' not a valid Finesse laser command".format(text))

        values.pop(0) # remove initial value
        
        if len(values) == 5:
            return laser(values[0],values[4],P=values[1],f_offset=values[2],phase=values[3])
        elif len(values) == 4:
            return laser(values[0],values[3],P=values[1],f_offset=values[2], phase=0)
        else:
            raise exceptions.RuntimeError("Laser Finesse code format incorrect '{0}'".format(text))
    
Daniel Brown's avatar
Daniel Brown committed
362
    def getFinesseText(self):
363
364
365
        nodes = self.getNodes()
        
        return 'l {0} {1} {2} {3} {4}'.format(self.name, self.__power, self.__f_offset, self.__phase, nodes[0].name)            
Daniel Brown's avatar
Daniel Brown committed
366
367
368
         
    def getQGraphicsItem(self):
        if self._svgItem == None:
369
            nodes = self.getNodes()
370
            self._svgItem = pykat.gui.graphics.ComponentQGraphicsItem(":/resources/laser.svg",
371
                                                   self,[(65,25,nodes[0])])
Daniel Brown's avatar
Daniel Brown committed
372
373
374
            
        return self._svgItem