detectors.py 36.7 KB
Newer Older
Daniel Brown's avatar
Daniel Brown committed
1
2
# -*- coding: utf-8 -*-
"""
Daniel Brown's avatar
Daniel Brown committed
3
Created on Fri Feb 01 0split()9:09:10 2013
Daniel Brown's avatar
Daniel Brown committed
4
5
6

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

import pykat.external.six as six
if six.PY2:
14
    import exceptions
15

Daniel Brown's avatar
Daniel Brown committed
16
import abc
Daniel Brown's avatar
Daniel Brown committed
17
from pykat.node_network import *
18
from pykat.param import Param, AttrParam
19
from pykat.SIfloat import SIfloat
20

21
import pykat.external.six as six
22
import pykat.exceptions as pkex
23
24

import collections
25
import warnings
26
import copy
Daniel Brown's avatar
Daniel Brown committed
27

28
29
30
31
32
from pykat import USE_GUI, NoGUIException

if USE_GUI:
    import pykat.gui.resources
    from pykat.gui.graphics import *
Daniel Brown's avatar
updates    
Daniel Brown committed
33

34
id_____pykat_class = 0
Daniel Brown's avatar
updates    
Daniel Brown committed
35

36
class BaseDetector(object) :
37
38
39
40
    """
    This is a base class for all detectors. Classes Detector1 and Detector2 should be used directly.
    This base class can handled detectors connected to multiple nodes.
    """
41
    
42
43
    __metaclass__ = abc.ABCMeta
    
Daniel Brown's avatar
updates    
Daniel Brown committed
44
45
46
47
    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
48
49
50
        global id_____pykat_class
        id_____pykat_class += 1
        cnew_name = str("%s.%s_%i" % (cls.__module__, cls.__name__, id_____pykat_class))
Daniel Brown's avatar
updates    
Daniel Brown committed
51
52
53
        
        cnew = type(cnew_name, (cls,), {})
        
54
        return object.__new__(cnew)
Daniel Brown's avatar
updates    
Daniel Brown committed
55
        
56
    def __init__(self, name, nodes=None, max_nodes=1):
57
58

        self.__dict__["____FROZEN____"] = False
59
        
Daniel Brown's avatar
Daniel Brown committed
60
61
62
63
64
65
66
        self.__name = name
        self._svgItem = None
        self._kat = None
        self.noplot = False
        self.enabled = True
        self.tag = None
        self._params = []
67
        self._mask = {}
Daniel Brown's avatar
Daniel Brown committed
68
        self.__scale = []
69
        self.__removed = False
70
        self.noplot = False
71
        
72
73
74
75
76
        self._alternate_beam = []
        self._nodes = []
        self._requested_nodes = []
        
        if nodes != None:
77
78
            if isinstance(nodes, (list, tuple)):
                
79
80
81
82
83
84
85
86
87
88
89
                if len(nodes) > max_nodes:
                    raise pkex.BasePyKatException("Tried to set too many nodes, %s, maximum number is %i." %(str(nodes),max_nodes))
                    
                for n in nodes:
                    if n[-1]=='*':
                        self._alternate_beam.append(True)
                        n = n[:-1]
                    else:
                        self._alternate_beam.append(False)
                        
                    self._requested_nodes.append(n)
90
            elif isinstance(nodes, six.string_types):
91
92
93
94
95
96
97
98
                # if we don't have a collection
                if nodes[-1]=='*':
                    self._alternate_beam.append(True)
                    nodes = nodes[:-1]
                else:
                    self._alternate_beam.append(False)
                    
                self._requested_nodes.append(nodes)
99
100
            else:
                raise pkex.BasePyKatException("Nodes should be a list or tuple of node names or a singular node name as a string.")
Daniel Brown's avatar
updates    
Daniel Brown committed
101
    
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    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
    
Daniel Brown's avatar
updates    
Daniel Brown committed
118
119
120
121
122
123
124
125
126
127
128
129
    def __deepcopy__(self, memo):
        """
        When deep copying a kat object we need to take into account
        the instance specific properties.
        """
        
        # 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)
        
        return result
130
                
Daniel Brown's avatar
Daniel Brown committed
131
132
133
134
    def _register_param(self, param):
        self._params.append(param)
        
    def _on_kat_add(self, kat):
135
136
        self._kat = kat
        
137
138
139
        for rn in self._requested_nodes:
            if rn != None:
                self._nodes.append(kat.nodes.createNode(rn))
Daniel Brown's avatar
Daniel Brown committed
140
    
141
142
143
    def _on_kat_remove(self):
        self.__removed = True
        
144
145
146
147
148
149
150
151
    def remove(self):
        if self.__removed:
            raise pkex.BasePyKatException("{0} has already been marked as removed".format(self.name))
        else:
            self._kat.remove(self)
    
        self.__removed = True
        
Daniel Brown's avatar
Daniel Brown committed
152
153
154
155
156
157
    @staticmethod
    def parseFinesseText(text):    
        raise NotImplementedError("This function is not implemented")
        
    def getFinesseText(self):
        """ Base class for individual finesse optical components """    
158
159
160
161
162
163
        #raise NotImplementedError("This function is not implemented")
        
        if self.noplot:
            return ["noplot " + self.name]
        else:
            return []
Daniel Brown's avatar
Daniel Brown committed
164
165
        
    def getQGraphicsItem(self):    
166
167
168
        if not USE_GUI:
            raise NoGUIException
            
Daniel Brown's avatar
Daniel Brown committed
169
        return None
170

171
172
173
    @property
    def removed(self): return self.__removed
    
174
175
176
    @property 
    def scale(self): return self.__scale
    @scale.setter
177
    def scale(self, value):
Daniel Brown's avatar
Daniel Brown committed
178
179
        if value not in self.__scale:
            self.__scale = value
Daniel Brown's avatar
Daniel Brown committed
180
181
182
183
184
185
    
    @property
    def name(self): return self.__name        

    def __str__(self): return self.name

186
    def mask(self, n, m, factor):
187
        _id = str(n)+"_"+str(m)
188
189
190
        
        # if the mask is 1 then remove this so it doesn't get 
        # printed as by default the value is 1.0
191
192
193
194
195
196
        if _id in self._mask and factor == 1.0:
            del self._mask[_id]
                
        self._mask[_id] = factor

    def _set_node(value, index):
197
        if self._kat is None:
198
199
200
201
202
203
204
205
206
207
208
209
210
            raise pkex.BasePyKatException("This detector has not been added to a kat object yet")
        else:
            if value[-1] == '*':
                self._alternate_beam[index] = True
                value = value[:-1]
            else:
                self._alternate_beam[index] = False
                
            if value in self._kat.nodes:
                self._nodes[index] = self._kat.nodes[value]
            else:
                raise pkex.BasePyKatException("There is no node called " + value + " in the kat object this detector is attached to.")
    
Daniel Brown's avatar
Daniel Brown committed
211
212
    def _getScaleCmds(self, rtn):
        if self.scale != None:
213
            if isinstance(self.scale, six.string_types):
Daniel Brown's avatar
Daniel Brown committed
214
215
216
217
218
219
                rtn.append("scale {1} {0}".format(self.name, self.scale))
            elif isinstance(self.scale, (list, tuple)):
                for s in self.scale:
                    rtn.append("scale {1} {0}".format(self.name, s))
            else:
                raise pkex.BasePyKatException("Scale command should either be a list of scales or a single string.")
Daniel Brown's avatar
Daniel Brown committed
220
221
222
223
224
225
226

class Detector0(BaseDetector):
    """
    A detector that attaches to no nodes.
    """
    pass
                        
227
class Detector1(BaseDetector):
228
229
230
    """
    A detector that attaches to one node.
    """
231
    @property 
232
    def node(self): return self._nodes[0]
233
234
235
236
237
238
    @node.setter
    def node(self, value):
        self._set_node(value, 0)      
        
                
class Detector2(BaseDetector):
239
240
241
    """
    A detector that attaches to two node.
    """
242
243
    
    @property 
244
    def node1(self): return self._nodes[0]
245
246
247
248
249
    @node1.setter
    def node(self, value):
        self._set_node(value, 0)
        
    @property 
250
    def node2(self): return self._nodes[1]
251
252
253
254
255
    @node2.setter
    def node(self, value):
        self._set_node(value, 1)
                
                
Daniel Brown's avatar
Daniel Brown committed
256
257
258
259
260
261
262
263
class beam(Detector1):
    
    def __init__(self, name, node_name, frequency=None, alternate_beam=False):
        BaseDetector.__init__(self, name, node_name)
        
        self.alternate_beam = alternate_beam
        self.__f = Param("f", self, frequency)        
    
264
265
        self._freeze()
        
Daniel Brown's avatar
Daniel Brown committed
266
267
268
269
270
271
272
273
274
275
276
    @property
    def f(self): return self.__f
    
    @f.setter
    def f(self, value):
        self.__f.value = value
        
    @staticmethod
    def parseFinesseText(text):
        
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
277

Daniel Brown's avatar
Daniel Brown committed
278
279
280
281
282
283
        node=values[-1]
        alt_beam = node[-1] == '*'
        
        if len(values) == 3:
            return beam(values[1], node, alternate_beam=alt_beam)
        elif len(values) == 4:
Daniel Brown's avatar
mend    
Daniel Brown committed
284
            return beam(values[1], node, alternate_beam=alt_beam, frequency=SIfloat(values[2]))
Daniel Brown's avatar
Daniel Brown committed
285
286
287
288
        else:
            raise pkex.BasePyKatException('Beam detector code "{0}" is not a valid FINESSE command'.format(text))
    
    def getFinesseText(self) :
289
        rtn = BaseDetector.getFinesseText(self)
Daniel Brown's avatar
Daniel Brown committed
290
291
292
293
294
295
296
297
298
299
        
        if self.alternate_beam:
            alt = '*'
        else:
            alt = ''
        
        if self.f.value is None:
            rtn.append("beam {name} {node}{alt}".format(name=self.name, node=self.node.name, alt=alt))
        else:
            rtn.append("beam {name} {f} {node}{alt}".format(name=self.name, f=str(self.f.value), node=self.node.name, alt=alt))
300
        
Daniel Brown's avatar
Daniel Brown committed
301
302
303
304
305
        for p in self._params:
            rtn.extend(p.getFinesseText())
        
        return rtn
        
306
307
308
309
310
311
312
313
class cp(Detector0):
    
    def __init__(self, name, cavity, direction, parameter):
        BaseDetector.__init__(self, name, None)
        
        self.cavity = str(cavity)
        self.direction = direction
        self.parameter = parameter
314
315
        
        self._freeze()
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353

    @property
    def direction(self): return self.__direction
    @direction.setter
    def direction(self, value):
        if value.lower() not in ["x", "y"]:
            raise pkex.BasePyKatException('Cavity parameter detector direction must be x or y.')
    
        self.__direction = value
        
        
    @property
    def parameter(self): return self.__param
    @parameter.setter
    def parameter(self, value):
        
        params = ["w0","w","zr","z","r","q","finesse","m","stability","loss","length","fsr","fwhm","pole","gouy","fsep","A","B","C","D"]

        if value not in params:
            raise pkex.BasePyKatException('Cavity parameter detector direction must be one of: ' + ", ".join(params))
    
        self.__param = value


    @staticmethod
    def parseFinesseText(text): 
        values = text.split()
        
        if len(values) == 4:
            # For FINESSE version < 2.1
            # Old format the name of the detector is a combination of the arguments
            return cp(values[1] + "_" + values[2] + "_" + values[3], values[1], values[2], values[3])
        elif len(values) == 5:
            return cp(values[1], values[2], values[3], values[4])
        else:
            raise pkex.BasePyKatException('Cavity parameter detector code "{0}" is not a valid FINESSE command'.format(text))
            
    def getFinesseText(self) :
354
        rtn = BaseDetector.getFinesseText(self)
355
356
357
358
359
360
361
362
        
        rtn.append("cp {name} {cavity} {direction} {parameter}".format(name=self.name,
                                                                   cavity=str(self.cavity),
                                                                   direction=self.direction,
                                                                   parameter=self.parameter))
        
        return rtn
        
Daniel Brown's avatar
Daniel Brown committed
363
364
365
366
367
368
369
class xd(Detector0):
    
    def __init__(self, name, component, motion):
        BaseDetector.__init__(self, name, None)
        
        self.component = component
        self.motion = motion
370
371
    
        self._freeze()
Daniel Brown's avatar
Daniel Brown committed
372
373
374
375
376
377
378
379
380
381
382

    @staticmethod
    def parseFinesseText(text): 
        values = text.split()
        
        if len(values) == 4:
            return xd(values[1], values[2], values[3])
        else:
            raise pkex.BasePyKatException('Motion detector code "{0}" is not a valid FINESSE command'.format(text))
            
    def getFinesseText(self) :
383
        rtn = BaseDetector.getFinesseText(self)
Daniel Brown's avatar
Daniel Brown committed
384
        
Daniel Brown's avatar
Daniel Brown committed
385
386
387
388
389
390
        rtn.append("xd {name} {component} {motion}".format(name=self.name,
                                                           component=self.component,
                                                           motion=self.motion))
        
        return rtn
              
Daniel Brown's avatar
Daniel Brown committed
391
        
392
class ad(Detector1):
Daniel Brown's avatar
Daniel Brown committed
393
394
    
    def __init__(self, name, frequency, node_name, mode=None, alternate_beam=False):
395
        BaseDetector.__init__(self, name, node_name)
Daniel Brown's avatar
Daniel Brown committed
396
397
398
        self.mode = mode
        self.alternate_beam = alternate_beam
        self.__f = Param("f", self, frequency)
Daniel Brown's avatar
Daniel Brown committed
399
    
400
401
        self._freeze()
    
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
    @property
    def mode(self): return self.__mode
    @mode.setter
    def mode(self, value):
        if value != None and len(value) != 2:
            raise pkex.BasePyKatException('Mode must be a container of length 2, first element the x mode and second the y mode')
    
        self.__mode = value
        
    @property
    def f(self): return self.__f
    @f.setter
    def f(self, value): 
        self.__f.value = value
        
    @staticmethod
    def parseFinesseText(text): 
        values = text.split()
420
421
422

        node=values[-1]
        alt_beam = node[-1] == '*'
Daniel Brown's avatar
Daniel Brown committed
423
424
425
        if len(values) == 6:
            return ad(values[1], values[4], values[5], mode = [int(values[2]), int(values[3])], alternate_beam=alt_beam)
        elif len(values) == 4:
426
            return ad(values[1], values[2], values[3], alternate_beam=alt_beam)
Daniel Brown's avatar
Daniel Brown committed
427
428
429
430
        else:
            raise pkex.BasePyKatException('Amplitude detector code "{0}" is not a valid FINESSE command'.format(text))
            
    def getFinesseText(self) :
431
        rtn = BaseDetector.getFinesseText(self)
Daniel Brown's avatar
Daniel Brown committed
432
433
434
435
436
437
        
        if self.alternate_beam:
            alt = '*'
        else:
            alt = ''
        
438
        if self.mode is None:
Daniel Brown's avatar
Daniel Brown committed
439
440
            rtn.append("ad {name} {f} {node}{alt}".format(name=self.name, f=str(self.f.value), node=self.node.name, alt=alt))
        else:
441
            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))
Daniel Brown's avatar
Daniel Brown committed
442
443
444
445
446
            
        for p in self._params:
            rtn.extend(p.getFinesseText())
        
        return rtn
447

448
class gouy(Detector1):
449
450
    
    def __init__(self, name, direction, spaces):
451
        BaseDetector.__init__(self, name)
452
453
454
        self.spaces = copy.copy(spaces)
        self.direction = direction
        self.alternate_beam = False
455
456
    
        self._freeze()
457
458
459
460
461
        
    @property
    def direction(self): return self.__dir
    @direction.setter
    def direction(self, value):
462
        if value is None or (value != 'x' and value != 'y'):
463
464
465
466
467
468
469
470
471
            raise pkex.BasePyKatException('Direction must be either x or y')
    
        self.__dir = value

    @property
    def spaces(self): return self.__spaces
    @spaces.setter
    def spaces(self, value):

472
        if value is None or len(value) < 1:
473
474
475
476
477
478
479
480
481
482
483
484
485
486
            raise pkex.BasePyKatException('Must be a list of space names')
    
        self.__spaces = value
        
    @staticmethod
    def parseFinesseText(text): 
        values = text.split()

        if len(values) > 3:
            return gouy(str(values[1]), str(values[2]), values[3:])
        else:
            raise pkex.BasePyKatException('Gouy detector code "{0}" is not a valid FINESSE command'.format(text))
            
    def getFinesseText(self) :
487
        rtn = BaseDetector.getFinesseText(self)
488
489
490
491
492
493
494
495
496
497

        rtn.append("gouy {name} {dir} {spaces}".format(name=self.name, dir=str(self.direction), spaces=" ".join(self.spaces)))
        
        for p in self._params:
            rtn.extend(p.getFinesseText())
        
        return rtn



498
class bp(Detector1):
499
    acceptedParameters = ['w', 'w0', 'z', 'zr', 'g', 'r', 'q', 'Rc']
500
501
    
    def __init__(self, name, direction, parameter, node, alternate_beam=False):
502
        BaseDetector.__init__(self, name, node)
503
504
505
        self.parameter = parameter
        self.direction = direction
        self.alternate_beam = alternate_beam
506
507
    
        self._freeze()
Daniel Brown's avatar
Daniel Brown committed
508
        
509
510
511
512
    @property
    def direction(self): return self.__dir
    @direction.setter
    def direction(self, value):
513
        if value is None or (value != 'x' and value != 'y'):
514
515
516
517
518
519
520
521
522
            raise pkex.BasePyKatException('Direction must be either x or y')
    
        self.__dir = value

    @property
    def parameter(self): return self.__param
    @parameter.setter
    def parameter(self, value):
        
523
        if value is None or (value not in self.acceptedParameters) :
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
            raise pkex.BasePyKatException('Parameter must be one of: %s'%(", ".join(self.acceptedParameters)))
    
        self.__param = value
        
    @staticmethod
    def parseFinesseText(text): 
        values = text.split()
        
        node=values[-1]
        alt_beam = node[-1] == '*'
        
        if len(values) > 3:
            return bp(str(values[1]), str(values[2]), str(values[3]), str(values[4]), alternate_beam=alt_beam)
        else:
            raise pkex.BasePyKatException('Gouy detector code "{0}" is not a valid FINESSE command'.format(text))
            
    def getFinesseText(self) :
541
        rtn = BaseDetector.getFinesseText(self)
542
543
544
545
546
547
548
549
550
551
552
553
554

        if self.alternate_beam:
            alt = "*"
        else:
            alt = ""
            
        rtn.append("bp {name} {dir} {param} {node}{alt}".format(name=self.name, dir=str(self.direction), param=self.parameter, node=self.node.name, alt=alt))
        
        for p in self._params:
            rtn.extend(p.getFinesseText())
        
        return rtn

Daniel Brown's avatar
Daniel Brown committed
555
id___2 = 0
556

557
class pd(Detector1):
558

559
560
561
562
    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
Daniel Brown's avatar
Daniel Brown committed
563
564
565
566
567
568
        global id___2
        id___2 += 1
        cnew_name = str("%s.%s_%i" % (cls.__module__, cls.__name__, id___2))
    
        cnew = type(cnew_name, (cls,), {})
    
569
        return object.__new__(cnew)
Daniel Brown's avatar
Daniel Brown committed
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584

    def __deepcopy__(self, memo):
        """
        When deep copying a kat object we need to take into account
        the instance specific properties.
        """
        
        # 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)
        
        result.__set_demod_attrs()
        
        return result
585
586

    def __init__(self, name=None, num_demods=1, node_name=None, senstype=None, alternate_beam=False, pdtype=None, **kwargs):
587
        BaseDetector.__init__(self, name, node_name)
Daniel Brown's avatar
Daniel Brown committed
588
589
590
        
        self.__num_demods = num_demods
        self.__senstype = senstype
Daniel Brown's avatar
Daniel Brown committed
591
        self.alternate_beam = alternate_beam
592
593
        self.__pdtype = pdtype

Daniel Brown's avatar
Daniel Brown committed
594
595
596
597
        # create the parameters for all 5 demodulations regardless
        # of how many the user specifies. Later we add properties to
        # those which correspond to the number of demodulations
        
598
599
600
601
602
        self.__f1 = Param("f1", self, None)
        self.__f2 = Param("f2", self, None)
        self.__f3 = Param("f3", self, None)
        self.__f4 = Param("f4", self, None)
        self.__f5 = Param("f5", self, None)
Daniel Brown's avatar
Daniel Brown committed
603
        
Daniel Brown's avatar
Daniel Brown committed
604
605
606
607
608
        self.__phase1 = Param("phase1", self, None)
        self.__phase2 = Param("phase2", self, None)
        self.__phase3 = Param("phase3", self, None)
        self.__phase4 = Param("phase4", self, None)
        self.__phase5 = Param("phase5", self, None)
Daniel Brown's avatar
Daniel Brown committed
609
        
610
        fs = [self.__f1, self.__f2, self.__f3, self.__f4, self.__f5]
Daniel Brown's avatar
Daniel Brown committed
611
        ps = [self.__phase1, self.__phase2, self.__phase3, self.__phase4, self.__phase5]
612

613
614
        for i in range(num_demods):
            f = 'f{0}'.format(i+1)
615
            #print("i {0} fs {1} f {2} keys {3}".format(i,len(fs),f, kwargs.keys()))
616
617
618
619
620
621
            
            if f in kwargs:
                fs[i].value = kwargs[f]
            else:
                raise pkex.BasePyKatException("Missing demodulation frequency {0} (f{0})".format(i+1))    
        
622
            p = 'phase{0}'.format(i+1)
623
624
            
            if p in kwargs:
625
                if kwargs[p] is None and i<num_demods-1:
626
                    raise pkex.BasePyKatException("Missing demodulation phase {0} (phase{0})".format(i+1))
627
628
629
                    
                ps[i].value = kwargs[p]
            elif i<num_demods-1:
630
                raise pkex.BasePyKatException("Missing demodulation phase {0} (phase{0})".format(i+1))
631
   
Daniel Brown's avatar
Daniel Brown committed
632
        self.__set_demod_attrs()
633
634
    
        self._freeze()
635
                
Daniel Brown's avatar
Daniel Brown committed
636
637
638
639
640
641
642
643
644
645
646
    @property
    def senstype(self): return self.__senstype
    @senstype.setter
    def senstype(self,value):
        if value == "": value = None
        
        if value != "S" and value != "N" and value != None: 
            raise pkex.BasePyKatException("Photodiode sensitivity type can either be 'N', 'S' or None.")
            
        self.__senstype = value
        
647
    @property
Daniel Brown's avatar
Daniel Brown committed
648
649
650
651
652
653
654
655
    def num_demods(self): return self.__num_demods
    @num_demods.setter
    def num_demods(self, value): 
        if value < 0 or value > 5:
            raise pkex.BasePyKatException("Number of demodulations must be between 0 and 5")
        
        self.__num_demods = value
        self.__set_demod_attrs()
656
657
658
659
660

    @property
    def pdtype(self): return self.__pdtype
    @pdtype.setter
    def pdtype(self, value): self.__pdtype = value
Daniel Brown's avatar
Daniel Brown committed
661
662
    
    def __get_fphi(self, name):
Daniel Brown's avatar
Daniel Brown committed
663
        return getattr(self, '_pd__' + name)
Daniel Brown's avatar
Daniel Brown committed
664
665
    
    def __set_f(self, num, value):
Daniel Brown's avatar
Daniel Brown committed
666
667
668
669
        value = SIfloat(value)
        
        p = getattr(self, '_pd__f' + num)
        p.value = value
Daniel Brown's avatar
Daniel Brown committed
670
671
    
    def __set_phi(self, num, value):
Daniel Brown's avatar
Daniel Brown committed
672
673
        value = SIfloat(value)
        
674
        if value is None and num != self.num_demods:
Daniel Brown's avatar
Daniel Brown committed
675
676
677
            # check if we are setting no phase that this is only on the last
            # demodulation phase.
            raise pkex.BasePyKatException("Only last demodulation phase can be set to None")
678
        elif isinstance(value, six.string_types) and not isinstance(value,float) and value.lower() != "max":
Daniel Brown's avatar
Daniel Brown committed
679
            raise pkex.BasePyKatException("Demodulation phase can only be set to a 'max' or a number (or None if the last demodulation phase)")
Daniel Brown's avatar
Daniel Brown committed
680
          
681
        p = getattr(self, '_pd__phase' + num)  
Daniel Brown's avatar
Daniel Brown committed
682
        p.value = value
Daniel Brown's avatar
Daniel Brown committed
683
684
685
686
687
688
        
    def __set_demod_attrs(self):
        """
        For the set number of demodulations the correct number of 
        Parameters are created.
        """
689
        self._unfreeze()
Daniel Brown's avatar
Daniel Brown committed
690
691
692
693
694
695
696
        
        # if there are demodulations present then we want to add
        # the various parameters so they are available for users
        # to play with.
        if self.__num_demods > 0:
            for i in range(1,6):
                name = str(i)
Daniel Brown's avatar
Daniel Brown committed
697
                
Daniel Brown's avatar
Daniel Brown committed
698
699
                if i <= self.num_demods:
                    if not hasattr(self, "f"+name):
Daniel Brown's avatar
Daniel Brown committed
700
701
702
703
                        fget = lambda self, i=i:        self.__get_fphi('f'+str(i))
                        fset = lambda self, value, i=i: self.__set_f(str(i), value)
                        
                        setattr(self.__class__, "f"+name, property(fget=fget, fset=fset))
Daniel Brown's avatar
Daniel Brown committed
704
                    
705
706
                    if not hasattr(self, "phase"+name):
                        setattr(self.__class__, "phase"+name, property(fget=lambda self, i=i: self.__get_fphi('phase'+str(i)), fset=lambda self, value, i=i: self.__set_phi(str(i), value)))
Daniel Brown's avatar
Daniel Brown committed
707
708
709
                else:
                    if hasattr(self, "f"+name):
                        delattr(self.__class__, "f"+name)
Daniel Brown's avatar
Daniel Brown committed
710
                        
711
712
                    if hasattr(self, "phase"+name):
                        delattr(self.__class__, "phase"+name)
713
714
        
        self._freeze()
Daniel Brown's avatar
Daniel Brown committed
715
    
716
717
    @staticmethod
    def parseFinesseText(text): 
Daniel Brown's avatar
Daniel Brown committed
718
        values = text.split()
719
720
721
722
723
724
725
726
        demods = 0
        senstype = None

        if len(values[0]) == 4:
            senstype = values[0][2]
            demods = int(values[0][3])
        elif len(values[0]) == 3:
            demods = int(values[0][2])
Daniel Brown's avatar
Daniel Brown committed
727
        elif len(values[0]) != 2:
728
            raise pkex.BasePyKatException("Photodiode code format incorrect '{0}' (1)".format(text))
729
730
        
        if len(values) <= 3 and demods > 0:
731
            raise pkex.BasePyKatException("Photodiode code format incorrect '{0}' (2)".format(text))
Daniel Brown's avatar
Daniel Brown committed
732
        elif len(values) > 3 and demods == 0:
733
            raise pkex.BasePyKatException("Photodiode code format incorrect '{0}' (3)".format(text))
734
735
736
737
            
        num_f_phs = len(values) - 3
        expected_f_phs = demods * 2
        
738
739
        if not (num_f_phs == expected_f_phs or num_f_phs == expected_f_phs-1):
            raise pkex.BasePyKatException("Photodiode code format incorrect '{0}' (4)".format(text))
740
741
742
743
744
745
746
        
        f = values[2:len(values)-1:2]    
        phs = values[3:len(values)-1:2]
        
        dict = {}
        
        for i in range(len(f)):
Daniel Brown's avatar
Daniel Brown committed
747
            dict['f{0}'.format(i+1)] = SIfloat(f[i])
748
        for i in range(len(phs)):
Daniel Brown's avatar
Daniel Brown committed
749
            if phs[i] == "max":
750
                dict['phase{0}'.format(i+1)] = "max"
Daniel Brown's avatar
Daniel Brown committed
751
            else:
752
                dict['phase{0}'.format(i+1)] = SIfloat(phs[i])
753
754
755
756
757
758
759
760
761
762
            
        node = values[-1]
        alt_beam = node[-1] == '*'
        
        if alt_beam:
            node = node[0:-1]
        
        return pd(values[1], demods, node, senstype=senstype, alternate_beam=alt_beam, **dict)

        
Daniel Brown's avatar
Daniel Brown committed
763
    def getFinesseText(self) :
764
        rtn = BaseDetector.getFinesseText(self)
Daniel Brown's avatar
Daniel Brown committed
765
766
767
768
769
        
        if self.enabled:
            alt_str = ""
            fphi_str = ""
            
Daniel Brown's avatar
Daniel Brown committed
770
            if self.alternate_beam:
Daniel Brown's avatar
Daniel Brown committed
771
772
773
                alt_str = "*"
                
            for n in range(1, 1+self.num_demods):
774
775
776
777
778
779
780
                _f = self.__getattribute__("f"+str(n))
                
                if _f == "$fs":
                    fphi_str += " $fs"
                else:
                    fphi_str += " {0:.16g}".format(float(_f))
                    
781
                phi_val = self.__getattribute__("phase"+str(n))
Daniel Brown's avatar
Daniel Brown committed
782
783
                
                if phi_val != None:
784
785
786
787
                    if type(phi_val) == float:
                        fphi_str += " {0:.16g}".format(float(phi_val))
                    else:
                        fphi_str += " {0}".format(phi_val)
Daniel Brown's avatar
Daniel Brown committed
788
789
790
            
            senstype = self.senstype
            
791
            if senstype is None:
Daniel Brown's avatar
Daniel Brown committed
792
                senstype = ""
793
            
Sean Leavey's avatar
Sean Leavey committed
794
            rtn.append("pd{0}{1} {2}{3} {4}{5}".format(senstype, self.num_demods, self.name, fphi_str, self.node.name, alt_str))
795

Daniel Brown's avatar
Daniel Brown committed
796
797
            self._getScaleCmds(rtn)
            
798
799
            if self.pdtype != None:
                rtn.append("pdtype {0} {1}".format(self.name, self.pdtype))
800
                
801
802
            for p in self._params:
                rtn.extend(p.getFinesseText())
Daniel Brown's avatar
Daniel Brown committed
803
804
            
        return rtn
805
  
Daniel Brown's avatar
Daniel Brown committed
806
class qnoised(pd):
807
808
    
    def __init__(self, name, num_demods, node_name, alternate_beam=False, pdtype=None, **kwargs):
Daniel Brown's avatar
Daniel Brown committed
809
        super(qnoised, self).__init__(name, num_demods, node_name, alternate_beam=alternate_beam, pdtype=pdtype, **kwargs)
810
    
811
812
        self._unfreeze()
        
813
        self.__homangle = AttrParam("homangle", self, None)
814
815
        
        self._freeze()
816
817
818
819
820
821
822
    
    @property
    def homangle(self): return self.__homangle
    @homangle.setter
    def homangle(self, value): self.__homangle.value = value
    
    @pd.pdtype.setter
Daniel Brown's avatar
Daniel Brown committed
823
824
    def pdtype(self, value):
        raise pkex.BasePyKatException("Setting pdtype is not possible with qnoised detectors")
825
    
Daniel Brown's avatar
Daniel Brown committed
826
827
828
829
830
831
832
    def parseAttributes(self, values):
        
        for key in values.keys():
            if key in ["homangle"]:
                self.__homangle.value = values[key]
            else:
                raise pkex.BasePyKatException("No attribute {0} for qnoised".format(key))
833
834
835
836
    
    @staticmethod
    def parseFinesseText(text): 
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
837

838
        if len(values) <= 3:
Daniel Brown's avatar
Daniel Brown committed
839
            raise pkex.BasePyKatException("qnoised code format incorrect '{0}' (2)".format(text))
Daniel Brown's avatar
Daniel Brown committed
840
            
Daniel Brown's avatar
Daniel Brown committed
841
        demods = int(values[2])
842
        
843
        if len(values) <= 4 and demods > 0:
Daniel Brown's avatar
Daniel Brown committed
844
            raise pkex.BasePyKatException("qnoised code format incorrect '{0}' (2)".format(text))
845
        elif len(values) > 4 and demods == 0:
Daniel Brown's avatar
Daniel Brown committed
846
            raise pkex.BasePyKatException("qnoised code format incorrect '{0}' (3)".format(text))
847
848
849
850
            
        num_f_phs = len(values) - 4
        expected_f_phs = demods * 2
        
Daniel Brown's avatar
Daniel Brown committed
851
852
        if not (num_f_phs == expected_f_phs or num_f_phs == (expected_f_phs-1)):
            raise pkex.BasePyKatException("qnoised code format incorrect '{0}' (4)".format(text))
853
854
855
856
857
        
        f = values[3:len(values)-1:2]    
        phs = values[4:len(values)-1:2]
        
        dict = {}
Daniel Brown's avatar
Daniel Brown committed
858
        
859
860
861
        for i in range(len(f)):
            dict['f{0}'.format(i+1)] = f[i]
        for i in range(len(phs)):
862
            dict['phase{0}'.format(i+1)] = phs[i]
Daniel Brown's avatar
Daniel Brown committed
863
            
864
865
866
867
868
869
        node = values[-1]
        alt_beam = node[-1] == '*'
        
        if alt_beam:
            node = node[0:-1]
        
870
871
872
873
874
875
876
877
        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)
878
879
    
    def getFinesseText(self) :
880
        rtn = BaseDetector.getFinesseText(self)
881
882
883
884
885
886
887
        
        if self.enabled:
            alt_str = ""
            fphi_str = ""
            
            if self.alternate_beam:
                alt_str = "*"
888
            
889
            for n in range(1, 1+self.num_demods):
890
891
892
893
894
895
896
                _f = self.__getattribute__("f"+str(n))
                
                if _f == "$fs":
                    fphi_str += " $fs"
                else:
                    fphi_str += " {0:.16g}".format(float(_f))
                    
897
                phi_val = self.__getattribute__("phase"+str(n))
898
899
                
                if phi_val != None:
900
901
902
903
                    if type(phi_val) == float:
                        fphi_str += " {0:.16g}".format(float(phi_val))
                    else:
                        fphi_str += " " + str(phi_val)
904
905
906
            
            senstype = self.senstype
            
907
            if senstype is None:
908
909
                senstype = ""
                
910
            rtn.append("qnoised{5} {0} {1} {2} {3}{4}".format(self.name, self.num_demods, fphi_str, self.node.name, alt_str, senstype))
Andreas Freise's avatar
Andreas Freise committed
911

Daniel Brown's avatar
Daniel Brown committed
912
            self._getScaleCmds(rtn)
913
914
915
916
917
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
        return rtn
Daniel Brown's avatar
Daniel Brown committed
918

919
class qshot(pd):
Daniel Brown's avatar
Daniel Brown committed
920
921
    
    def __init__(self, name, num_demods, node_name, alternate_beam=False, **kwargs):
922
        super(qshot, self).__init__(name, num_demods, node_name, alternate_beam=alternate_beam, pdtype=None, **kwargs)     
923

Daniel Brown's avatar
Daniel Brown committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
    @pd.pdtype.setter
    def pdtype(self, value):
        raise pkex.BasePyKatException("Setting pdtype is not possible with qshot detectors")
    
    @pd.senstype.setter
    def senstype(self,value):
        raise pkex.BasePyKatException("qshot detector has no sensitvity type")
    
    @staticmethod
    def parseFinesseText(text): 
        values = text.split()

        if len(values) <= 3:
            raise pkex.BasePyKatException("qshot code format incorrect '{0}' (2)".format(text))
            
        demods = int(values[2])
        
        if len(values) <= 4 and demods > 0:
            raise pkex.BasePyKatException("qshot code format incorrect '{0}' (2)".format(text))
        elif len(values) > 4 and demods == 0:
            raise pkex.BasePyKatException("qshot code format incorrect '{0}' (3)".format(text))
            
        num_f_phs = len(values) - 4
        expected_f_phs = demods * 2
        
        if not (num_f_phs == expected_f_phs or num_f_phs == (expected_f_phs-1)):
            raise pkex.BasePyKatException("qshot code format incorrect '{0}' (4)".format(text))
        
        f = values[3:len(values)-1:2]    
        phs = values[4:len(values)-1:2]
        
        dict = {}
        
        for i in range(len(f)):
            dict['f{0}'.format(i+1)] = f[i]
        for i in range(len(phs)):
960
            dict['phase{0}'.format(i+1)] = phs[i]
Daniel Brown's avatar
Daniel Brown committed
961
962
963
964
965
966
            
        node = values[-1]
        alt_beam = node[-1] == '*'
        
        if alt_beam:
            node = node[0:-1]
967
968
969
970
971
972
973
            
        if values[0].endswith('S'):
            sens='S'
        elif values[0].endswith('N'):
            sens='N'
        else:
            sens=None
Daniel Brown's avatar
Daniel Brown committed
974
        
975
        return qshot(values[1], demods, node, senstype=sens, alternate_beam=alt_beam, **dict)
976
    
Daniel Brown's avatar
Daniel Brown committed
977
    def getFinesseText(self) :
978
        rtn = BaseDetector.getFinesseText(self)
Daniel Brown's avatar
Daniel Brown committed
979
980
981
982
983
984
985
986
987
        
        if self.enabled:
            alt_str = ""
            fphi_str = ""
            
            if self.alternate_beam:
                alt_str = "*"
                
            for n in range(1, 1+self.num_demods):
988
989
990
991
992
993
994
                _f = self.__getattribute__("f"+str(n))
                
                if _f == "$fs":
                    fphi_str += " $fs"
                else:
                    fphi_str += " {0:.16g}".format(float(_f))
                    
995
                phi_val = self.__getattribute__("phase"+str(n))
Daniel Brown's avatar
Daniel Brown committed
996
997
                
                if phi_val != None:
998
999
1000
1001
                    if type(phi_val) == float:
                        fphi_str += " {0:.16g}".format(float(phi_val))
                    else:
                        fphi_str += " " + str(phi_val)
Daniel Brown's avatar
Daniel Brown committed
1002
1003
1004
            
            senstype = self.senstype
            
1005
            if senstype is None:
Daniel Brown's avatar
Daniel Brown committed
1006
1007
                senstype = ""
                
1008
            rtn.append("qshot{5} {0} {1} {2} {3}{4}".format(self.name, self.num_demods, fphi_str, self.node.name, alt_str,senstype))
Daniel Brown's avatar
Daniel Brown committed
1009

Daniel Brown's avatar
Daniel Brown committed
1010
            self._getScaleCmds(rtn)
Daniel Brown's avatar
Daniel Brown committed
1011
1012
1013
1014
1015
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
        return rtn
Daniel Brown's avatar
Daniel Brown committed
1016
    
1017
1018
1019
1020
1021
1022
    
class hd(Detector2):
    
    def __init__(self, name, phase, node1_name, node2_name):
        BaseDetector.__init__(self, name, (node1_name, node2_name), max_nodes=2)
    
1023
        self.__phase = Param("phase", self, phase)
1024
1025
1026

        self._freeze()
        
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
    @property
    def phase(self): return self.__phase
    @phase.setter
    def phase(self, value): self.__phase.value = value
    
    def parseAttributes(self, values):
        raise pkex.BasePyKatException("hd detector %s has no attributes to set" % self.name)
    
    @staticmethod
    def parseFinesseText(text): 
        values = text.split()
        
        return hd(values[1], float(values[2]), str(values[3]), str(values[4]))
    
    def getFinesseText(self):
1042
        rtn = BaseDetector.getFinesseText(self)
1043
1044
        
        if self.enabled:   
1045
1046
            n1 = self.node1.name
            n2 = self.node2.name
1047
            
1048
1049
            if self._alternate_beam[0]: n1 += "*"
            if self._alternate_beam[1]: n2 += "*"
1050
1051
1052
            
            rtn.append("hd {0} {1} {2} {3}".format(self.name, self.phase, n1, n2))

Daniel Brown's avatar
Daniel Brown committed
1053
            self._getScaleCmds(rtn)
1054
1055
1056
1057
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
1058
1059
1060
1061
1062
1063
1064
1065
1066
        return rtn
        
class qhd(Detector2):
    
    def __init__(self, name, phase, node1_name, node2_name, sensitivity=""):
        BaseDetector.__init__(self, name, (node1_name, node2_name), max_nodes=2)
    
        self.__phase = Param("phase", self, phase)
        self.sensitivity = sensitivity
1067
1068
    
        self._freeze()
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
        
    @property
    def phase(self): return self.__phase
    @phase.setter
    def phase(self, value): self.__phase.value = value
    
    @property
    def sensitivity(self): 
        return self.__sensitivity
    @sensitivity.setter
    def sensitivity(self, value):
        if value == 'S' or value == 'N':
            self.__sensitivity = value
1082
        elif value is None or value == '':
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
            self.__sensitivity = ""
        else:
            raise pkex.BasePyKatException("qhd (%s) sensitivity option '%s' is not available, use either 'S' or 'N'." % (self.name, value))
        
    
    def parseAttributes(self, values):
        raise pkex.BasePyKatException("hd detector %s has no attributes to set" % self.name)
    
    @staticmethod
    def parseFinesseText(text): 
        values = text.split()
        
Daniel Brown's avatar
Daniel Brown committed
1095
1096
1097
1098
1099
1100
        sens = values[0][-1]
        
        if sens != 'S' and sens != 'N':
            sens = None
            
        return qhd(values[1], float(values[2]), str(values[3]), str(values[4]), sensitivity = sens)
1101
1102
    
    def getFinesseText(self):
1103
        rtn = BaseDetector.getFinesseText(self)
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
        
        if self.enabled:   
            n1 = self.node1.name
            n2 = self.node2.name
            
            if self._alternate_beam[0]: n1 += "*"
            if self._alternate_beam[1]: n2 += "*"
            
            rtn.append("qhd{4} {0} {1} {2} {3}".format(self.name, self.phase, n1, n2, self.sensitivity))

Daniel Brown's avatar
Daniel Brown committed
1114
            self._getScaleCmds(rtn)
1115
1116
1117
1118
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
1119
        return rtn