finesse.py 53.6 KB
Newer Older
Daniel Brown's avatar
Daniel Brown committed
1001
1002
1003
        if isinstance(obj, Component):
            nodes = self.nodes.getComponentNodes(obj)

1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
        if isinstance(obj, Component):    
            del self.__components[obj.name]
            self.__del_component(obj)
            self.nodes.removeComponent(obj)
        elif isinstance(obj, Command):    
            del self.__commands[obj.name]
            self.__del_command(obj)
        elif isinstance(obj, Detector):    
            del self.__detectors[obj.name]
            self.__del_detector(obj)
        
        for b in self.__blocks:
            if obj in self.__blocks[b].contents:
                self.__blocks[b].contents.remove(obj)
        
Daniel Brown's avatar
Daniel Brown committed
1019
1020
1021
1022
1023
        if self.pykatgui != None:
            self.pykatgui._onComponentRemoved(obj, nodes)
    
        del nodes
        
1024
1025
        import gc
        print gc.get_referrers(obj)
1026
    
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
    def getMatrices(self):
        
        import scipy
        from scipy.sparse import coo_matrix
        
        prev = self.noxaxis
        
        self.noxaxis = True
        self.printmatrix = True
        print "".join(self.generateKatScript())
        self.verbose = True
        self.run(printout=1)
        self.printmatrix = None
        self.noxaxis = prev        
        
        if self.__prevrunfilename == None:
            return None
        else:
            
            Mcarrier = None
            Msignal = None
            
            if os.path.exists("klu_full_matrix_car.dat"):
                M = np.loadtxt("klu_full_matrix_car.dat")
                
                if M.size > 0:
                    row = M[:,0]-1
                    col = M[:,1]-1
                    data = M[:,2] + 1j * M[:,3]
                    N = row.max()+1
                    Mcarrier = coo_matrix((data,(row,col)), shape=(N,N))
                
        
            if os.path.exists("klu_full_matrix_sig.dat"):
                M = np.loadtxt("klu_full_matrix_sig.dat")
                
                if M.size > 0:
                    row = M[:,0]-1
                    col = M[:,1]-1
                    data = M[:,2] + 1j * M[:,3]
                    N = row.max()+1
                    Msignal = coo_matrix((data,(row,col)), shape=(N,N))
        
            return (Mcarrier, Msignal)

        
1073
1074
    def hasNamedObject(self, name):
        return name in self.__components or name in self.__detectors or name in self.__commands
Daniel Brown's avatar
Daniel Brown committed
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
        
    def add(self, obj):
        try:
            obj.tag = self.__currentTag
            self.__blocks[self.__currentTag].contents.append(obj)
            
            if isinstance(obj, Component):
                
                if obj.name in self.__components :
                    raise pkex.BasePyKatException("A component with name '{0}' has already been added".format([obj.name]))            
                            
                self.__components[obj.name] = obj
                self.__add_component(obj)
                
            elif isinstance(obj, Detector):
                
                if obj.name in self.__detectors :
                        raise pkex.BasePyKatException("A detector '{0}' has already been added".format(obj.name))
                        
                self.__detectors[obj.name] = obj
                self.__add_detector(obj)
                
            elif isinstance(obj, Command):
                
                self.__commands[obj.__class__.__name__] = obj
                self.__add_command(obj)
                
1102
            else:
Daniel Brown's avatar
Daniel Brown committed
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
                raise pkex.BasePyKatException("Object {0} could not be added".format(obj))
                
            obj._on_kat_add(self)
            
        except pkex.BasePyKatException as ex:
            print ex

    def readOutFile(self, filename):
        
        with open(filename,'r') as outfile:
            # read first to lines to get to header line
            outfile.readline()
            outfile.readline()
            
            hdr = outfile.readline().replace('%','').replace('\n','').split(',')
        
1119
1120
1121
1122
1123
1124
        data = np.loadtxt(filename, comments='%',skiprows=4)

        # convert 1D arrays into 2D ones for simpler selection
        if len(data.shape) == 1:
            data = np.array([data])
                            
1125
        if hasattr(self, "x2axis") and self.noxaxis == False:
Daniel Brown's avatar
Daniel Brown committed
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
            # need to parse 2D outputs slightly different as they are effectively 2D matrices
            # written in linear form
            x = data[0::(1+self.x2axis.steps),0]
            y = data[0:(1+self.x2axis.steps),1]
            # get rows and columns lined up so that we can reshape a single column of all x/y data
            # into a matrix
            z = data[:,2:].transpose().reshape(data.shape[1]-2, 1+self.xaxis.steps, 1+self.x2axis.steps)
            # once you do this the data for y and x axes need swapping
            z = z.swapaxes(1,2)
            return [x, y, z, hdr]
        else:
            shape_len = len(data.shape)
            
1139
            rows,cols = data.shape
Daniel Brown's avatar
Daniel Brown committed
1140
            
1141
1142
1143
            x = data[:,0]
            y = data[:,1:cols]
        
Daniel Brown's avatar
Daniel Brown committed
1144
            return [x, y, hdr]
1145
1146
1147
1148
1149
1150
1151
1152
1153

    def removeLine(self, fragment) :
        for key in self.__blocks:
            objs = self.__blocks[key].contents
            for obj in objs:
                if isinstance(obj, str):
                    if fragment in obj:
                        print "  ** removing line '{0}'".format(obj)
                        objs.remove(obj)
1154
1155

                    
Daniel Brown's avatar
Daniel Brown committed
1156
1157
    def generateKatScript(self) :
        """ Generates the kat file which can then be run """
1158

1159
        def writeBlock():
Daniel Brown's avatar
Daniel Brown committed
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
            for obj in objs:
                if isinstance(obj, str):
                    out.append(obj + '\n')
                    
                elif isinstance(obj, Component) or isinstance(obj, Detector) or isinstance(obj, Command):
                    txt = obj.getFinesseText() 
                    
                    if txt != None:
                        if isinstance(txt,list):
                            for t in txt:
                                out.append(t + "\n")
                        else:
                            out.append(txt + "\n")
1173

1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
        
        out = []    
        import datetime
        strtoday = datetime.datetime.now()
        out.append(strtoday.strftime("%% Generated by PyKat %d.%m.%Y %H:%M:%S\n") )

        # write the FTblocks
        for key in self.__blocks:
            objs = self.__blocks[key].contents

1184
            if key != NO_BLOCK:
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
                if np.size(objs)>0:
                    out.append("\n")
                    out.append("%%% FTblock " + key + "\n")
                    writeBlock()
                    out.append("%%% FTend " + key + "\n")

        # write the NO_BLOCK blocks
        for key in self.__blocks:
            objs = self.__blocks[key].contents


            if key == NO_BLOCK:
                if np.size(objs)>0:
                    out.append("\n")
                    writeBlock()
                
Daniel Brown's avatar
Daniel Brown committed
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
        # now loop through all the nodes and get any gauss commands
        for key in self.nodes.getNodes():
            txt = self.nodes.getNodes()[key].getFinesseText()
            
            if txt != None:
                if isinstance(txt,list):
                    for t in txt: out.append(t+ "\n")
                else:
                    out.append(txt + "\n")
        
1211

1212
1213
1214
1215
1216
1217
1218
1219
1220
        # now get any signal commands
        txt = self.signals.getFinesseText()
        
        if txt != None:
            if isinstance(txt,list):
                for t in txt: out.append(t+ "\n")
            else:
                out.append(txt + "\n")

1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
        if self.vacuum != None:
            
            if isinstance(self.vacuum, collections.Container):
                objs = []
                
                if len(self.vacuum) > 0:
                    for a in self.vacuum:
                        if hasattr(a, 'name'):
                            objs.append(a.name)
                        else:
                            objs.append(str(a))

                    out.append("vacuum {0}\n".format(" ".join(objs)))
                                        
            elif isinstance(self.vacuum, str):
                out.append("vacuum {0}\n".format(self.vacuum))
            else:
                pkex.BasePyKatException("Couldn't understand vacuum input list")

1240
        if self.scale != None and self.scale !='': out.append("scale {0}\n".format(self.scale))
Daniel Brown's avatar
Daniel Brown committed
1241
        if self.phase != None: out.append("phase {0}\n".format(self.phase))
Sean Leavey's avatar
Sean Leavey committed
1242
        if self.trace != None: out.append("trace {0}\n".format(self.trace))
1243
1244
1245
1246
1247
        if self.maxtem != None:
                if self.maxtem == -1:
                        out.append("maxtem off\n")
                else:
                        out.append("maxtem {0}\n".format(self.maxtem))
Daniel Brown's avatar
Daniel Brown committed
1248

1249
1250
        if self.noxaxis == True:
            out.append("noxaxis\n")
1251
            
1252
1253
        if self.yaxis != None:
            out.append("yaxis {0}\n".format(self.yaxis))
1254
1255
1256
1257
         
        if self.printmatrix != None and self.printmatrix == True:
            out.append("printmatrix\n")
            
Daniel Brown's avatar
Daniel Brown committed
1258
1259
        if self.lambda0 != 1064e-9:
            out.append("lambda {0}\n".format(self.lambda0))
1260
            
Daniel Brown's avatar
Daniel Brown committed
1261
1262
        # ensure we don't do any plotting. That should be handled
        # by user themselves
1263
1264
        #out.append("gnuterm no\n")
        #out.append("pyterm no\n")
Daniel Brown's avatar
Daniel Brown committed
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
        
        return out
        
    def openGUI(self):
        if NO_GUI:
            print  "No PyQt4 module was installed so cannot open a GUI"
        else:
            self.app = QCoreApplication.instance() 
            created = False
            
            if self.app == None:
                created = True
                self.app = QApplication([""])
                
            if self.pykatgui == None:
                self.pykatgui = pyKatGUI(self)
                self.pykatgui.main()
            else:
                self.pykatgui.show()
                
            if created: self.app.exec_()
    
    def getComponents(self):
        return self.__components.values()
    
    def hasComponent(self, name):
        return (name in self.__components)
    
    def _newName(self, container, prefix):
        n = 1
        name = "{0}{1}".format(prefix, n)
        
        while name in container:
            n += 1
            name = "{0}{1}".format(prefix,n)
        
        return name
    
    def getNewComponentName(self,prefix):
        '''
        Returns a name for a component which hasn't already been added.
        Returns [prefix] + number, where number is greater than 1. e.g.
        if m1 exists getNewName('m') will return 'm2'
        '''
        return self._newName(self.__components, prefix)
    
    def getNewDetectorName(self,prefix):
        '''
        Returns a name for a component which hasn't already been added.
        Returns [prefix] + number, where number is greater than 1. e.g.
        if m1 exists getNewName('m') will return 'm2'
        '''
        return self._newName(self.__detectors, prefix)
        
    def getNewNodeNames(self,prefix,N=1):
        '''
        Returns a list of names for N number of nodes which haven't already been added.
        Returns [prefix] + number, where number is greater than 1. e.g.
        if m1 exists getNewName('m') will return 'm2'
        '''
        rtn = []
        n = 1
        
        for M in range(1,N+1):
            name = "{0}{1}".format(prefix, n)
            
            while name in self.nodes.getNodes() or (name in rtn):
                n += 1
                name = "{0}{1}".format(prefix,n)
        
            rtn.append(name)
            
        return rtn
        
1339
1340
1341
1342
1343
1344
1345
    def lkat_trace(self, getCavities=True, getNodes=True, getSpaces=True):
        """
        Given the current state of the kat object a new FINESSE process is called and just
        the beam tracing routine is run. The object that is returned contains all the information
        from the beam tracing routine for each node and space components defined as well as cavity 
        commands.   
        """
Daniel Brown's avatar
Daniel Brown committed
1346
1347
1348
1349
        if lkat_location == None:
            raise RuntimeError("Could not find shared library 'libkat', please install to a system location or copy to the same directory as this script")
            
        trace_info = Manager().dict()
1350
1351
1352
1353
1354
        
        prev = self.maxtem
        self.maxtem = 0
        
        try:
1355
1356
            p = self.getProcess(f__lkat_trace_callback, trace_info=trace_info,
                                getCavities=getCavities, getNodes=getNodes, getSpaces=getSpaces)
1357
1358
            p.start()
            p.join()
1359
            p.terminate()
1360
            
1361
1362
1363
            # return a local copy of the trace information dictionary
            return dict(trace_info)
        finally: 
1364
            self.maxtem = prev
Daniel Brown's avatar
Daniel Brown committed
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
    
    def __add_detector(self, det):

        if not isinstance(det, Detector):
            raise exceptions.ValueError("Argument is not of type Detector")
        
        name = det.name
        fget = lambda self: self.__get_detector(name)
        
        setattr(self.__class__, name, property(fget))
1375
1376
1377
        setattr(self, '__det_' + name, det)                

    def __del_detector(self, det):
Daniel Brown's avatar
Daniel Brown committed
1378

1379
1380
1381
1382
1383
1384
1385
1386
        if not isinstance(det, Detector):
            raise exceptions.ValueError("Argument is not of type Detector")
        
        name = det.name
        
        delattr(self.__class__, name)
        delattr(self, '__det_' + name) 
        
Daniel Brown's avatar
Daniel Brown committed
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
    def __get_detector(self, name):
        return getattr(self, '__det_' + name) 
        
    def __add_command(self, com):

        if not isinstance(com, Command):
            raise exceptions.ValueError("Argument is not of type Command")
        
        name = com.__class__.__name__
        fget = lambda self: self.__get_command(name)
        
        setattr(self.__class__, name, property(fget))
        setattr(self, '__com_' + name, com)                   

1401
1402
1403
1404
1405
1406
1407
1408
1409
    def __del_command(self, com):

        if not isinstance(com, Command):
            raise exceptions.ValueError("Argument is not of type Command")
        
        name = com.__class__.__name__
        delattr(self.__class__, name)
        delattr(self, '__com_' + name)
        
Daniel Brown's avatar
Daniel Brown committed
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
    def __get_command(self, name):
        return getattr(self, '__com_' + name)            
    
    def __add_component(self, comp):

        if not isinstance(comp, Component):
            raise exceptions.ValueError("Argument is not of type Component")
            
        fget = lambda self: self.__get_component(comp.name)
        
        setattr(self.__class__, comp.name, property(fget))
        setattr(self, '__comp_' + comp.name, comp)                   
1422
1423
        
    def __del_component(self, comp):
Daniel Brown's avatar
Daniel Brown committed
1424

1425
1426
1427
1428
1429
1430
        if not isinstance(comp, Component):
            raise exceptions.ValueError("Argument is not of type Component")
        
        delattr(self.__class__, comp.name)
        delattr(self, '__comp_' + comp.name)
        
Daniel Brown's avatar
Daniel Brown committed
1431
1432
1433
1434
    def __get_component(self, name):
        return getattr(self, '__comp_' + name)        

    def remove_comments(self, string):
1435
1436
1437
        """
        This takes a raw Finesse code string and removes any comments
        It returns a list of lines however, not a multiline string.
1438
        Also removes any extrawhite space in command lines.
1439
        """
Daniel Brown's avatar
Daniel Brown committed
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
        pattern = r"(\".*?\"|\'.*?\'|%{3}[^\r\n]*$)|(/\*.*?\*/|%[^\r\n]*$|#[^\r\n]*$|//[^\r\n]*$)"
        # first group captures quoted strings (double or single)
        # second group captures comments (//single-line or /* multi-line */)
        regex = re.compile(pattern, re.MULTILINE|re.DOTALL)
        def _replacer(match):
            # if the 2nd group (capturing comments) is not None,
            # it means we have captured a non-quoted (real) comment string.
            if match.group(2) is not None:
                return "" # so we will return empty to remove the comment
            else: # otherwise, we will return the 1st group
                return match.group(1) # captured quoted-string
1451
1452
1453
1454
1455
1456
1457
        
        # remove any inline comments
        string = regex.sub(_replacer, string)
        
        commands = []
        
        for line in string.split('\n'):
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
            line = line.replace('\r','')
            if len(line) > 0:
                # remove any mutliple whitespace
                line = " ".join(line.split())
                # add to a list all the positions of any inline comment markers
                i = [line.find('#'), line.find('\\')]
                i = filter(lambda a: a != -1, i)
        
                if len(i) == 0:
                    commands.append(line)
                else:
                    line = line[0:min(i)]
                    if len(line):
                        commands.append(line)
        
        
1474
        return commands
1475
1476
1477

# printing pykat logo on first input
kat.logo()