detectors.py 26 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
7
8
9
10
11
12

@author: Daniel
"""
import exceptions
import pykat.gui.resources

from pykat.utils import *
from pykat.gui.graphics import *
from pykat.node_network import *
13
from pykat.param import Param
14
import collections
15
16
import pykat.exceptions as pkex
import warnings
17
import copy
Daniel Brown's avatar
Daniel Brown committed
18

19
20
21
22
class BaseDetector(object) :
    
    def __init__(self, name, nodes=None, max_nodes=1):
        
Daniel Brown's avatar
Daniel Brown committed
23
24
25
26
27
28
29
        self.__name = name
        self._svgItem = None
        self._kat = None
        self.noplot = False
        self.enabled = True
        self.tag = None
        self._params = []
30
        self._mask = {}
31
        self.__scale = None
32
33
        self.__removed = False
        
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
        self._alternate_beam = []
        self._nodes = []
        self._requested_nodes = []
        
        if nodes != None:
            if isinstance(nodes, collections.Iterable):
                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)
            else:
                # 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)
Daniel Brown's avatar
Daniel Brown committed
60
61
62
63
64
    
    def _register_param(self, param):
        self._params.append(param)
        
    def _on_kat_add(self, kat):
65
66
        self._kat = kat
        
67
68
69
        for rn in self._requested_nodes:
            if rn != None:
                self._nodes.append(kat.nodes.createNode(rn))
Daniel Brown's avatar
Daniel Brown committed
70
    
71
72
73
74
75
76
77
78
    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
79
80
81
82
83
84
85
86
87
88
    @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):    
        return None
89

90
91
92
    @property
    def removed(self): return self.__removed
    
93
94
95
    @property 
    def scale(self): return self.__scale
    @scale.setter
96
97
    def scale(self, value):
        self.__scale = value
Daniel Brown's avatar
Daniel Brown committed
98
99
100
101
102
103
    
    @property
    def name(self): return self.__name        

    def __str__(self): return self.name

104
    def mask(self, n, m, factor):
105
        _id = str(n)+"_"+str(m)
106
107
108
        
        # if the mask is 1 then remove this so it doesn't get 
        # printed as by default the value is 1.0
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        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.")
    
class Detector1(BaseDetector):
    
    @property 
    def node(self): return self.__nodes[0]
    @node.setter
    def node(self, value):
        self._set_node(value, 0)      
        
                
class Detector2(BaseDetector):
    
    @property 
    def node1(self): return self.__nodes[0]
    @node1.setter
    def node(self, value):
        self._set_node(value, 0)
        
    @property 
    def node2(self): return self.__nodes[1]
    @node2.setter
    def node(self, value):
        self._set_node(value, 1)
                
                
                
154
                
Daniel Brown's avatar
Daniel Brown committed
155

156
class ad(Detector1):
Daniel Brown's avatar
Daniel Brown committed
157
158
    
    def __init__(self, name, frequency, node_name, mode=None, alternate_beam=False):
159
        BaseDetector.__init__(self, name, node_name)
Daniel Brown's avatar
Daniel Brown committed
160
161
162
        self.mode = mode
        self.alternate_beam = alternate_beam
        self.__f = Param("f", self, frequency)
Daniel Brown's avatar
Daniel Brown committed
163
    
Daniel Brown's avatar
Daniel Brown committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    @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()
182
183
184

        node=values[-1]
        alt_beam = node[-1] == '*'
Daniel Brown's avatar
Daniel Brown committed
185
186
187
        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:
188
            return ad(values[1], values[2], values[3], alternate_beam=alt_beam)
Daniel Brown's avatar
Daniel Brown committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
        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:
203
            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
204
205
206
207
208
            
        for p in self._params:
            rtn.extend(p.getFinesseText())
        
        return rtn
209

210
class gouy(Detector1):
211
212
    
    def __init__(self, name, direction, spaces):
213
        BaseDetector.__init__(self, name)
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
        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



258
class bp(Detector1):
259
260
261
    acceptedParameters = ['w', 'w0', 'z', 'zr', 'g', 'r', 'q']
    
    def __init__(self, name, direction, parameter, node, alternate_beam=False):
262
        BaseDetector.__init__(self, name, node)
263
264
265
        self.parameter = parameter
        self.direction = direction
        self.alternate_beam = alternate_beam
Daniel Brown's avatar
Daniel Brown committed
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
302
303
304
305
306
307
308
309
310
311
312
313
    @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


314
class pd(Detector1):
315

316
    def __init__(self, name, num_demods, node_name, senstype=None, alternate_beam=False, pdtype=None, **kwargs):
317
        BaseDetector.__init__(self, name, node_name)
Daniel Brown's avatar
Daniel Brown committed
318
319
320
        
        self.__num_demods = num_demods
        self.__senstype = senstype
Daniel Brown's avatar
Daniel Brown committed
321
        self.alternate_beam = alternate_beam
322
323
        self.__pdtype = pdtype

Daniel Brown's avatar
Daniel Brown committed
324
325
326
327
        # 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
        
328
329
330
331
332
        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
333
334
335
336
337
338
339
        
        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)
        
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
        fs = [self.__f1, self.__f2, self.__f3, self.__f4, self.__f5]
        ps = [self.__phi1, self.__phi2, self.__phi3, self.__phi4, self.__phi5]
        
        for i in range(num_demods):
            f = 'f{0}'.format(i+1)
            
            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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
        # define new class for assigning new attributes
        cls = type(self)
        self.__class__ = type(cls.__name__, (cls,), {})
    
        self.__set_demod_attrs()
        
    @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
        
378
    @property
Daniel Brown's avatar
Daniel Brown committed
379
380
381
382
383
384
385
386
    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()
387
388
389
390
391

    @property
    def pdtype(self): return self.__pdtype
    @pdtype.setter
    def pdtype(self, value): self.__pdtype = value
Daniel Brown's avatar
Daniel Brown committed
392
393
    
    def __get_fphi(self, name):
Daniel Brown's avatar
Daniel Brown committed
394
        return getattr(self, '_pd__' + name)
Daniel Brown's avatar
Daniel Brown committed
395
396
    
    def __set_f(self, num, value):
397
        setattr(self, '_pd__f' + num, value)
Daniel Brown's avatar
Daniel Brown committed
398
399
400
401
402
403
404
405
406
    
    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")
        elif isinstance(value, str) and not isinstance(value,float) and value.lower() != "max":
            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
407
        setattr(self, '_'+ self.__class__.__name__ +'__phi' + num, value)
Daniel Brown's avatar
Daniel Brown committed
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
        
    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
    
435
436
    @staticmethod
    def parseFinesseText(text): 
Daniel Brown's avatar
Daniel Brown committed
437
        values = text.split()
438
439
440
441
442
443
444
445
        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
446
        elif len(values[0]) != 2:
447
            raise pkex.BasePyKatException("Photodiode code format incorrect '{0}' (1)".format(text))
448
449
        
        if len(values) <= 3 and demods > 0:
450
            raise pkex.BasePyKatException("Photodiode code format incorrect '{0}' (2)".format(text))
Daniel Brown's avatar
Daniel Brown committed
451
        elif len(values) > 3 and demods == 0:
452
            raise pkex.BasePyKatException("Photodiode code format incorrect '{0}' (3)".format(text))
453
454
455
456
            
        num_f_phs = len(values) - 3
        expected_f_phs = demods * 2
        
457
458
        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))
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
        
        f = values[2:len(values)-1:2]    
        phs = values[3: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]
        
        return pd(values[1], demods, node, senstype=senstype, alternate_beam=alt_beam, **dict)

        
Daniel Brown's avatar
Daniel Brown committed
479
480
481
482
483
484
485
    def getFinesseText(self) :
        rtn = []
        
        if self.enabled:
            alt_str = ""
            fphi_str = ""
            
Daniel Brown's avatar
Daniel Brown committed
486
            if self.alternate_beam:
Daniel Brown's avatar
Daniel Brown committed
487
488
489
                alt_str = "*"
                
            for n in range(1, 1+self.num_demods):
490
                fphi_str += " {0:.16g}".format(float(self.__getattribute__("f"+str(n))))
Daniel Brown's avatar
Daniel Brown committed
491
492
493
                phi_val = self.__getattribute__("phi"+str(n))
                
                if phi_val != None:
494
495
496
497
                    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
498
499
500
501
502
            
            senstype = self.senstype
            
            if senstype == None:
                senstype = ""
503
            
Sean Leavey's avatar
Sean Leavey committed
504
            rtn.append("pd{0}{1} {2}{3} {4}{5}".format(senstype, self.num_demods, self.name, fphi_str, self.node.name, alt_str))
505
506

            if self.scale != None:
507
                rtn.append("scale {1} {0}".format(self.name, self.scale))
508
509
510

            if self.pdtype != None:
                rtn.append("pdtype {0} {1}".format(self.name, self.pdtype))
511
                
512
513
            for p in self._params:
                rtn.extend(p.getFinesseText())
Daniel Brown's avatar
Daniel Brown committed
514
515
            
        return rtn
516
  
Daniel Brown's avatar
Daniel Brown committed
517
class qnoised(pd):
518
519
    
    def __init__(self, name, num_demods, node_name, alternate_beam=False, pdtype=None, **kwargs):
Daniel Brown's avatar
Daniel Brown committed
520
        super(qnoised, self).__init__(name, num_demods, node_name, alternate_beam=alternate_beam, pdtype=pdtype, **kwargs)
521
522
523
524
525
526
527
528
529
    
        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
530
531
    def pdtype(self, value):
        raise pkex.BasePyKatException("Setting pdtype is not possible with qnoised detectors")
532
    
Daniel Brown's avatar
Daniel Brown committed
533
534
535
536
537
538
539
    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))
540
541
542
543
    
    @staticmethod
    def parseFinesseText(text): 
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
544

545
        if len(values) <= 3:
Daniel Brown's avatar
Daniel Brown committed
546
            raise pkex.BasePyKatException("qnoised code format incorrect '{0}' (2)".format(text))
Daniel Brown's avatar
Daniel Brown committed
547
            
Daniel Brown's avatar
Daniel Brown committed
548
        demods = int(values[2])
549
        
550
        if len(values) <= 4 and demods > 0:
Daniel Brown's avatar
Daniel Brown committed
551
            raise pkex.BasePyKatException("qnoised code format incorrect '{0}' (2)".format(text))
552
        elif len(values) > 4 and demods == 0:
Daniel Brown's avatar
Daniel Brown committed
553
            raise pkex.BasePyKatException("qnoised code format incorrect '{0}' (3)".format(text))
554
555
556
557
            
        num_f_phs = len(values) - 4
        expected_f_phs = demods * 2
        
Daniel Brown's avatar
Daniel Brown committed
558
559
        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))
560
561
562
563
564
        
        f = values[3:len(values)-1:2]    
        phs = values[4:len(values)-1:2]
        
        dict = {}
Daniel Brown's avatar
Daniel Brown committed
565
        
566
567
568
569
        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
570
            
571
572
573
574
575
576
        node = values[-1]
        alt_beam = node[-1] == '*'
        
        if alt_beam:
            node = node[0:-1]
        
577
578
579
580
581
582
583
584
        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)
585
586
587
588
589
590
591
592
593
594
    
    def getFinesseText(self) :
        rtn = []
        
        if self.enabled:
            alt_str = ""
            fphi_str = ""
            
            if self.alternate_beam:
                alt_str = "*"
595
            
596
            for n in range(1, 1+self.num_demods):
597
                fphi_str += " {0:.16g}".format(float(self.__getattribute__("f"+str(n))))
598
599
600
                phi_val = self.__getattribute__("phi"+str(n))
                
                if phi_val != None:
601
602
603
604
                    if type(phi_val) == float:
                        fphi_str += " {0:.16g}".format(float(phi_val))
                    else:
                        fphi_str += " " + str(phi_val)
605
606
607
608
609
610
            
            senstype = self.senstype
            
            if senstype == None:
                senstype = ""
                
611
            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
612

613
            if self.scale != None:
614
                rtn.append("scale {1} {0}".format(self.name, self.scale))
615
616
617
618
619
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
        return rtn
Daniel Brown's avatar
Daniel Brown committed
620

621
class qshot(pd):
Daniel Brown's avatar
Daniel Brown committed
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
    
    def __init__(self, name, num_demods, node_name, alternate_beam=False, **kwargs):
        super(qnoised, self).__init__(name, num_demods, node_name, alternate_beam=alternate_beam, pdtype=None, senstype=None, **kwargs)
    
    @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]
669
670
671
672
673
674
675
            
        if values[0].endswith('S'):
            sens='S'
        elif values[0].endswith('N'):
            sens='N'
        else:
            sens=None
Daniel Brown's avatar
Daniel Brown committed
676
        
677
        return qshot(values[1], demods, node, senstype=sens, alternate_beam=alt_beam, **dict)
678
    
Daniel Brown's avatar
Daniel Brown committed
679
680
681
682
683
684
685
686
687
688
689
    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):
690
                fphi_str += " {0:.16g}".format(float(self.__getattribute__("f"+str(n))))
Daniel Brown's avatar
Daniel Brown committed
691
692
693
                phi_val = self.__getattribute__("phi"+str(n))
                
                if phi_val != None:
694
695
696
697
                    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
698
699
700
701
702
703
            
            senstype = self.senstype
            
            if senstype == None:
                senstype = ""
                
704
            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
705
706

            if self.scale != None:
707
                rtn.append("scale {1} {0}".format(self.name, self.scale))
Daniel Brown's avatar
Daniel Brown committed
708
709
710
711
712
713
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
        return rtn
        
714
def xd(Detector1):
Daniel Brown's avatar
Daniel Brown committed
715

716
    def __init__(self, name, node_name, component, motion):
717
        BaseDetector.__init__(name, None)
Daniel Brown's avatar
Daniel Brown committed
718
        
719
720
        self.__motion = motion
        self.__component = component
Daniel Brown's avatar
Daniel Brown committed
721
        
722
723
724
725
726
727
    @property
    def motion(self): return self.__motion
    
    @property
    def component(self): return self.__component
    
Daniel Brown's avatar
Daniel Brown committed
728
729
    @staticmethod
    def parseFinesseText(text): 
Daniel Brown's avatar
Daniel Brown committed
730
        values = text.split()
Daniel Brown's avatar
Daniel Brown committed
731

732
733
734
735
736
        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
737
    def getFinesseText(self) :
738
739
        rtn = []
        
Daniel Brown's avatar
Daniel Brown committed
740
        if self.enabled:
741
            rtn.append("xd {0} {1} {2}".format(self.name, self.component, self.motion))
742

743
            if self.scale != None:
744
                rtn.append("scale {1} {0}".format(self.name, self.scale))
745
746
747
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
Daniel Brown's avatar
Daniel Brown committed
748
            
749
        return rtn
Daniel Brown's avatar
Daniel Brown committed
750
    
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
    
class hd(Detector2):
    
    def __init__(self, name, phase, node1_name, node2_name):
        BaseDetector.__init__(self, name, (node1_name, node2_name), max_nodes=2)
    
        self.__homangle = Param("phase", self, None)
    
    @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:   
            n1 = self.nodes[0].name
            n2 = self.nodes[1].name
            
            if self.__alternate_beam1[0]: n1 += "*"
            if self.__alternate_beam2[1]: n2 += "*"
            
            rtn.append("hd {0} {1} {2} {3}".format(self.name, self.phase, n1, n2))

            if self.scale != None:
                rtn.append("scale {1} {0}".format(self.name, self.scale))
                
            for p in self._params:
                rtn.extend(p.getFinesseText())
            
        return rtn