detectors.py 30.1 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
from __future__ import absolute_import
from __future__ import division
9
from __future__ import print_function
10
11
from __future__ import unicode_literals

12
13
14
import pykat.external.six as six
if six.PY2:
	import exceptions
Daniel Brown's avatar
Daniel Brown committed
15
import abc
Daniel Brown's avatar
Daniel Brown committed
16
from pykat.node_network import *
Daniel Brown's avatar
Daniel Brown committed
17
from pykat.param import Param, AttrParam
18
from pykat.SIfloat import SIfloat
19

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

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

27
28
29
30
31
32
from pykat import USE_GUI, NoGUIException

if USE_GUI:
    import pykat.gui.resources
    from pykat.gui.graphics import *
    
33
class BaseDetector(object) :
34
35
36
37
    """
    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.
    """
38
    
39
40
    __metaclass__ = abc.ABCMeta
    
41
42
    def __init__(self, name, nodes=None, max_nodes=1):
        
Daniel Brown's avatar
Daniel Brown committed
43
44
45
46
47
48
49
        self.__name = name
        self._svgItem = None
        self._kat = None
        self.noplot = False
        self.enabled = True
        self.tag = None
        self._params = []
50
        self._mask = {}
Daniel Brown's avatar
Daniel Brown committed
51
        self.__scale = []
52
53
        self.__removed = False
        
54
55
56
57
58
        self._alternate_beam = []
        self._nodes = []
        self._requested_nodes = []
        
        if nodes != None:
59
60
            if isinstance(nodes, (list, tuple)):
                
61
62
63
64
65
66
67
68
69
70
71
                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)
72
            elif isinstance(nodes, six.string_types):
73
74
75
76
77
78
79
80
                # 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)
81
82
83
            else:
                raise pkex.BasePyKatException("Nodes should be a list or tuple of node names or a singular node name as a string.")
                
84
85
                
                  
Daniel Brown's avatar
Daniel Brown committed
86
87
88
89
    def _register_param(self, param):
        self._params.append(param)
        
    def _on_kat_add(self, kat):
90
91
        self._kat = kat
        
92
93
94
        for rn in self._requested_nodes:
            if rn != None:
                self._nodes.append(kat.nodes.createNode(rn))
Daniel Brown's avatar
Daniel Brown committed
95
    
96
97
98
99
100
101
102
103
    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
104
105
106
107
108
109
110
111
112
    @staticmethod
    def parseFinesseText(text):    
        raise NotImplementedError("This function is not implemented")
        
    def getFinesseText(self):
        """ Base class for individual finesse optical components """    
        raise NotImplementedError("This function is not implemented")
        
    def getQGraphicsItem(self):    
113
114
115
        if not USE_GUI:
            raise NoGUIException
            
Daniel Brown's avatar
Daniel Brown committed
116
        return None
117

118
119
120
    @property
    def removed(self): return self.__removed
    
121
122
123
    @property 
    def scale(self): return self.__scale
    @scale.setter
124
    def scale(self, value):
Daniel Brown's avatar
Daniel Brown committed
125
126
        if value not in self.__scale:
            self.__scale = value
Daniel Brown's avatar
Daniel Brown committed
127
128
129
130
131
132
    
    @property
    def name(self): return self.__name        

    def __str__(self): return self.name

133
    def mask(self, n, m, factor):
134
        _id = str(n)+"_"+str(m)
135
136
137
        
        # if the mask is 1 then remove this so it doesn't get 
        # printed as by default the value is 1.0
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
        if _id in self._mask and factor == 1.0:
            del self._mask[_id]
                
        self._mask[_id] = factor

    def _set_node(value, index):
        if self._kat == None:
            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
158
159
    def _getScaleCmds(self, rtn):
        if self.scale != None:
160
            if isinstance(self.scale, six.string_types):
Daniel Brown's avatar
Daniel Brown committed
161
162
163
164
165
166
167
                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.")
                
168
class Detector1(BaseDetector):
169
170
171
    """
    A detector that attaches to one node.
    """
172
    @property 
173
    def node(self): return self._nodes[0]
174
175
176
177
178
179
    @node.setter
    def node(self, value):
        self._set_node(value, 0)      
        
                
class Detector2(BaseDetector):
180
181
182
    """
    A detector that attaches to two node.
    """
183
184
    
    @property 
185
    def node1(self): return self._nodes[0]
186
187
188
189
190
    @node1.setter
    def node(self, value):
        self._set_node(value, 0)
        
    @property 
191
    def node2(self): return self._nodes[1]
192
193
194
195
196
197
    @node2.setter
    def node(self, value):
        self._set_node(value, 1)
                
                
                
198
                
Daniel Brown's avatar
Daniel Brown committed
199

200
class ad(Detector1):
Daniel Brown's avatar
Daniel Brown committed
201
202
    
    def __init__(self, name, frequency, node_name, mode=None, alternate_beam=False):
203
        BaseDetector.__init__(self, name, node_name)
Daniel Brown's avatar
Daniel Brown committed
204
205
206
        self.mode = mode
        self.alternate_beam = alternate_beam
        self.__f = Param("f", self, frequency)
Daniel Brown's avatar
Daniel Brown committed
207
    
Daniel Brown's avatar
Daniel Brown committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
    @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()
226
227
228

        node=values[-1]
        alt_beam = node[-1] == '*'
Daniel Brown's avatar
Daniel Brown committed
229
230
231
        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:
232
            return ad(values[1], values[2], values[3], alternate_beam=alt_beam)
Daniel Brown's avatar
Daniel Brown committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
        else:
            raise pkex.BasePyKatException('Amplitude detector code "{0}" is not a valid FINESSE command'.format(text))
            
    def getFinesseText(self) :
        rtn = []
        
        if self.alternate_beam:
            alt = '*'
        else:
            alt = ''
        
        if self.mode == None:
            rtn.append("ad {name} {f} {node}{alt}".format(name=self.name, f=str(self.f.value), node=self.node.name, alt=alt))
        else:
247
            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
248
249
250
251
252
            
        for p in self._params:
            rtn.extend(p.getFinesseText())
        
        return rtn
253

254
class gouy(Detector1):
255
256
    
    def __init__(self, name, direction, spaces):
257
        BaseDetector.__init__(self, name)
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
        self.spaces = copy.copy(spaces)
        self.direction = direction
        self.alternate_beam = False
        
    @property
    def direction(self): return self.__dir
    @direction.setter
    def direction(self, value):
        if value == None or (value != 'x' and value != 'y'):
            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):

        if value == None or len(value) < 1:
            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) :
        rtn = []

        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



302
class bp(Detector1):
303
304
305
    acceptedParameters = ['w', 'w0', 'z', 'zr', 'g', 'r', 'q']
    
    def __init__(self, name, direction, parameter, node, alternate_beam=False):
306
        BaseDetector.__init__(self, name, node)
307
308
309
        self.parameter = parameter
        self.direction = direction
        self.alternate_beam = alternate_beam
Daniel Brown's avatar
Daniel Brown committed
310
        
311
312
313
314
315
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
354
355
356
357
    @property
    def direction(self): return self.__dir
    @direction.setter
    def direction(self, value):
        if value == None or (value != 'x' and value != 'y'):
            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):
        
        if value == None or (value not in self.acceptedParameters) :
            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) :
        rtn = []

        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


358
class pd(Detector1):
359

360
361
362
363
364
365
366
    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
        return object.__new__(type(cls.__name__, (cls,), {}), *args, **kwargs)
        
    def __init__(self, name=None, num_demods=1, node_name=None, senstype=None, alternate_beam=False, pdtype=None, **kwargs):
367
        BaseDetector.__init__(self, name, node_name)
Daniel Brown's avatar
Daniel Brown committed
368
369
370
        
        self.__num_demods = num_demods
        self.__senstype = senstype
Daniel Brown's avatar
Daniel Brown committed
371
        self.alternate_beam = alternate_beam
372
373
        self.__pdtype = pdtype

Daniel Brown's avatar
Daniel Brown committed
374
375
376
377
        # 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
        
378
379
380
381
382
        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
383
384
385
386
387
388
389
        
        self.__phi1 = Param("phi1", self, None)
        self.__phi2 = Param("phi2", self, None)
        self.__phi3 = Param("phi3", self, None)
        self.__phi4 = Param("phi4", self, None)
        self.__phi5 = Param("phi5", self, None)
        
390
391
        fs = [self.__f1, self.__f2, self.__f3, self.__f4, self.__f5]
        ps = [self.__phi1, self.__phi2, self.__phi3, self.__phi4, self.__phi5]
392
393

        print("-------------------------------------------------------")
394
395
        for i in range(num_demods):
            f = 'f{0}'.format(i+1)
396
            print("i {0} fs {1} f {2} keys {3}".format(i,len(fs),f, kwargs.keys()))
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
            
            if f in kwargs:
                fs[i].value = kwargs[f]
            else:
                raise pkex.BasePyKatException("Missing demodulation frequency {0} (f{0})".format(i+1))    
        
            p = 'phi{0}'.format(i+1)
            
            if p in kwargs:
                if kwargs[p] == None and i<num_demods-1:
                    raise pkex.BasePyKatException("Missing demodulation phase {0} (phi{0})".format(i+1))
                    
                ps[i].value = kwargs[p]
            elif i<num_demods-1:
                raise pkex.BasePyKatException("Missing demodulation phase {0} (phi{0})".format(i+1))
        
Daniel Brown's avatar
Daniel Brown committed
413
414
    
        self.__set_demod_attrs()
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
    
    
    def __deepcopy__(self, memo):
        """
        When deep copying a kat object we need to take into account
        the instance specific properties.
        """
        
        result = pd(self.name, self.num_demods, self.node.name)
        
        memo[id(self)] = result 
        result.__dict__ = copy.deepcopy(self.__dict__, memo)

        # Find all properties in class we are copying
        # and deep copy these to the new class instance
        for x in self.__class__.__dict__.items():
            if isinstance(x[1], property):
                setattr(result.__class__, x[0], x[1])
                        
        return result
Daniel Brown's avatar
Daniel Brown committed
435
436
437
438
439
440
441
442
443
444
445
446
        
    @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
        
447
    @property
Daniel Brown's avatar
Daniel Brown committed
448
449
450
451
452
453
454
455
    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()
456
457
458
459
460

    @property
    def pdtype(self): return self.__pdtype
    @pdtype.setter
    def pdtype(self, value): self.__pdtype = value
Daniel Brown's avatar
Daniel Brown committed
461
462
    
    def __get_fphi(self, name):
Daniel Brown's avatar
Daniel Brown committed
463
        return getattr(self, '_pd__' + name)
Daniel Brown's avatar
Daniel Brown committed
464
465
    
    def __set_f(self, num, value):
466
        setattr(self, '_pd__f' + num, value)
Daniel Brown's avatar
Daniel Brown committed
467
468
469
470
471
472
    
    def __set_phi(self, num, value):
        if value == None and num != self.num_demods:
            # 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")
473
        elif isinstance(value, six.string_types) and not isinstance(value,float) and value.lower() != "max":
Daniel Brown's avatar
Daniel Brown committed
474
475
            raise pkex.BasePyKatException("Demodulation phase can only be set to a 'max' or a number (or None if the last demodulation phase)")
            
Sean Leavey's avatar
Sean Leavey committed
476
        setattr(self, '_'+ self.__class__.__name__ +'__phi' + num, value)
Daniel Brown's avatar
Daniel Brown committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
        
    def __set_demod_attrs(self):
        """
        For the set number of demodulations the correct number of 
        Parameters are created.
        """
        
        # 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)
                if i <= self.num_demods:
                    if not hasattr(self, "f"+name):
                        setattr(self.__class__, "f"+name, property(fget=lambda self, i=i: self.__get_fphi('f'+str(i)), fset=lambda self, value, i=i: self.__set_f(str(i), value)))
                    
                    if not hasattr(self, "phi"+name):
                        setattr(self.__class__, "phi"+name, property(fget=lambda self, i=i: self.__get_fphi('phi'+str(i)), fset=lambda self, value, i=i: self.__set_phi(str(i), value)))
                else:
                    if hasattr(self, "f"+name):
                        delattr(self.__class__, "f"+name)
                    if hasattr(self, "phi"+name):
                        delattr(self.__class__, "phi"+name)
        else:
            return
    
504
505
    @staticmethod
    def parseFinesseText(text): 
Daniel Brown's avatar
Daniel Brown committed
506
        values = text.split()
507
508
509
510
511
512
513
514
        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
515
        elif len(values[0]) != 2:
516
            raise pkex.BasePyKatException("Photodiode code format incorrect '{0}' (1)".format(text))
517
518
        
        if len(values) <= 3 and demods > 0:
519
            raise pkex.BasePyKatException("Photodiode code format incorrect '{0}' (2)".format(text))
Daniel Brown's avatar
Daniel Brown committed
520
        elif len(values) > 3 and demods == 0:
521
            raise pkex.BasePyKatException("Photodiode code format incorrect '{0}' (3)".format(text))
522
523
524
525
            
        num_f_phs = len(values) - 3
        expected_f_phs = demods * 2
        
526
527
        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))
528
529
530
531
532
533
534
        
        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
535
            dict['f{0}'.format(i+1)] = SIfloat(f[i])
536
        for i in range(len(phs)):
Daniel Brown's avatar
Daniel Brown committed
537
538
539
540
            if phs[i] == "max":
                dict['phi{0}'.format(i+1)] = "max"
            else:
                dict['phi{0}'.format(i+1)] = SIfloat(phs[i])
541
542
543
544
545
546
547
548
549
550
            
        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
551
552
553
554
555
556
557
    def getFinesseText(self) :
        rtn = []
        
        if self.enabled:
            alt_str = ""
            fphi_str = ""
            
Daniel Brown's avatar
Daniel Brown committed
558
            if self.alternate_beam:
Daniel Brown's avatar
Daniel Brown committed
559
560
561
                alt_str = "*"
                
            for n in range(1, 1+self.num_demods):
562
                fphi_str += " {0:.16g}".format(float(self.__getattribute__("f"+str(n))))
Daniel Brown's avatar
Daniel Brown committed
563
564
565
                phi_val = self.__getattribute__("phi"+str(n))
                
                if phi_val != None:
566
567
568
569
                    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
570
571
572
573
574
            
            senstype = self.senstype
            
            if senstype == None:
                senstype = ""
575
            
Sean Leavey's avatar
Sean Leavey committed
576
            rtn.append("pd{0}{1} {2}{3} {4}{5}".format(senstype, self.num_demods, self.name, fphi_str, self.node.name, alt_str))
577

Daniel Brown's avatar
Daniel Brown committed
578
579
            self._getScaleCmds(rtn)
            
580
581
            if self.pdtype != None:
                rtn.append("pdtype {0} {1}".format(self.name, self.pdtype))
582
                
583
584
            for p in self._params:
                rtn.extend(p.getFinesseText())
Daniel Brown's avatar
Daniel Brown committed
585
586
            
        return rtn
587
  
Daniel Brown's avatar
Daniel Brown committed
588
class qnoised(pd):
589
590
    
    def __init__(self, name, num_demods, node_name, alternate_beam=False, pdtype=None, **kwargs):
Daniel Brown's avatar
Daniel Brown committed
591
        super(qnoised, self).__init__(name, num_demods, node_name, alternate_beam=alternate_beam, pdtype=pdtype, **kwargs)
592
593
594
595
596
597
598
599
600
    
        self.__homangle = AttrParam("homangle", self, None)
    
    @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
601
602
    def pdtype(self, value):
        raise pkex.BasePyKatException("Setting pdtype is not possible with qnoised detectors")
603
    
Daniel Brown's avatar
Daniel Brown committed
604
605
606
607
608
609
610
    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))
611
612
613
614
    
    @staticmethod
    def parseFinesseText(text): 
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
615

616
        if len(values) <= 3:
Daniel Brown's avatar
Daniel Brown committed
617
            raise pkex.BasePyKatException("qnoised code format incorrect '{0}' (2)".format(text))
Daniel Brown's avatar
Daniel Brown committed
618
            
Daniel Brown's avatar
Daniel Brown committed
619
        demods = int(values[2])
620
        
621
        if len(values) <= 4 and demods > 0:
Daniel Brown's avatar
Daniel Brown committed
622
            raise pkex.BasePyKatException("qnoised code format incorrect '{0}' (2)".format(text))
623
        elif len(values) > 4 and demods == 0:
Daniel Brown's avatar
Daniel Brown committed
624
            raise pkex.BasePyKatException("qnoised code format incorrect '{0}' (3)".format(text))
625
626
627
628
            
        num_f_phs = len(values) - 4
        expected_f_phs = demods * 2
        
Daniel Brown's avatar
Daniel Brown committed
629
630
        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))
631
632
633
634
635
        
        f = values[3:len(values)-1:2]    
        phs = values[4:len(values)-1:2]
        
        dict = {}
Daniel Brown's avatar
Daniel Brown committed
636
        
637
638
639
640
        for i in range(len(f)):
            dict['f{0}'.format(i+1)] = f[i]
        for i in range(len(phs)):
            dict['phi{0}'.format(i+1)] = phs[i]
Daniel Brown's avatar
Daniel Brown committed
641
            
642
643
644
645
646
647
        node = values[-1]
        alt_beam = node[-1] == '*'
        
        if alt_beam:
            node = node[0:-1]
        
648
649
650
651
652
653
654
655
        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)
656
657
658
659
660
661
662
663
664
665
    
    def getFinesseText(self) :
        rtn = []
        
        if self.enabled:
            alt_str = ""
            fphi_str = ""
            
            if self.alternate_beam:
                alt_str = "*"
666
            
667
            for n in range(1, 1+self.num_demods):
668
                fphi_str += " {0:.16g}".format(float(self.__getattribute__("f"+str(n))))
669
670
671
                phi_val = self.__getattribute__("phi"+str(n))
                
                if phi_val != None:
672
673
674
675
                    if type(phi_val) == float:
                        fphi_str += " {0:.16g}".format(float(phi_val))
                    else:
                        fphi_str += " " + str(phi_val)
676
677
678
679
680
681
            
            senstype = self.senstype
            
            if senstype == None:
                senstype = ""
                
682
            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
683

Daniel Brown's avatar
Daniel Brown committed
684
            self._getScaleCmds(rtn)
685
686
687
688
689
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
        return rtn
Daniel Brown's avatar
Daniel Brown committed
690

691
class qshot(pd):
Daniel Brown's avatar
Daniel Brown committed
692
693
    
    def __init__(self, name, num_demods, node_name, alternate_beam=False, **kwargs):
Daniel Brown's avatar
Daniel Brown committed
694
        super(qshot, self).__init__(name, num_demods, node_name, alternate_beam=alternate_beam, pdtype=None, senstype=None, **kwargs) 
Daniel Brown's avatar
Daniel Brown committed
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
    
    @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)):
            dict['phi{0}'.format(i+1)] = phs[i]
            
        node = values[-1]
        alt_beam = node[-1] == '*'
        
        if alt_beam:
            node = node[0:-1]
739
740
741
742
743
744
745
            
        if values[0].endswith('S'):
            sens='S'
        elif values[0].endswith('N'):
            sens='N'
        else:
            sens=None
Daniel Brown's avatar
Daniel Brown committed
746
        
747
        return qshot(values[1], demods, node, senstype=sens, alternate_beam=alt_beam, **dict)
748
    
Daniel Brown's avatar
Daniel Brown committed
749
750
751
752
753
754
755
756
757
758
759
    def getFinesseText(self) :
        rtn = []
        
        if self.enabled:
            alt_str = ""
            fphi_str = ""
            
            if self.alternate_beam:
                alt_str = "*"
                
            for n in range(1, 1+self.num_demods):
760
                fphi_str += " {0:.16g}".format(float(self.__getattribute__("f"+str(n))))
Daniel Brown's avatar
Daniel Brown committed
761
762
763
                phi_val = self.__getattribute__("phi"+str(n))
                
                if phi_val != None:
764
765
766
767
                    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
768
769
770
771
772
773
            
            senstype = self.senstype
            
            if senstype == None:
                senstype = ""
                
774
            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
775

Daniel Brown's avatar
Daniel Brown committed
776
            self._getScaleCmds(rtn)
Daniel Brown's avatar
Daniel Brown committed
777
778
779
780
781
782
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
        return rtn
        
783
def xd(Detector1):
Daniel Brown's avatar
Daniel Brown committed
784

785
    def __init__(self, name, node_name, component, motion):
786
        BaseDetector.__init__(name, None)
Daniel Brown's avatar
Daniel Brown committed
787
        
788
789
        self.__motion = motion
        self.__component = component
Daniel Brown's avatar
Daniel Brown committed
790
        
791
792
793
794
795
796
    @property
    def motion(self): return self.__motion
    
    @property
    def component(self): return self.__component
    
Daniel Brown's avatar
Daniel Brown committed
797
798
    @staticmethod
    def parseFinesseText(text): 
Daniel Brown's avatar
Daniel Brown committed
799
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
800

801
802
803
804
805
        if len(values) != 4:
            raise pkex.BasePyKatException("Motion detector command format incorrect '{0}' (2)".format(text))
            
        return xd(values[1], values[2], values[3])
    
Daniel Brown's avatar
Daniel Brown committed
806
    def getFinesseText(self) :
807
808
        rtn = []
        
Daniel Brown's avatar
Daniel Brown committed
809
        if self.enabled:
810
            rtn.append("xd {0} {1} {2}".format(self.name, self.component, self.motion))
811

Daniel Brown's avatar
Daniel Brown committed
812
            self._getScaleCmds(rtn)
813
814
815
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
Daniel Brown's avatar
Daniel Brown committed
816
            
817
        return rtn
Daniel Brown's avatar
Daniel Brown committed
818
    
819
820
821
822
823
824
    
class hd(Detector2):
    
    def __init__(self, name, phase, node1_name, node2_name):
        BaseDetector.__init__(self, name, (node1_name, node2_name), max_nodes=2)
    
825
        self.__phase = Param("phase", self, phase)
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
    
    @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):
        rtn = []
        
        if self.enabled:   
845
846
            n1 = self.node1.name
            n2 = self.node2.name
847
            
848
849
            if self._alternate_beam[0]: n1 += "*"
            if self._alternate_beam[1]: n2 += "*"
850
851
852
            
            rtn.append("hd {0} {1} {2} {3}".format(self.name, self.phase, n1, n2))

Daniel Brown's avatar
Daniel Brown committed
853
            self._getScaleCmds(rtn)
854
855
856
857
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
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
888
889
890
891
892
        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
        
    @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
        elif value == None or value == '':
            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
893
894
895
896
897
898
        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)
899
900
901
902
903
904
905
906
907
908
909
910
911
    
    def getFinesseText(self):
        rtn = []
        
        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
912
            self._getScaleCmds(rtn)
913
914
915
916
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
917
        return rtn