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

@author: Daniel
"""
7
8
9
10
11
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

12
from pykat import USE_GUI, HAS_OPTIVIS, NoGUIException
13
14
15
16
17
18

import pykat.external.six as six

if six.PY2:
	import exceptions

19
import warnings
Daniel Brown's avatar
Daniel Brown committed
20
21
22
23
24
import pykat.exceptions as pkex
import pykat
from pykat.node_network import *
from pykat.exceptions import *
import abc
25
26
27
28
29
30
31
32
33
import copy
from collections import OrderedDict

if HAS_OPTIVIS:
    import optivis.bench.components as optivis_components
    from optivis.view.canvas import OptivisCanvasItemDataType
    from optivis.bench.labels import Label as optivis_label
    from optivis.geometry import Coordinates as optivis_coord
    import PyQt4
Daniel Brown's avatar
Daniel Brown committed
34

Daniel Brown's avatar
Daniel Brown committed
35
36
from pykat.SIfloat import *
from pykat.param import Param, AttrParam
37
import weakref
38
import pykat.exceptions as pkex
39
from copy import deepcopy
Daniel Brown's avatar
Daniel Brown committed
40

41
next_component_id = 1
42

43
44
45
46
47
if USE_GUI:
    import pykat.gui.resources
    import pykat.gui.graphics
    from pykat.gui.graphics import *

Daniel Brown's avatar
Daniel Brown committed
48
49
class NodeGaussSetter(object):
    def __init__(self, component, node):                
50
51
        self.__comp = weakref.ref(component)
        self.__node = weakref.ref(node)
Daniel Brown's avatar
Daniel Brown committed
52
53
54
55
56
57
58
59
60
        self.__name = None
        
    @property
    def name(self):
        return self.__name
        
    @name.setter
    def name(self, value):
        self.__name = str(value)
Daniel Brown's avatar
Daniel Brown committed
61
62
63
    
    @property
    def node(self):
64
        return self.__node()
Daniel Brown's avatar
Daniel Brown committed
65
66
67
    
    @property
    def q(self):
68
        return self.__node().qx
Daniel Brown's avatar
Daniel Brown committed
69
70
71
        
    @q.setter
    def q(self, value):
72
        self.__node().setGauss(self.__comp(), complex(value))
Daniel Brown's avatar
Daniel Brown committed
73
74
75
        
    @property
    def qx(self):
76
        return self.__node().qx
Daniel Brown's avatar
Daniel Brown committed
77
78
    @qx.setter
    def qx(self, value):
79
        self.__node().setGauss(self.__comp(), complex(value))
Daniel Brown's avatar
Daniel Brown committed
80
81
82
    
    @property
    def qy(self):
83
        return self.__node().qy
Daniel Brown's avatar
Daniel Brown committed
84
85
    @qy.setter
    def qy(self, value):
86
        self.__node().setGauss(self.__comp(), self.qx, complex(value))
Daniel Brown's avatar
Daniel Brown committed
87
        
88
id_____pykat_class = 0
89
  
Daniel Brown's avatar
Daniel Brown committed
90
91
class Component(object):
    __metaclass__ = abc.ABCMeta
92
93
94
95
96

    def __new__(cls, *args, **kwargs):
        # This creates an instance specific class for the component
        # this enables us to add properties to instances rather than
        # all classes
97
98
99
        global id_____pykat_class
        id_____pykat_class += 1
        cnew_name = str("%s.%s_%i" % (cls.__module__, cls.__name__, id_____pykat_class))
100
101
102
        
        cnew = type(cnew_name, (cls,), {})
        
103
        return object.__new__(cnew)
104
105
        
    def __init__(self, name=None):
106
        self._unfreeze()
107
108
        
        self._optivis_component = None
Daniel Brown's avatar
Daniel Brown committed
109
110
111
112
113
114
        self.__name = name
        self._svgItem = None
        self._requested_node_names = []
        self._kat = None
        self.tag = None
        self._params = []
115
        self.__removed = False
Daniel Brown's avatar
Daniel Brown committed
116
        self._default_fsig_param = None
117
        self.optivisLabelContent = None
Daniel Brown's avatar
Daniel Brown committed
118
119
120
121
        
        # store a unique ID for this component
        global next_component_id
        self.__id = next_component_id
122
        next_component_id += 1    
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
     
    def _freeze(self): self.__dict__["____FROZEN____"] = True
    def _unfreeze(self): self.__dict__["____FROZEN____"] = False
        
    def __setattr__(self, name, value):
        if self.__dict__["____FROZEN____"] and not hasattr(self, name):
            warnings.warn("'%s' does not have attribute called '%s'" % (self.__name, name), stacklevel=2)
            
        if hasattr(self, name) and hasattr(self.__class__, name):
            prop = getattr(self.__class__, name)
            
            if isinstance(prop, property):
                prop.fset(self, value)
                return
                
        self.__dict__[name] = value
         
140
141
142
143
144
145
    def __deepcopy__(self, memo):
        """
        When deep copying a kat object we need to take into account
        the instance specific properties.
        """
        
146
147
148
149
        # Here we create a copy of this object based of the base class
        # of this one, otherwise we're making a copy of a copy of a copy...
        result = self.__class__.__new__(self.__class__.__base__)
        result.__dict__ = copy.deepcopy(self.__dict__, memo)
150
        
151
152
153
        for _ in result._params:
            _._updateOwner(result)
        
154
155
        return result
        
Daniel Brown's avatar
Daniel Brown committed
156
157
    def _register_param(self, param):
        self._params.append(param)
Daniel Brown's avatar
Daniel Brown committed
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    
    def _default_fsig(self):
        """
        Returns what Finesse internally determines as the default 
        fsig parameter. This is used mainly for parsing fsig command
        lines where no target parameter is stated.
        """
        if self._default_fsig_param != None:
            if not self._default_fsig_param.canFsig:
                raise pkex.BasePyKatException("Default fsig parameter %s is not possible to fsig" % (self.__default_fsig_param.name))
            else:
                return self._default_fsig_param
        else:
            return None
    
Daniel Brown's avatar
Daniel Brown committed
173
174
175
176
177
178
179
180
181
182
183
184
185
    def _on_kat_add(self, kat):
        """
        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.
        """
        if self._kat != None:
            raise pkex.BasePyKatException("Component has already been added to a finesse.kat object")
            
        self._kat = kat
        
        kat.nodes.registerComponentNodes(self, self._requested_node_names, self.__on_node_change)
186
187
188
189
190
191
     
    def _on_kat_remove(self):
        # inform all parameters that we have removed its owner
        # so that it can then warn about any puts/vars/xaxis
        for p in self._params:
            p._onOwnerRemoved()
Daniel Brown's avatar
Daniel Brown committed
192
        
193
194
195
196
        del self._params[:]

        self.__removed = True
          
Daniel Brown's avatar
Daniel Brown committed
197
198
199
200
201
202
203
204
205
    def __on_node_change(self):
        # 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)]
206

Daniel Brown's avatar
Daniel Brown committed
207
208
209
        # now we have a list of which to remove
        for key in key_rm:
            ns = self.__dict__[key]
210
211
212
213
            name = str(ns.node.name)
            
            if '__nodesetter_' + name in self.__dict__:
                delattr(self, '__nodesetter_' + name)
214
            
215
216
217
218
            if name in self.__class__.__dict__:
                delattr(self.__class__, name)
        
        # Now re-add them pointing to the recent nodes
Daniel Brown's avatar
Daniel Brown committed
219
220
221
222
223
224
        for node in self.nodes:
            if type(node) != pykat.node_network.DumpNode:
                ns = NodeGaussSetter(self, node)
                self.__add_node_setter(ns)
        
    def __add_node_setter(self, ns):
225
226
        self._unfreeze()
        
Daniel Brown's avatar
Daniel Brown committed
227
228
229
        if not isinstance(ns, NodeGaussSetter):
            raise exceptions.ValueError("Argument is not of type NodeGaussSetter")
        
230
        name = str(ns.node.name)
Daniel Brown's avatar
Daniel Brown committed
231
        fget = lambda self: self.__get_node_setter(name)
232
            
Daniel Brown's avatar
Daniel Brown committed
233
234
235
        setattr(self.__class__, name, property(fget))
        setattr(self, '__nodesetter_' + name, ns)                   

236
237
        self._freeze()
        
Daniel Brown's avatar
Daniel Brown committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
    def __get_node_setter(self, name):
        return getattr(self, '__nodesetter_' + name)   
        
    @staticmethod
    @abc.abstractmethod
    def parseFinesseText(text):
        """Parses Finesse syntax"""
        raise NotImplementedError("This function is not implemented")

    @abc.abstractmethod
    def getFinesseText(self):
        """ Base class for individual Finesse optical components """    
        raise NotImplementedError("This function is not implemented")

    @abc.abstractmethod
    def getQGraphicsItem(self):    
254
255
256
        if not USE_GUI:
            raise NoGUIException
            
Daniel Brown's avatar
Daniel Brown committed
257
258
        return None      
    
259
260
261
    @property
    def removed(self): return self.__removed
    
Daniel Brown's avatar
Daniel Brown committed
262
263
264
265
266
267
268
269
270
271
272
    @property
    def nodes(self): return self._kat.nodes.getComponentNodes(self) 
    
    @property    
    def name(self): return self.__name      
    
    @property
    def id(self): return self.__id
    
    def __str__(self): return self.name
    
273
    def remove(self):
274
275
276
277
        if self.__removed:
            raise pkex.BasePyKatException("{0} has already been marked as removed".format(self.name))
        else:
            self._kat.remove(self)
278
279
280
281
282
283
    
    def getOptivisParameterDict(self):
        if len(self._params) == 0:
            return None
            
        d = OrderedDict()
284
        
285
286
        for p in self._params:
            d[p.name] = OptivisCanvasItemDataType.TEXTBOX
287
        
288
        return d
289
        
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
    def getOptivisTooltip(self):
        tooltip = "Name: %s" % self.name
        
        for p in self._params:
            if p.value is not None:
                tooltip += "\n%s = %s" %(p.name, str(p.value))
        
        return tooltip

    def setOptivisLabelContent(self):
        """
        Sets default Optivis label contents
        """

        if self.optivisLabelContent is None:
            self.optivisLabelContent = {}

        self.optivisLabelContent["Name"] = self.name


Daniel Brown's avatar
Daniel Brown committed
310
311
class AbstractMirrorComponent(Component):
    __metaclass__ = abc.ABCMeta
312
        
Daniel Brown's avatar
Daniel Brown committed
313
    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):
Daniel Brown's avatar
Daniel Brown committed
314
        super(AbstractMirrorComponent, self).__init__(name)
315
 
Daniel Brown's avatar
Daniel Brown committed
316
        if (L != None and R != None and T != None) and SIfloat(R)+SIfloat(T)+SIfloat(L) != 1: 
317
            raise pkex.BasePyKatException('L+R+T must equal 1 if all are specified at {0}'.format(self.name))
318
        elif (R != None and L is None and T != None):
Daniel Brown's avatar
Daniel Brown committed
319
            L = 1- (SIfloat(R)+SIfloat(T))
320
        elif (R is None and L != None and T != None):
Daniel Brown's avatar
Daniel Brown committed
321
            R = 1 - (SIfloat(L)+SIfloat(T))
322
        elif (R != None and L != None and T is None):
Daniel Brown's avatar
Daniel Brown committed
323
            T = 1 - (SIfloat(L)+SIfloat(R))
324
        elif (L is None and R is None and T is None):
325
326
            raise pkex.BasePyKatException('Must specify at least two of L, R or T')
        
Daniel Brown's avatar
Daniel Brown committed
327
328
        self.__R = Param("R", self, SIfloat(R))
        self.__T = Param("T", self, SIfloat(T))
329
330
        self.__L = Param("L", self, SIfloat(L))
        
331
        self.__phi = Param("phi", self, SIfloat(phi), canFsig=True, fsig_name="phase")
Daniel Brown's avatar
Daniel Brown committed
332
333
        self.__Rcx = AttrParam("Rcx", self, SIfloat(Rcx))
        self.__Rcy = AttrParam("Rcy", self, SIfloat(Rcy))
334
335
        self.__xbeta = AttrParam("xbeta", self, SIfloat(xbeta), canFsig=True, fsig_name="xbeta")
        self.__ybeta = AttrParam("ybeta", self, SIfloat(ybeta), canFsig=True, fsig_name="ybeta")
Daniel Brown's avatar
Daniel Brown committed
336
        self.__mass = AttrParam("mass", self, SIfloat(mass))
Daniel Brown's avatar
Daniel Brown committed
337
338
        self.__Ix = AttrParam("Ix", self, SIfloat(Ix))
        self.__Iy = AttrParam("Iy", self, SIfloat(Iy))
Daniel Brown's avatar
Daniel Brown committed
339
        self.__r_ap = AttrParam("r_ap", self, SIfloat(r_ap))
340
    
Daniel Brown's avatar
Daniel Brown committed
341
342
343
344
        self.__zmech = AttrParam("zmech", self, zmech)
        self.__rxmech = AttrParam("rxmech", self, rxmech)
        self.__rymech = AttrParam("rymech", self, rymech)
        
345
346
347
348
349
350
        self.__z = Param("z", self, None, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="z")
        self.__rx = Param("rx", self, None, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="rx")
        self.__ry = Param("ry", self, None, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="ry")
        self.__Fz = Param("Fz", self, None, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="Fz")
        self.__Frx = Param("Frx", self, None, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="Frx")
        self.__Fry = Param("Fry", self, None, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="Fry")
351
        
352
353
354
355
356
        self.__Fs0 = Param("Fs0", self, None, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="Fs0")
        self.__Fs1 = Param("Fs1", self, None, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="Fs1")
        self.__Fs0 = Param("s0", self, None, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="s0")
        self.__Fs1 = Param("s1", self, None, canFsig=True, isPutable=False, isPutter=False, isTunable=False, fsig_name="s1")
            
Daniel Brown's avatar
Daniel Brown committed
357
        self._default_fsig_param = self.__phi
358
359
360
361
362
363
    
    def setRTL(self, R=None, T=None, L=None):
        if R is not None: self.R.value = R
        if T is not None: self.T.value = T
        if L is not None: self.L.value = L
    
364
365
366
367
368
369
370
371
372
373
374
375
376
    @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
    
377
378
379
    @property
    def L(self): return self.__L
    @L.setter
380
    def L(self,value): self.__L.value = SIfloat(value)       
Daniel Brown's avatar
Daniel Brown committed
381
382
383
384
385
386
387
388
389
390
391
        
    @property
    def r_ap(self): return self.__r_ap
    @r_ap.setter
    def r_ap(self,value): self.__r_ap.value = SIfloat(value)

    @property
    def mass(self): return self.__mass
    @mass.setter
    def mass(self,value): self.__mass.value = SIfloat(value)
    
Daniel Brown's avatar
Daniel Brown committed
392
393
394
395
396
397
398
399
400
401
    @property
    def Ix(self): return self.__Ix
    @Ix.setter
    def Ix(self,value): self.__Ix.value = SIfloat(value)
    
    @property
    def Iy(self): return self.__Iy
    @Iy.setter
    def Iy(self,value): self.__Iy.value = SIfloat(value)
    
Daniel Brown's avatar
Daniel Brown committed
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
    @property
    def R(self): return self.__R
    @R.setter
    def R(self,value): self.__R.value = SIfloat(value)
    
    @property
    def T(self): return self.__T
    @T.setter
    def T(self,value): self.__T.value = SIfloat(value)
        
    @property
    def phi(self): return self.__phi
    @phi.setter
    def phi(self,value): self.__phi.value = SIfloat(value)
    
    @property
    def Rcx(self): return self.__Rcx
    @Rcx.setter
    def Rcx(self,value): self.__Rcx.value = SIfloat(value)
    
    @property
    def Rcy(self): return self.__Rcy
    @Rcy.setter
    def Rcy(self,value): self.__Rcy.value = SIfloat(value)
    
    @property
    def xbeta(self): return self.__xbeta
    @xbeta.setter
    def xbeta(self,value): self.__xbeta.value = SIfloat(value)
    
    @property
    def ybeta(self): return self.__ybeta
    @ybeta.setter
    def ybeta(self,value): self.__ybeta.value = SIfloat(value)
    
Daniel Brown's avatar
Daniel Brown committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
    @property
    def zmech(self): return self.__zmech
    @zmech.setter
    def zmech(self,value): self.__zmech.value = value
    
    @property
    def rxmech(self): return self.__rxmech
    @rxmech.setter
    def rxmech(self,value): self.__rxmech.value = value
    
    @property
    def rymech(self): return self.__rymech
    @rymech.setter
    def rymech(self,value): self.__rymech.value = value
    
Daniel Brown's avatar
Daniel Brown committed
452
453
454
455
456
457
458
459
460
461
462
463
    @property
    def Rc(self):
        if self.Rcx == self.Rcy:
            return self.Rcx
        else:
            return [self.Rcx, self.Rcy]
    
    @Rc.setter
    def Rc(self,value):
        self.Rcx.value = SIfloat(value)
        self.Rcy.value = SIfloat(value)

Daniel Brown's avatar
Daniel Brown committed
464
465
466
467
468
469
470
    def parseAttribute(self, key, value):
        if key in ["Rcx", "Rx", "ROCx", "rx", "rcx", "rocx"]:
            self.Rcx = value
        elif key in ["Rcy", "Ry", "ROCy", "ry", "rcy", "rocy"]:
            self.Rcy = value
        elif key in ["Rc", "ROC", "r", "rc", "roc"]:
            self.Rc = value
Daniel Brown's avatar
Daniel Brown committed
471
        elif key in ["M","m", "Mass", "mass"]:
Daniel Brown's avatar
Daniel Brown committed
472
            self.mass = value
Daniel Brown's avatar
Daniel Brown committed
473
        elif key in ["xbeta", "xBeta"]:
Daniel Brown's avatar
Daniel Brown committed
474
            self.xbeta = value
Daniel Brown's avatar
Daniel Brown committed
475
        elif key in ["ybeta","yBeta"]:
Daniel Brown's avatar
Daniel Brown committed
476
477
478
479
480
481
482
            self.ybeta = value
        elif key in ["x_off"]:
            self.x_offset = value
        elif key in ["y_off"]:
            self.y_offset = value
        elif key in ["r_ap"]:
            self.r_ap = value
Daniel Brown's avatar
Daniel Brown committed
483
484
485
486
        elif key in ["Ix","ix"]:
            self.Ix = value
        elif key in ["Iy","iy"]:
            self.Iy = value
Daniel Brown's avatar
Daniel Brown committed
487
488
489
490
491
492
        elif key in ["zmech", "mech"]:
            self.zmech = value
        elif key in ["rxmech"]:
            self.rxmech = value
        elif key in ["rymech"]:
            self.rymech = value
Daniel Brown's avatar
Daniel Brown committed
493
494
495
496
497
        else:
            return False
            
        return True
        
Daniel Brown's avatar
Daniel Brown committed
498
class mirror(AbstractMirrorComponent):
499
    def __init__(self,name,node1,node2,R=None,T=None,L=None,phi=0,Rcx=None,Rcy=None,xbeta=None,ybeta=None,mass=None, r_ap=None):
Daniel Brown's avatar
Daniel Brown committed
500
        super(mirror, self).__init__(name, R, T, L, phi, Rcx, Rcy, xbeta, ybeta, mass, r_ap)
Daniel Brown's avatar
Daniel Brown committed
501
502
503
        
        self._requested_node_names.append(node1)
        self._requested_node_names.append(node2)
504
505
        self._freeze()
        
Daniel Brown's avatar
Daniel Brown committed
506
507
508
509
510
511
    def parseAttributes(self, values):
        
        for key in values.keys():
            if not self.parseAttribute(key, values[key]):
                raise pkex.BasePyKatException("No attribute {0} for mirrors".format(key))
        
Daniel Brown's avatar
Daniel Brown committed
512
513
    @staticmethod
    def parseFinesseText(text):
514
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
515
516

        if values[0] != "m" and values[0] != "m1" and values[0] != "m2":
517
            raise pkex.BasePyKatException("'{0}' not a valid Finesse mirror command".format(text))
Daniel Brown's avatar
Daniel Brown committed
518
519
        
        if len(values) != 7:
520
            raise pkex.BasePyKatException("Mirror Finesse code format incorrect '{0}'".format(text))
Daniel Brown's avatar
Daniel Brown committed
521
522
523

        if len(values[0])==1:
            values.pop(0) # remove initial value
Daniel Brown's avatar
Daniel Brown committed
524
            return mirror(values[0], values[4], values[5], L=None, R=values[1], T=values[2], phi=values[3])
Daniel Brown's avatar
Daniel Brown committed
525
526
527
        else:
            if values[0][1]=="1":
                values.pop(0) # remove initial value
Daniel Brown's avatar
Daniel Brown committed
528
                return mirror(values[0], values[4], values[5], R=None, L=values[2], T=values[1], phi=values[3])
Daniel Brown's avatar
Daniel Brown committed
529
530
            else:
                values.pop(0) # remove initial value
Daniel Brown's avatar
Daniel Brown committed
531
                return mirror(values[0], values[4], values[5], T=None, R=values[1], L=values[2], phi=values[3])
Daniel Brown's avatar
Daniel Brown committed
532

533
    def getFinesseText(self):
534
535
        if abs(self.R + self.T + self.L - 1) > 1e-14:
            raise pkex.BasePyKatException("Mirror {0} has R+T+L = {1}, must equal 1 +- 1e-14".format(self.name, self.R+self.T+self.L))
536
        
Daniel Brown's avatar
Daniel Brown committed
537
538
539
540
541
542
543
544
545
546
        rtn = []
            
        rtn.append('m {0} {1} {2} {3} {4} {5}'.format(
                self.name, self.R.value, self.T.value, self.phi.value,
                self.nodes[0].name, self.nodes[1].name))

        for p in self._params:
            rtn.extend(p.getFinesseText())
                    
        return rtn
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
    
    def getOptivisComponent(self):
        self.setOptivisLabelContent()
        
        if self._optivis_component is None:
            self._optivis_component = optivis_components.CavityMirror(name=self.name, aoi=0, tooltip=self.getOptivisTooltip, paramList=self.getOptivisParameterDict(), pykatObject=weakref.ref(self))
            
            lbl = optivis_label(text="", position=optivis_coord(0, -1), item=self._optivis_component)
            lbl.content["Name"] = self.name
            self._optivis_component.labels.append(lbl)
        
        return self._optivis_component
    
    def getOptivisNode(self, mode, kat_node):
        mode = mode.lower()
        
        if mode != "input" and mode.lower() != "output":
            raise pkex.BasePyKatException("Mode must be either input or output not %s" % mode)
        
        if mode == "input":
            if kat_node is self.nodes[0]:
                return self._optivis_component.getInputNode("fr")
            else:
                return self._optivis_component.getInputNode("bk")
                
        elif mode == "output":
            if kat_node is self.nodes[0]:
                return self._optivis_component.getOutputNode("fr")
            else:
                return self._optivis_component.getOutputNode("bk")
          
Daniel Brown's avatar
Daniel Brown committed
578
579
        
    def getQGraphicsItem(self):
580
581
582
        if not USE_GUI:
            raise NoGUIException
            
583
        if self._svgItem is None:
Daniel Brown's avatar
Daniel Brown committed
584
585
586
587
588
            self._svgItem = pykat.gui.graphics.ComponentQGraphicsItem(":/resources/mirror_flat.svg", self ,[(-4,15,self.nodes[0]), (14,15,self.nodes[1])])
            
        return self._svgItem

class beamSplitter(AbstractMirrorComponent):
589
590
    def __init__(self, name, node1, node2, node3, node4, R = None, T = None, L=None, phi = 0, alpha = 0, Rcx = None, Rcy = None, xbeta = None, ybeta = None, mass = None, r_ap = None):
        super(beamSplitter, self).__init__(name, R, T, L, phi, Rcx, Rcy, xbeta, ybeta, mass, r_ap)
Daniel Brown's avatar
Daniel Brown committed
591
592
593
594
595
        
        self._requested_node_names.append(node1)
        self._requested_node_names.append(node2)
        self._requested_node_names.append(node3)
        self._requested_node_names.append(node4)
Daniel Brown's avatar
Daniel Brown committed
596
        self.__alpha = Param("alpha", self, SIfloat(alpha))
597
598

        self._freeze()
599
        
Daniel Brown's avatar
Daniel Brown committed
600
601
602
603
604
    @property
    def alpha(self): return self.__alpha
    @alpha.setter
    def alpha(self,value): self.__alpha.value = SIfloat(value)
    
Daniel Brown's avatar
Daniel Brown committed
605
606
607
608
609
610
611
612
    def parseAttributes(self, values):
        
        for key in values.keys():
            if not self.parseAttribute(key, values[key]):
                if key == "alpha":
                    self.alpha = values[key]
                else:
                    raise pkex.BasePyKatException("No attribute {0} for mirrors".format(key))
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
    
    def getOptivisComponent(self):
        self.setOptivisLabelContent()
        
        if self._optivis_component is None:
            self._optivis_component = optivis_components.BeamSplitter(name=self.name, aoi=-self.alpha, tooltip=self.getOptivisTooltip, paramList=self.getOptivisParameterDict(), pykatObject=weakref.ref(self))
        
        return self._optivis_component
    
    def getOptivisNode(self, mode, kat_node):
        mode = mode.lower()
        
        if mode != "input" and mode.lower() != "output":
            raise pkex.BasePyKatException("Mode must be either input or output")
        
        if mode == "input":
            if kat_node is self.nodes[0]:
                return self._optivis_component.getInputNode("frA")
            elif kat_node is self.nodes[1]:
                return self._optivis_component.getInputNode("frB")
            elif kat_node is self.nodes[2]:
                return self._optivis_component.getInputNode("bkB")
            elif kat_node is self.nodes[3]:
                return self._optivis_component.getInputNode("bkA")
        elif mode == "output":
            if kat_node is self.nodes[0]:
                return self._optivis_component.getOutputNode("frB")
            elif kat_node is self.nodes[1]:
                return self._optivis_component.getOutputNode("frA")
            elif kat_node is self.nodes[2]:
                return self._optivis_component.getOutputNode("bkA")
            elif kat_node is self.nodes[3]:
                return self._optivis_component.getOutputNode("bkB")
                     
Daniel Brown's avatar
Daniel Brown committed
647
648
    @staticmethod
    def parseFinesseText(text):
649
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
650
651

        if values[0] != "bs" and values[0] != "bs1" and values[0] != "bs2":
652
            raise pkex.BasePyKatException("'{0}' not a valid Finesse beam splitter command".format(text))
Daniel Brown's avatar
Daniel Brown committed
653
654
        
        if len(values) != 10:
655
            raise pkex.BasePyKatException("Beam splitter Finesse code format incorrect '{0}'".format(text))
Daniel Brown's avatar
Daniel Brown committed
656

657
        if len(values[0])==2:
Daniel Brown's avatar
Daniel Brown committed
658
            values.pop(0) # remove initial value
Daniel Brown's avatar
Daniel Brown committed
659
660
            return beamSplitter(values[0], values[5], values[6], values[7], values[8],
                                values[1], values[2], None, values[3], values[4])
661
662
        elif values[0][2]=="1":
            values.pop(0) # remove initial value
Daniel Brown's avatar
Daniel Brown committed
663
664
            return beamSplitter(values[0], values[5], values[6], values[7], values[8],
                                None, values[1], values[2], values[3], values[4])
Daniel Brown's avatar
Daniel Brown committed
665
        else:
666
            values.pop(0) # remove initial value
Daniel Brown's avatar
Daniel Brown committed
667
668
            return beamSplitter(values[0], values[5], values[6], values[7], values[8],
                                values[1], None, values[2], values[3], values[4])
669
        
Daniel Brown's avatar
Daniel Brown committed
670
    def getFinesseText(self):
671
672
        if abs(self.R + self.T + self.L - 1) > 1e-14:
            raise pkex.BasePyKatException("Beamsplitter {0} has R+T+L = {1}, must equal 1 +- 1e-14".format(self.name, self.R+self.T+self.L))
Daniel Brown's avatar
Daniel Brown committed
673

Daniel Brown's avatar
Daniel Brown committed
674
675
676
        rtn = []
            
        rtn.append('bs {0} {1} {2} {3} {4} {5} {6} {7} {8}'.format(
677
678
                self.name, self.R.value, self.T.value, self.phi.value,
                self.alpha.value, self.nodes[0].name,
Daniel Brown's avatar
Daniel Brown committed
679
680
681
682
683
684
685
686
687
                self.nodes[1].name, self.nodes[2].name,
                self.nodes[3].name))

        for p in self._params:
            rtn.extend(p.getFinesseText())
            
        return rtn
        
    def getQGraphicsItem(self):
688
689
690
        if not USE_GUI:
            raise NoGUIException
            
691
        if self._svgItem is None:
Daniel Brown's avatar
Daniel Brown committed
692
            # FIXME: make proper SVG component for beam splitter
693
            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])])
Daniel Brown's avatar
Daniel Brown committed
694
695
696
697
            
        return self._svgItem
   
class space(Component):
698
    def __init__(self, name, node1, node2, L = 0, n = 1, g = None, gx = None, gy = None):
Daniel Brown's avatar
Daniel Brown committed
699
700
701
702
703
        Component.__init__(self, name)
        
        self._requested_node_names.append(node1)
        self._requested_node_names.append(node2)
        self._QItem = None
Daniel Brown's avatar
Daniel Brown committed
704
        self.__L = Param("L", self, SIfloat(L), canFsig=True, fsig_name="phase")
Daniel Brown's avatar
Daniel Brown committed
705
        self.__n = Param("n", self, SIfloat(n))
706

707
708
        self.__gx = AttrParam("gx", self, gx)
        self.__gy = AttrParam("gy", self, gy)
Daniel Brown's avatar
Daniel Brown committed
709
        
Daniel Brown's avatar
Daniel Brown committed
710
        self._default_fsig_param = self.__L
711
712

        self._freeze()
Daniel Brown's avatar
Daniel Brown committed
713
        
Daniel Brown's avatar
Daniel Brown committed
714
715
716
    @property
    def L(self): return self.__L
    @L.setter
Andreas Freise's avatar
Andreas Freise committed
717
    def L(self,value): self.__L.value = SIfloat(value)
Daniel Brown's avatar
Daniel Brown committed
718
719
720
721
    @property
    def n(self): return self.__n
    @n.setter
    def n(self,value): self.__n.value = SIfloat(value)
722
723

    @property
Daniel Brown's avatar
Daniel Brown committed
724
725
726
727
728
729
    def g(self):
        if self.__gx.value == self.__gy.value: 
            return self.__g
        else:
            raise pkex.BasePyKatException("Gouy phase in x and y directions are different, use gx and gy properties instead")
            
730
    @g.setter
Daniel Brown's avatar
Daniel Brown committed
731
732
733
734
    def g(self,value):
        self.__gx.value = SIfloat(value)
        self.__gy.value = SIfloat(value)
        
735
736
737
738
739
740
741
742
743
    @property
    def gx(self): return self.__gx
    @gx.setter
    def gx(self,value): self.__gx.value = SIfloat(value)

    @property
    def gy(self): return self.__gy
    @gy.setter
    def gy(self,value): self.__gy.value = SIfloat(value)
Daniel Brown's avatar
Daniel Brown committed
744
    
745
746
747
748
749
750
751
752
753
754
755
756
    def connectingComponents(self):
        """
        Returns the two components that this space connects.
        """
        a = list(self.nodes[0].components + self.nodes[1].components)
        a = [value for value in a if value != self]
        
        if len(a) != 2:
            raise pkex.BasePyKatException("Space should only connect 2 components")
            
        return a
        
Daniel Brown's avatar
Daniel Brown committed
757
758
759
760
761
762
763
    def parseAttributes(self, values):
        
        for key in values.keys():
            if key in ["gx","gouyx"]:
                self.__gx.value = values[key]
            elif key in ["gy", "gouyy"]:
                self.__gy.value = values[key]
764
            elif key in ["g","gouy"]:
Daniel Brown's avatar
Daniel Brown committed
765
766
767
768
769
                self.__gx.value = values[key]
                self.__gy.value = values[key]
            else:
                raise pkex.BasePyKatException("No attribute {0} for spaces".format(key))
                
Daniel Brown's avatar
Daniel Brown committed
770
771
    @staticmethod
    def parseFinesseText(text):
772
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
773
774

        if values[0] != "s":
775
            raise pkex.BasePyKatException("'{0}' not a valid Finesse space command".format(text))
Daniel Brown's avatar
Daniel Brown committed
776
777
778
779
780
781
782
783

        values.pop(0) # remove initial value
        
        if len(values) == 5:
            return space(values[0], values[3], values[4], values[1], values[2])
        elif len(values) == 4:
            return space(values[0], values[2], values[3], values[1])
        else:
784
            raise pkex.BasePyKatException("Space Finesse code format incorrect '{0}'".format(text))
Daniel Brown's avatar
Daniel Brown committed
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
        
    def getFinesseText(self):
        rtn = []
        
        if self.__n == 1:
            rtn.append('s {0} {1} {2} {3}'.format(self.name, self.__L.value, self.nodes[0].name, self.nodes[1].name))
        else:
            rtn.append('s {0} {1} {2} {3} {4}'.format(self.name, self.__L.value, self.__n.value, self.nodes[0].name, self.nodes[1].name))
       
        for p in self._params:
            rtn.extend(p.getFinesseText())
            
        return rtn
        
    def getQGraphicsItem(self):
800
801
802
        if not USE_GUI:
            raise NoGUIException
            
803
        if self._QItem is None:
Daniel Brown's avatar
Daniel Brown committed
804
805
806
807
808
            self._QItem = pykat.gui.graphics.SpaceQGraphicsItem(self)
        
        return self._QItem

class grating(Component):
809
    def __init__(self, name, node1, node2, node3 = None, node4 = None, n = 2, d = 0, eta_0 = None, eta_1 = None, eta_2 = None, eta_3 = None, rho_0 = None, alpha = None): # TODO: implement Rcx, Rcy and Rc
Daniel Brown's avatar
Daniel Brown committed
810
811
812
813
814
815
816
817
818
        Component.__init__(self, name)
        
        self._requested_node_names.append(node1)
        self._requested_node_names.append(node2)

        if n > 2:
            if node3 != None:
                self._requested_node_names.append(node3)
            else:
819
                raise pkex.BasePyKatException("Grating node 3 not specified")
Daniel Brown's avatar
Daniel Brown committed
820
821
822
823
824

        if n > 3:
            if node4 != None:
                self._requested_node_names.append(node4)
            else:
825
                raise pkex.BasePyKatException("Grating node 4 not specified")
Daniel Brown's avatar
Daniel Brown committed
826
827

        if n > 4 or n < 2:
828
            raise pkex.BasePyKatException("Grating must have between 2 and 4 ports")
Daniel Brown's avatar
Daniel Brown committed
829
830
831
832
833
834
835
836
837
        
        self.__n = n
        self.__d = Param("d", self, SIfloat(d))
        self.__eta_0 = AttrParam("eta_0", self, SIfloat(eta_0))
        self.__eta_1 = AttrParam("eta_1", self, SIfloat(eta_1))
        self.__eta_2 = AttrParam("eta_2", self, SIfloat(eta_2))
        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))
838
        self._svgItem = None
839
840

        self._freeze()
841
        
Daniel Brown's avatar
Daniel Brown committed
842
843
844
845
846
    @property
    def n(self): return Param('n', self.__n)
    @n.setter
    def n(self, value):
        if value < 2 or value > 4:
847
            raise pkex.BasePyKatException("Grating must have between 2 and 4 ports")
Daniel Brown's avatar
Daniel Brown committed
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
        else:
            self.__n = value
    
    @property
    def d(self): return self.__d
    @d.setter
    def d(self, value): self.__d.value = SIfloat(value)
    
    @property
    def eta_0(self): return self.__eta_0
    @eta_0.setter
    def eta_0(self, value): self.__eta_0.value = SIfloat(value)
    
    @property
    def eta_1(self): return self.__eta_1
    @eta_1.setter
    def eta_1(self, value): self.__eta_1.value = SIfloat(value)
    
    @property
    def eta_2(self): return self.__eta_2
    @eta_2.setter
    def eta_2(self, value): self.__eta_2.value = SIfloat(value)
    
    @property
    def eta_3(self): return self.__eta_3
    @eta_3.setter
    def eta_3(self, value): self.__eta_3.value = SIfloat(value)
    
    @property
    def rho_0(self): return self.__rho_0
    @rho_0.setter
    def rho_0(self, value): self.__rho_0.value = SIfloat(value)
    
    @property
    def alpha(self): return self.__alpha
    @alpha.setter
    def alpha(self, value): self.__alpha.value = SIfloat(value)
    
    @staticmethod
    def parseFinesseText(text):
888
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
889
890

        if values[0][0 : 2] != "gr":
891
            raise pkex.BasePyKatException("'{0}' not a valid Finesse grating command".format(text))
Daniel Brown's avatar
Daniel Brown committed
892
893
894

        if len(values[0]) > 2:
            if int(values[0][2]) > 4 or int(values[0][2]) < 2:
895
                raise pkex.BasePyKatException("Grating must have between 2 and 4 ports")
Daniel Brown's avatar
Daniel Brown committed
896
897
898
899
900
901
902
903
904
            else:
                n = int(values[0][2])
        else:
            n = 2

        values.pop(0) # remove initial value
        
        if n == 2:
            if len(values) != 4:
905
                raise pkex.BasePyKatException("Two port grating must have 2 nodes defined")
Daniel Brown's avatar
Daniel Brown committed
906
907
908
909

            return grating(values[0], values[2], values[3], None, None, n, values[1])
        elif n == 3:
            if len(values) != 5:
910
                raise pkex.BasePyKatException("Three port grating must have 3 nodes defined")
Daniel Brown's avatar
Daniel Brown committed
911
912
913
914
            
            return grating(values[0], values[2], values[3], values[4], None, n, values[1])
        else:
            if len(values) != 6:
915
                raise pkex.BasePyKatException("Four port grating must have 4 nodes defined")
Daniel Brown's avatar
Daniel Brown committed
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
            
            return grating(values[0], values[2], values[3], values[4], values[5], n, values[1])
        
    def getFinesseText(self):
        rtn = []
        
        if self.__n == 2:
            rtn.append('gr{0} {1} {2} {3} {4}'.format(self.__n, self.name, self.__d.value, self.nodes[0].name, self.nodes[1].name))
        elif self.__n == 3:
            rtn.append('gr{0} {1} {2} {3} {4} {5}'.format(self.__n, self.name, self.__d.value, self.nodes[0].name, self.nodes[1].name, self.nodes[2].name))
        else:
            rtn.append('gr{0} {1} {2} {3} {4} {5} {6}'.format(self.__n, self.name, self.__d.value, self.nodes[0].name, self.nodes[1].name, self.nodes[2].name, self.nodes[3].name))
        
        for p in self._params:
            rtn.extend(p.getFinesseText())
        
        return rtn
       
    def getQGraphicsItem(self):
935
936
937
        if not USE_GUI:
            raise NoGUIException
            
938
        if self._svgItem is None:
939
            self._svgItem = pykat.gui.graphics.SpaceQGraphicsItem(self) # TODO: make SVG graphic for grating
Daniel Brown's avatar
Daniel Brown committed
940
        
941
        return self._svgItem
Daniel Brown's avatar
Daniel Brown committed
942
943

class isolator(Component):
944
    def __init__(self, name, node1, node2, S = 0, node3="dump", option = 0, L = 0):
945
946
947
948
949
950
951
952
953
954
955
956
957
958
        """
        Creates an isolator component. Ligth passes from node 1 to node 2, and from node
        2 to node 3. 

        S         Suppression factor for the reversed direction [power dB].
        L         Loss, fraction of input power loss. Number between 0 and 1.
        option    0: Light passes from node1 to node2, and from node2 to node3. Light
                     is suppressed when going from node3 to node2, and from node2 to
                     node1.
                  1: Light passes from node2 to node1, and from node3 to node2. Light
                     is suppressed when going from node1 to node2, and from node2 to
                     node3. 
        """
        
Daniel Brown's avatar
Daniel Brown committed
959
960
961
962
        Component.__init__(self, name)
        
        self._requested_node_names.append(node1)
        self._requested_node_names.append(node2)
963
        self._requested_node_names.append(node3)
964
        self._svgItem = None
965
        self._option = option
Daniel Brown's avatar
Daniel Brown committed
966
967
        
        self.__S = Param("S",self,SIfloat(S))
968
969
        self.__L = Param("L",self,SIfloat(L))

970
        self._freeze()
Daniel Brown's avatar
Daniel Brown committed
971
972
973
974
975
        
    @property
    def S(self): return self.__S
    @S.setter
    def S(self, value): self.__S.value = SIfloat(value)
976
977
978
979
980

    @property
    def L(self): return self.__L
    @L.setter
    def L(self, value): self.__L.value = SIfloat(value)
Daniel Brown's avatar
Daniel Brown committed
981
982
983
    
    @staticmethod
    def parseFinesseText(text):
984
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
985

986
        if values[0] != "isol" and values[0] != "isol*":
987
            raise pkex.BasePyKatException("'{0}' not a valid Finesse isolator command".format(text))
Daniel Brown's avatar
Daniel Brown committed
988

989
990
991
992
993
        if values[0].endswith('*'):
            option = 1
        else:
            option = 0
            
Daniel Brown's avatar
Daniel Brown committed
994
995
996
        values.pop(0) # remove initial value
        
        if len(values) == 4:
997
            return isolator(values[0], values[2], values[3], values[1], option=option)
998
        elif len(values) == 5:
999
            # Checking if loss is specified, should be a number.
1000
1001
1002
            if values[2].isnumeric():
                return isolator(values[0], values[3], values[4], values[1],
                                L=values[2], option=option)
1003
            # .. if not a number, it's a node name.
1004
1005
1006
1007
1008
            else:
                return isolator(values[0], values[2], values[3], node3=values[4],
                                S=values[1], option=option)
        elif len(values) == 6:
             return isolator(values[0], values[3], values[4], values[1], values[5], option, values[2])
Daniel Brown's avatar
Daniel Brown committed
1009
        else:
1010
            raise pkex.BasePyKatException("Isolator Finesse code format incorrect '{0}'".format(text))
Daniel Brown's avatar
Daniel Brown committed
1011
1012
        
    def getFinesseText(self):
1013
1014
1015
1016
1017
        if self._option == 0:
            cmd = "isol"
        elif self._option == 1:
            cmd = "isol*"
            
1018
        rtn = ['{cmd} {0} {1} {2} {3} {4} {5}'.format(self.name, self.S.value, self.L.value, self.nodes[0].name, self.nodes[1].name, self.nodes[2].name, cmd=cmd)]
Daniel Brown's avatar
Daniel Brown committed
1019
1020
1021
        
        for p in self._params:
            rtn.extend(p.getFinesseText())
1022

Daniel Brown's avatar
Daniel Brown committed
1023
        return rtn
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
    
    def getOptivisComponent(self):
        self.setOptivisLabelContent()
        
        if self._optivis_component is None:
            self._optivis_component = optivis_components.FaradayIsolator(name=self.name, tooltip=self.getOptivisTooltip, paramList=self.getOptivisParameterDict(), pykatObject=weakref.ref(self))
        
        return self._optivis_component
    
    def getOptivisNode(self, mode, kat_node):
        mode = mode.lower()
        
        if mode != "input" and mode.lower() != "output":
            raise pkex.BasePyKatException("Mode must be either input or output")
        
        if mode == "input":
            if kat_node is self.nodes[0]:
                return self._optivis_component.getInputNode("fr")
            elif kat_node is self.nodes[1]:
                return self._optivis_component.getInputNode("bk")
        elif mode == "output":
            if kat_node is self.nodes[0]:
                return self._optivis_component.getnOutputNode("fr")
            elif kat_node is self.nodes[1]:
                return self._optivis_component.getOutputNode("bk")
     
     
Daniel Brown's avatar
Daniel Brown committed
1051
    def getQGraphicsItem(self):
1052
1053
1054
        if not USE_GUI:
            raise NoGUIException
            
1055
        if self._svgItem is None:
1056
            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])])
Daniel Brown's avatar
Daniel Brown committed
1057
        
1058
        return self._svgItem
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
        
        
        
class isolator1(Component):
    def __init__(self, name, node1, node2, node3, node4):
        """
        Creates a 4-port isolator component.
        """
        
        Component.__init__(self, name)
        
        self._requested_node_names.append(node1)
        self._requested_node_names.append(node2)
        self._requested_node_names.append(node3)
        self._requested_node_names.append(node4)
        self._svgItem = None

1076
1077
        self._freeze()
        
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
    @staticmethod
    def parseFinesseText(text):
        values = text.split()

        if values[0] != "isol1":
            raise pkex.BasePyKatException("'{0}' not a valid Finesse isolator command".format(text))
            
        values.pop(0) # remove initial value
        
        if len(values) == 5:
             return isolator1(values[0], values[1], values[2], values[3], values[4])
        else:
            raise pkex.BasePyKatException("Isolator1 Finesse code format incorrect '{0}'".format(text))
        
    def getFinesseText(self):
        rtn = ['isol1 {0} {1} {2} {3} {4}'.format(self.name, self.nodes[0].name,
                                              self.nodes[1].name, self.nodes[2].name,
                                              self.nodes[3].name)]
        
        for p in self._params:
            rtn.extend(p.getFinesseText())

        return rtn
        
1102
1103
    def getQGraphicsItem(self):
        raise NotImplemented()    
1104
        
Daniel Brown's avatar
Daniel Brown committed
1105
1106

class lens(Component):
Daniel Brown's avatar
Daniel Brown committed
1107
    def __init__(self, name, node1, node2, f=1, p=None):
Daniel Brown's avatar
Daniel Brown committed
1108
1109
        Component.__init__(self, name)
        
Daniel Brown's avatar
Daniel Brown committed
1110
1111
1112
        if not ((f is None) ^ (p is None)):
            raise pkex.BasePyKatException("Specify either a focal length or power, not both.")
        
Daniel Brown's avatar
Daniel Brown committed
1113
1114
        self._requested_node_names.append(node1)
        self._requested_node_names.append(node2)
1115
        self._svgItem = None
Daniel Brown's avatar
Daniel Brown committed
1116
        self.__f = Param("f", self, SIfloat(f))
Daniel Brown's avatar
Daniel Brown committed
1117
        self.__p = Param("p", self, SIfloat(p))
1118
1119

        self._freeze()
Daniel Brown's avatar
Daniel Brown committed
1120
1121
1122
        
    @property
    def f(self): return self.__f
Daniel Brown's avatar
Daniel Brown committed
1123
            
Daniel Brown's avatar
Daniel Brown committed
1124
    @f.setter
Daniel Brown's avatar
Daniel Brown committed
1125
1126
1127
1128
1129
    def f(self, value):
        self.__f.value = SIfloat(value)
        self.__p.value = None
    
    @property
Daniel Brown's avatar
Daniel Brown committed
1130
    def p(self): return self.__p
Daniel Brown's avatar
Daniel Brown committed
1131
            
Daniel Brown's avatar
Daniel Brown committed
1132
    @p.setter
Daniel Brown's avatar
Daniel Brown committed
1133
1134
1135
    def p(self, value):
        self.__p.value = SIfloat(value)
        self.__f.value = None
Daniel Brown's avatar
Daniel Brown committed
1136
1137
1138
    
    @staticmethod
    def parseFinesseText(text):
1139
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
1140

Daniel Brown's avatar
Daniel Brown committed
1141
        if not values[0].startswith("lens"):
1142
            raise pkex.BasePyKatException("'{0}' not a valid Finesse lens command".format(text))
Daniel Brown's avatar
Daniel Brown committed
1143

Daniel Brown's avatar
Daniel Brown committed
1144
1145
        alt = values[0].endswith("*")
        
Daniel Brown's avatar
Daniel Brown committed
1146
1147
1148
        values.pop(0) # remove initial value
        
        if len(values) == 4:
Daniel Brown's avatar
Daniel Brown committed
1149
1150
1151
1152
            if not alt:
                return lens(values[0], values[2], values[3], f=values[1], p=None)
            else:
                return lens(values[0], values[2], values[3], f=None, p=values[1])
Daniel Brown's avatar
Daniel Brown committed
1153
        else:
1154
            raise pkex.BasePyKatException("Lens Finesse code format incorrect '{0}'".format(text))
Daniel Brown's avatar
Daniel Brown committed
1155
1156
        
    def getFinesseText(self):
Daniel Brown's avatar
Daniel Brown committed
1157
        if self.__p.value is None:
Daniel Brown's avatar
Daniel Brown committed
1158
1159
1160
            rtn = ['lens {0} {1} {2} {3}'.format(self.name, self.f.value, self.nodes[0].name, self.nodes[1].name)]
        else:
            rtn = ['lens* {0} {1} {2} {3}'.format(self.name, self.p.value, self.nodes[0].name, self.nodes[1].name)]
Daniel Brown's avatar
Daniel Brown committed
1161
1162
1163
1164
1165
        
        for p in self._params:
            rtn.extend(p.getFinesseText())
            
        return rtn
1166
1167
1168
1169
1170
1171
    
    def getOptivisComponent(self):
        self.setOptivisLabelContent()
        
        if self._optivis_component is None:
            self._optivis_component = optivis_components.ConvexLens(name=self.name, tooltip=self.getOptivisTooltip, paramList=self.getOptivisParameterDict(), pykatObject=weakref.ref(self))
Daniel Brown's avatar
Daniel Brown committed
1172
        
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
        return self._optivis_component
    
    def getOptivisNode(self, mode, kat_node):
        mode = mode.lower()
        
        if mode != "input" and mode.lower() != "output":
            raise pkex.BasePyKatException("Mode must be either input or output")
        
        if mode == "input":
            if kat_node is self.nodes[0]:
                return self._optivis_component.getInputNode("fr")
            elif kat_node is self.nodes[1]:
                return self._optivis_component.getInputNode("bk")
        elif mode == "output":
            if kat_node is self.nodes[0]:
                return self._optivis_component.getnOutputNode("fr")
            elif kat_node is self.nodes[1]:
                return self._optivis_component.getOutputNode("bk")
                
Daniel Brown's avatar
Daniel Brown committed
1192
    def getQGraphicsItem(self):
1193
1194
1195
        if not USE_GUI:
            raise NoGUIException
            
1196
        if self._svgItem is None:
1197
            self._svgItem = pykat.gui.graphics.ComponentQGraphicsItem(":/resources/lens.svg", self ,[(-4,15,self.nodes[0]), (14,15,self.nodes[1])])