finesse.py 98.9 KB
Newer Older
2001
        kat.remove or kat.component.remove() to delete parsed objects.
2002
        """
2003
2004
        found = False

2005
2006
2007
        for key in self.__blocks:
            objs = self.__blocks[key].contents
            for obj in objs:
2008
                if isinstance(obj,  six.string_types):
2009
                    if fragment in obj:
2010
                        print ("  ** removing line '{0}'".format(obj))
2011
                        objs.remove(obj)
2012
2013
2014
2015
2016
                        found = True

        if not found:
            pkex.BasePyKatException("The command fragment '%s' is not an extra line added to this kat object. Please check that the item you are trying to remove has not been parsed as a pykat object." % fragment)

2017

2018
2019
2020
2021
2022
2023
2024
    def addLine(self, line, block=NO_BLOCK) :
        """
        This will forcefully add a line of FINESSE code to a particular block
        if specfied. This command will not undergo any parsing so it will remain
        as just a string. This of course can create possible conflicts with other
        pykat object that create similar commands so becareful.
        """
Daniel Brown's avatar
Daniel Brown committed
2025
        self.__blocks[block].contents.append(line)
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
        
    def printExtraLines(self):
        """
        This prints all the Finesse commands that have not been parsed
        into pykat objects. This should be used for reference only. To
        add or remove extra lines use the addLine and removeLine methods.
        """
        found = False
        
        for key in self.__blocks:
            objs = self.__blocks[key].contents
            for obj in objs:
                if isinstance(obj, six.string_types):
                    print(obj)
                    found = True
        
        if not found:
            print("No extra lines were found")
        
2045
                        
Daniel Brown's avatar
Daniel Brown committed
2046
2047
    def generateKatScript(self) :
        """ Generates the kat file which can then be run """
2048

2049
        def writeBlock():
Daniel Brown's avatar
Daniel Brown committed
2050
            for obj in objs:
2051
                if isinstance(obj, six.string_types):
Daniel Brown's avatar
Daniel Brown committed
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
                    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")
2063

2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
        
        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

2074
            if key != NO_BLOCK:
2075
2076
2077
2078
2079
2080
                if np.size(objs)>0:
                    out.append("\n")
                    out.append("%%% FTblock " + key + "\n")
                    writeBlock()
                    out.append("%%% FTend " + key + "\n")

2081
        
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
        # 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
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
        # 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")
        
2102

2103
2104
2105
2106
2107
2108
2109
2110
2111
        # 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")

2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
        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)))
                                        
2126
            elif isinstance(self.vacuum, six.string_types):
2127
2128
2129
2130
                out.append("vacuum {0}\n".format(self.vacuum))
            else:
                pkex.BasePyKatException("Couldn't understand vacuum input list")

2131
        if self.scale != None and self.scale !='': out.append("scale {0}\n".format(self.scale))
Daniel Brown's avatar
Daniel Brown committed
2132
        if self.phase != None: out.append("phase {0}\n".format(self.phase))
Sean Leavey's avatar
Sean Leavey committed
2133
        if self.trace != None: out.append("trace {0}\n".format(self.trace))
2134
2135
2136
2137
2138
        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
2139

2140
2141
        if self.noxaxis == True:
            out.append("noxaxis\n")
2142
            
2143
        if self.yaxis is not None:
2144
            out.append("yaxis {0}\n".format(self.yaxis))
Daniel Brown's avatar
Daniel Brown committed
2145
2146
2147
2148
        
        if self.deriv_h is not None:
            out.append("deriv_h {0}\n".format(self.deriv_h))
            
2149
2150
2151
2152
        if self.retrace is not None:
            out.append("retrace {0}\n".format(str(self.retrace)))
            
        if self.printmatrix is not None and self.printmatrix == True:
2153
2154
            out.append("printmatrix\n")
            
Daniel Brown's avatar
Daniel Brown committed
2155
2156
        if self.lambda0 != 1064e-9:
            out.append("lambda {0}\n".format(self.lambda0))
2157

Daniel Brown's avatar
Daniel Brown committed
2158
2159
        # ensure we don't do any plotting. That should be handled
        # by user themselves
2160
2161
        #out.append("gnuterm no\n")
        #out.append("pyterm no\n")
Daniel Brown's avatar
Daniel Brown committed
2162
2163
        
        return out
2164

2165
    def nodeGraph(self, output):
2166
        """
2167
        nodeGraph(output)
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215

        Generate node visualisation of pykat node network using the
        pygraphviz package. The generated graphics is saved in output, where the
        output format is determined from the file extension. The exact formats
        available depend on how graphviz was built, but generally .pdf and .png
        should work.
        """
        if not HAS_GRAPHVIZ:
            print('pygraphviz is not installed.')
            return

        import pygraphviz as pgv

        def add_kat_node(G, from_id, node):
            color = 'black' if node.name == 'dump' else 'red'
            G.add_node(node.id, label='', xlabel=node.name, width=0.2,
                       shape='point', fontsize=11, color=color)
            G.add_edge(from_id, node.id)

        G = pgv.AGraph(strict=False)
        G.graph_attr['label'] = 'Created by PyKat'
        G.graph_attr['pencolor'] = 'black'
        G.node_attr['style'] = 'filled'
        G.node_attr['fontname'] = 'helvetica'

        # add components and associated nodes
        for comp in self.components.itervalues():
            if isinstance(comp, pykat.components.laser):
                attr = {'fillcolor': 'Orange', 'shape': 'box'}
            elif isinstance(comp, pykat.components.space):
                attr = {'fillcolor': 'MediumSlateBlue', 'shape': 'diamond'}
            else:
                attr = {'fillcolor': 'LightSkyBlue', 'shape': 'box'}
            G.add_node(comp.name, **attr)
            for node in comp.nodes:
                add_kat_node(G, comp.name, node)

        # add detectors and associated nodes
        for det in self.detectors.itervalues():
            # slightly ugly, but unfortunately detectors don't have the .nodes
            # property like components do.
            if len(det._nodes) > 0:
                G.add_node(det.name, fillcolor='YellowGreen', shape='ellipse')
                for node in det._nodes:
                    add_kat_node(G, det.name, node)
        
        G.draw(output, prog='neato')

2216
2217
2218
2219
    def optivis(self):
        if not HAS_OPTIVIS:
            print("Optivis is not installed")
            return None
Daniel Brown's avatar
Daniel Brown committed
2220
        
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
        import optivis.scene as scene
        import optivis.bench.links as links
        import optivis.view.canvas as canvas
        
        scene = scene.Scene(title="My pykat layout")
        
        # Run through again to add links
        for c in self.getComponents():
            if not isinstance(c, pykat.components.space):
                continue
            
            a = c.connectingComponents()
            
            # Need to handle where spaces don't connect two components but there is a loose
            # node, which may or may not have detectors attached
            if a[0] is None or a[1] is None:
                continue
                
            c1 = a[0].getOptivisComponent()
            c2 = a[1].getOptivisComponent()
            
            no = a[0].getOptivisNode("Output", c.nodes[0])
            ni = a[1].getOptivisNode("Input", c.nodes[1])
            
            if no is None or ni is None:
                raise pkex.BasePyKatException("Optivis node is None")
            
            c._optivis_component = links.Link(outputNode=no, inputNode=ni, length=c.L.value)
            
            c.label_node1 = optivis_label(text="", position=optivis_coord(-0.5, 0), item=c._optivis_component)
            c.label_node2 = optivis_label(text="", position=optivis_coord( 0.5, 0), item=c._optivis_component)
            label_name = optivis_label(text="", position=optivis_coord(0, -0.5), item=c._optivis_component)
            label_name.content["Name"] = c.name
            
            c._optivis_component.labels.append(c.label_node1)
            c._optivis_component.labels.append(c.label_node2)
            c._optivis_component.labels.append(label_name)
            scene.addLink(c._optivis_component)
        
        gui = canvas.Full(scene=scene)
        
        ### get menu bar from Optivis
        menubar = gui.qMainWindow.menuBar()
        
        ### add new Pykat menu and menu items
        pykatMenu = menubar.addMenu('&Pykat')
    
        # save
        save = PyQt4.QtGui.QAction('Save', gui.qMainWindow)
        save.setShortcut('Ctrl+S')
        save.triggered.connect(lambda: self._optivis_doSave(gui))
        pykatMenu.addAction(save)
    
        # trace
        trace = PyQt4.QtGui.QAction('Trace', gui.qMainWindow)
        trace.setShortcut('Ctrl+T')
        trace.triggered.connect(lambda: self._optivis_doTrace(gui))
        pykatMenu.addAction(trace)
    
        return gui
    
    def _optivis_doTrace(self, gui, **kwargs):
        """
        Change at some point to use a stored GUI reference
        """
        if not HAS_OPTIVIS:
            print("Optivis is not installed")
            return None
        
        prev = self.noxaxis
        
        self.noxaxis = True
        out, tdata = self.run(getTraceData=True, **kwargs)
        self.noxaxis = prev
        
        # For now just select the first trace computed
        # Later we could add some gui list to show the different ones
        tdata = tdata[0]
        
        for c in self.getComponents():
            if not isinstance(c, pykat.components.space):
                continue
                
            if not (hasattr(c, "label_node1") and hasattr(c, "label_node2")):
                continue
                
            c.label_node1.content["w0_x"] = tdata[c.nodes[0].name][0].w0
            c.label_node1.content["w_x"] = tdata[c.nodes[0].name][0].w
            c.label_node1.content["z_x"] = tdata[c.nodes[0].name][0].z
            c.label_node1.content["Rc_x"] = tdata[c.nodes[0].name][0].Rc
            c.label_node1.content["Zr_x"] = tdata[c.nodes[0].name][0].zr
            
            c.label_node1.content["w0_y"] = tdata[c.nodes[0].name][1].w0
            c.label_node1.content["w_y"] = tdata[c.nodes[0].name][1].w
            c.label_node1.content["z_y"] = tdata[c.nodes[0].name][1].z
            c.label_node1.content["Rc_y"] = tdata[c.nodes[0].name][1].Rc
            c.label_node1.content["Zr_y"] = tdata[c.nodes[0].name][1].zr
            
            c.label_node2.content["w0_x"] = tdata[c.nodes[1].name][0].w0
            c.label_node2.content["w_x"] = tdata[c.nodes[1].name][0].w
            c.label_node2.content["z_x"] = tdata[c.nodes[1].name][0].z
            c.label_node2.content["Rc_x"] = tdata[c.nodes[1].name][0].Rc
            c.label_node2.content["Zr_x"] = tdata[c.nodes[1].name][0].zr
            
            c.label_node2.content["w0_y"] = tdata[c.nodes[1].name][1].w0
            c.label_node2.content["w_y"] = tdata[c.nodes[1].name][1].w
            c.label_node2.content["z_y"] = tdata[c.nodes[1].name][1].z
            c.label_node2.content["Rc_y"] = tdata[c.nodes[1].name][1].Rc
            c.label_node2.content["Zr_y"] = tdata[c.nodes[1].name][1].zr
       
        gui.redraw()
        
    def _optivis_doSave(self, gui, **kwargs):
        """
        Save kat script from Optivis
        """
        if not HAS_OPTIVIS:
            print("Optivis is not installed")
            return None
    
        # generate file path
        directory = os.path.join(os.path.expanduser('~'), '{0}.kat'.format(gui.scene.title))

        # desired save path
        path = None
    
        # get path to file to export to
        while True:    
            dialog = PyQt4.Qt.QFileDialog(parent=gui.qMainWindow, caption='Save Finesse Script', directory=directory)
            dialog.setAcceptMode(PyQt4.Qt.QFileDialog.AcceptSave)
            dialog.setFileMode(PyQt4.Qt.QFileDialog.AnyFile)

            # show dialog
            dialog.exec_()
      
            if len(dialog.selectedFiles()) is 0:
                # no filename specified
                return

            # get file path and format
            path = str(dialog.selectedFiles()[0])
      
            try:
                # check if we can write to the path
                open(path, 'w').close()
                os.unlink(path)
        
                # if we get this far, all is good so we can break out the infinite loop
                break
            except OSError:
                PyQt4.Qt.QMessageBox.critical(gui.qMainWindow, 'Filename invalid', 'The specified filename is invalid')
            except IOError:
                PyQt4.Qt.QMessageBox.critical(gui.qMainWindow, 'Permission denied', 'You do not have permission to save the file to the specified location.')
    
        # save kat file
        self.saveScript(filename=path)
    
Daniel Brown's avatar
Daniel Brown committed
2378
    def openGUI(self):
2379
2380
        if not USE_GUI:
            raise NoGUIException
Daniel Brown's avatar
Daniel Brown committed
2381
2382
2383
        else:
            self.app = QCoreApplication.instance() 
            created = False
2384
            
2385
            if self.app is None:
Daniel Brown's avatar
Daniel Brown committed
2386
2387
                created = True
                self.app = QApplication([""])
2388
                
2389
            if self.pykatgui is None:
Daniel Brown's avatar
Daniel Brown committed
2390
2391
2392
2393
                self.pykatgui = pyKatGUI(self)
                self.pykatgui.main()
            else:
                self.pykatgui.show()
2394
                
Daniel Brown's avatar
Daniel Brown committed
2395
            if created: self.app.exec_()
2396
    
Daniel Brown's avatar
Daniel Brown committed
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
    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
2448
2449
2450
2451
2452
2453
     
    def _lkat_getProcess(self, callback, **kwargs):
        """
        """
        
        cmd = "\n".join(self.generateKatScript())
Daniel Brown's avatar
Daniel Brown committed
2454
        
2455
2456
2457
2458
        return Process(target=f__lkat_process, args=(callback, cmd, kwargs))
    
      
    def _lkat_trace(self, getCavities=True, getNodes=True, getSpaces=True):
2459
2460
2461
2462
2463
2464
        """
        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.   
        """
2465
        if lkat_location is None:
Daniel Brown's avatar
Daniel Brown committed
2466
2467
2468
            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()
2469
2470
2471
2472
2473
        
        prev = self.maxtem
        self.maxtem = 0
        
        try:
2474
2475
            p = self.getProcess(f__lkat_trace_callback, trace_info=trace_info,
                                getCavities=getCavities, getNodes=getNodes, getSpaces=getSpaces)
2476
2477
            p.start()
            p.join()
2478
            p.terminate()
2479
            
2480
2481
2482
            # return a local copy of the trace information dictionary
            return dict(trace_info)
        finally: 
2483
            self.maxtem = prev
Daniel Brown's avatar
Daniel Brown committed
2484
2485
2486
2487
    
    def __add_detector(self, det):

        if not isinstance(det, Detector):
2488
            raise pkex.BasePyKatException("Argument is not of type Detector")
Daniel Brown's avatar
Daniel Brown committed
2489
2490
2491
2492
        
        name = det.name
        fget = lambda self: self.__get_detector(name)
        
2493
2494
2495
        if hasattr(self, name):
            raise pkex.BasePyKatException("There is something attached to the kat object already called `%s`" % name)
        
Daniel Brown's avatar
Daniel Brown committed
2496
        setattr(self.__class__, name, property(fget))
2497
2498
2499
        setattr(self, '__det_' + name, det)                

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

2501
        if not isinstance(det, Detector):
2502
            raise pkex.BasePyKatException("Argument is not of type Detector")
2503
2504
        
        name = det.name
2505
            
2506
2507
2508
        delattr(self.__class__, name)
        delattr(self, '__det_' + name) 
        
Daniel Brown's avatar
Daniel Brown committed
2509
2510
2511
2512
2513
2514
    def __get_detector(self, name):
        return getattr(self, '__det_' + name) 
        
    def __add_command(self, com):

        if not isinstance(com, Command):
2515
            raise pkex.BasePyKatException("Argument is not of type Command")
Daniel Brown's avatar
Daniel Brown committed
2516
        
2517
2518
2519
2520
2521
        if com._Command__unique:
            name = com.__class__.__name__
        else:
            name = com.name
            
2522
2523
2524
        if hasattr(self, name):
            raise pkex.BasePyKatException("There is something attached to the kat object already called `%s`" % name)
            
Daniel Brown's avatar
Daniel Brown committed
2525
2526
2527
2528
2529
        fget = lambda self: self.__get_command(name)
        
        setattr(self.__class__, name, property(fget))
        setattr(self, '__com_' + name, com)                   

2530
2531
2532
2533
2534
    def __del_command(self, com):

        if not isinstance(com, Command):
            raise exceptions.ValueError("Argument is not of type Command")
        
2535
2536
2537
2538
        if com._Command__unique:
            name = com.__class__.__name__
        else:
            name = com.name
2539
        
2540
2541
2542
        delattr(self.__class__, name)
        delattr(self, '__com_' + name)
        
Daniel Brown's avatar
Daniel Brown committed
2543
2544
2545
2546
2547
2548
    def __get_command(self, name):
        return getattr(self, '__com_' + name)            
    
    def __add_component(self, comp):

        if not isinstance(comp, Component):
2549
            raise pkex.BasePyKatException("Argument is not of type Component")
2550
2551
2552
2553
2554
        
        name = comp.name
        
        if hasattr(self, name):
            raise pkex.BasePyKatException("There is something attached to the kat object already called `%s`" % name)
Daniel Brown's avatar
Daniel Brown committed
2555
            
2556
        fget = lambda self: self.__get_component(name)
Daniel Brown's avatar
Daniel Brown committed
2557
        
2558
2559
        setattr(self.__class__, name, property(fget))
        setattr(self, '__comp_' + name, comp)                   
2560
2561
        
    def __del_component(self, comp):
Daniel Brown's avatar
Daniel Brown committed
2562

2563
        if not isinstance(comp, Component):
2564
            raise pkex.BasePyKatException("Argument is not of type Component")
2565
2566
2567
2568
        
        delattr(self.__class__, comp.name)
        delattr(self, '__comp_' + comp.name)
        
Daniel Brown's avatar
Daniel Brown committed
2569
2570
2571
2572
    def __get_component(self, name):
        return getattr(self, '__comp_' + name)        

    def remove_comments(self, string):
2573
2574
2575
        """
        This takes a raw Finesse code string and removes any comments
        It returns a list of lines however, not a multiline string.
2576
        Also removes any extrawhite space in command lines.
2577
        """
Daniel Brown's avatar
Daniel Brown committed
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
        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
2589
2590
2591
2592
2593
2594
2595
        
        # remove any inline comments
        string = regex.sub(_replacer, string)
        
        commands = []
        
        for line in string.split('\n'):
2596
2597
2598
2599
2600
2601
            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('\\')]
2602
2603
2604
                #i = filter(lambda a: a != -1, i)
                i = [a for a in i if a != -1]    

2605
2606
2607
2608
2609
2610
2611
2612
                if len(i) == 0:
                    commands.append(line)
                else:
                    line = line[0:min(i)]
                    if len(line):
                        commands.append(line)
        
        
2613
        return commands
2614
2615
2616

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