finesse.py 47.4 KB
Newer Older
1001
1002
1003
            x = data[:,0]
            y = data[:,1:cols]
        
Daniel Brown's avatar
Daniel Brown committed
1004
            return [x, y, hdr]
1005
1006
1007
1008
1009
1010
1011
1012
1013

    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)
1014
1015

                    
Daniel Brown's avatar
Daniel Brown committed
1016
1017
    def generateKatScript(self) :
        """ Generates the kat file which can then be run """
1018

1019
        def writeBlock():
Daniel Brown's avatar
Daniel Brown committed
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
            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")
1033

1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
        
        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

1044
            if key != NO_BLOCK:
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
                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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
        # 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")
        
1071

1072
1073
1074
1075
1076
1077
1078
1079
1080
        # 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")

1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
        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")

1100
        if self.scale != None and self.scale !='': out.append("scale {0}\n".format(self.scale))
Daniel Brown's avatar
Daniel Brown committed
1101
        if self.phase != None: out.append("phase {0}\n".format(self.phase))
Sean Leavey's avatar
Sean Leavey committed
1102
        if self.trace != None: out.append("trace {0}\n".format(self.trace))
1103
1104
1105
1106
1107
        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
1108

1109
1110
1111
        if self.noxaxis == True:
            out.append("noxaxis\n")

Daniel Brown's avatar
Daniel Brown committed
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
        # ensure we don't do any plotting. That should be handled
        # by user themselves
        out.append("gnuterm no\n")
        out.append("pyterm no\n")
        
        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
        
Daniel Brown's avatar
Daniel Brown committed
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
    def lkat_trace(self):
        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()

        p = self.getProcess(f__lkat_trace_callback, trace_info=trace_info)
        p.start()
        p.join()

Daniel Brown's avatar
Daniel Brown committed
1200
1201
        # return a local copy of the trace information dictionary
        return dict(trace_info)
Daniel Brown's avatar
Daniel Brown committed
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
    
    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))
1212
1213
1214
        setattr(self, '__det_' + name, det)                

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

1216
1217
1218
1219
1220
1221
1222
1223
        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
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
    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)                   

1238
1239
1240
1241
1242
1243
1244
1245
1246
    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
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
    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)                   
1259
1260
        
    def __del_component(self, comp):
Daniel Brown's avatar
Daniel Brown committed
1261

1262
1263
1264
1265
1266
1267
        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
1268
1269
1270
1271
    def __get_component(self, name):
        return getattr(self, '__comp_' + name)        

    def remove_comments(self, string):
1272
1273
1274
        """
        This takes a raw Finesse code string and removes any comments
        It returns a list of lines however, not a multiline string.
1275
        Also removes any extrawhite space in command lines.
1276
        """
Daniel Brown's avatar
Daniel Brown committed
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
        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
1288
1289
1290
1291
1292
1293
1294
        
        # remove any inline comments
        string = regex.sub(_replacer, string)
        
        commands = []
        
        for line in string.split('\n'):
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
            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)
        
        
1311
        return commands
1312
1313
1314

# printing pykat logo on first input
kat.logo()
For faster browsing, not all history is shown. View entire blame