Ejemplo n.º 1
0
    def test_read(self):

        print "testPySpectra.test_read"

        PySpectra.cls()
        PySpectra.delete()
        PySpectra.setTitle("the graphics window should contain 24 plots")
        PySpectra.read("%s/test/data/ti_au_tio2_sio2_kat55a_0001.fio" %
                       pySpectraPath)
        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 24)
        self.assertEqual(lst[0].name, "TI_AU_TIO2_SIO2_KAT55A_0001")
        self.assertEqual(lst[1].name, "TI_AU_TIO2_SIO2_KAT55A_0001_RING")

        PySpectra.display()
        PySpectra.processEventsLoop(1)

        PySpectra.cls()
        PySpectra.delete()
        PySpectra.setTitle("the graphics window should contain 4 plots")
        PySpectra.read("%s/test/data/SPLITTER_PXE_BL_22_2.dat" % pySpectraPath)
        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 4)
        self.assertEqual(lst[0].name, "scan1")
        self.assertEqual(lst[1].name, "scan2")
        self.assertEqual(lst[2].name, "scan3")
        self.assertEqual(lst[3].name, "scan4")

        PySpectra.display()
        PySpectra.processEventsLoop(1)

        print "testPySpectra.test_read DONE"
Ejemplo n.º 2
0
    def test_create(self):

        print "testIFC.test_create"

        PySpectra.cls()
        PySpectra.delete()
        PySpectra.command("create s1")
        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 1)
        self.assertEqual(lst[0].name, "s1")
        PySpectra.command("display s1")

        PySpectra.command("derivative s1")
        lst = PySpectra.getGqeList()
        self.assertEqual(lst[1].name, "s1_derivative")
        self.assertEqual(len(lst), 2)

        PySpectra.command("antiderivative s1")
        lst = PySpectra.getGqeList()
        self.assertEqual(lst[2].name, "s1_antiderivative")
        self.assertEqual(len(lst), 3)

        PySpectra.command("delete s1")
        PySpectra.command("delete s1_derivative")
        PySpectra.command("delete s1_antiderivative")
        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 0)
        print "testIFC.test_create DONE"

        return
Ejemplo n.º 3
0
    def testCreateScansByGqes(self):

        print "testPySpectra.testCreateScansByGqes"
        PySpectra.cls()
        PySpectra.delete()
        PySpectra.setTitle("create scan by putData-gqes")

        x = np.linspace(0., 10., 100)
        tan = np.tan(x)
        sin = np.sin(x)
        cos = np.cos(x)

        hsh = {
            'putData': {
                'gqes': [{
                    'x': x,
                    'y': tan,
                    'name': 'tan'
                }, {
                    'x': x,
                    'y': cos,
                    'name': 'cos'
                }, {
                    'x': x,
                    'y': sin,
                    'name': 'sin',
                    'showGridY': False,
                    'symbolColor': 'blue',
                    'showGridX': True,
                    'yLog': False,
                    'symbol': '+',
                    'xLog': False,
                    'symbolSize': 5
                }]
            }
        }

        PySpectra.toPyspLocal(hsh)

        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 3)

        self.assertEqual(lst[0].name, 'tan')
        self.assertEqual(lst[1].name, 'cos')
        self.assertEqual(lst[2].name, 'sin')

        comparison = x == lst[0].x
        self.assertTrue(comparison.all())
        comparison = tan == lst[0].y
        self.assertTrue(comparison.all())
        comparison = cos == lst[1].y
        self.assertTrue(comparison.all())
        comparison = sin == lst[2].y
        self.assertTrue(comparison.all())
        PySpectra.display()

        PySpectra.processEventsLoop(1)

        #utils.launchGui()
        print "testPySpectra.testCreateScansByGqes, DONE"
Ejemplo n.º 4
0
def cls():
    '''
    clear screen: allow for a new plot
    '''
    #print( "mpl_graphics.cls")

    if Fig is None:
        _initGraphic()

    Fig.clear()
    Fig.canvas.flush_events()
    #plt.draw()
    if Canvas is not None:
        try:
            Canvas.draw()
        except Exception as e:
            print("mpl_graphics.cls: caught exception from Canvas.draw")
            print(repr(e))
    #
    # clear the plotItems
    #
    gqeList = PySpectra.getGqeList()

    for scan in gqeList:
        scan.plotItem = None
        if type(scan) == PySpectra.Scan:
            scan.plotDataItem = None
            scan.lastIndex = 0
Ejemplo n.º 5
0
    def testWriteReadImage(self):
        print "testPySpectra.testWrite"
        PySpectra.cls()
        PySpectra.delete()

        (xmin, xmax) = (-2., 1)
        (ymin, ymax) = (-1.5, 1.5)
        (width, height) = (200, 200)
        maxiter = 100

        m = PySpectra.Image(name="MandelbrotSet",
                            colorMap='Greys',
                            estimatedMax=maxiter,
                            xMin=xmin,
                            xMax=xmax,
                            width=width,
                            yMin=ymin,
                            yMax=ymax,
                            height=height)

        m.zoomMb(flagDisplay=False)

        ret = PySpectra.write(['MandelbrotSet'])

        PySpectra.cls()
        PySpectra.delete()
        PySpectra.setTitle("create Mandelbrotset; write; read; display")

        self.assertEqual(os.path.exists(ret), True)

        PySpectra.read(ret)

        PySpectra.setTitle("The Mandelbrotset")
        PySpectra.display()
        PySpectra.processEventsLoop(2)

        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 1)

        ima = lst[0]
        self.assertEqual(ima.name, "MandelbrotSet")
        self.assertEqual(type(ima), PySpectra.PySpectra.Image)
        self.assertEqual(ima.width, width)
        self.assertEqual(ima.height, height)

        self.assertEqual(ima.xMin, xmin)
        self.assertEqual(ima.xMax, xmax)
        self.assertEqual(ima.yMin, ymin)
        self.assertEqual(ima.yMax, ymax)

        ima.zoomMb(targetIX=50, targetIY=100, flagDisplay=False)
        PySpectra.display()
        PySpectra.processEventsLoop(1)

        ima.zoomMb(targetIX=50, targetIY=100, flagDisplay=False)
        PySpectra.display()
        PySpectra.processEventsLoop(1)

        return
Ejemplo n.º 6
0
    def testMCAMenu( self):
        print( "testMCAMenu.testMCAMenu, start")

        PySpectra.cls()
        PySpectra.delete()

        mg = HasyUtils.MgUtils.MgConf( None, "mg_tnggui", True)
        mg.addTimer( "eh_t01")
        mg.addMCA( "eh_mca01")
        mg.updateConfiguration()
        #
        self.assertEqual( len(PySpectra.getGqeList()), 0)

        self.assertEqual( testMCAMenu.mcaWidgetClass.statusMCA, "Idle")
        testMCAMenu.mcaWidgetClass.sampleTimeLine.setText( "3")
        testMCAMenu.mcaWidgetClass.cb_startMeasurement()
        self.waitSomeTime( 1.0)
        self.assertEqual( testMCAMenu.mcaWidgetClass.statusMCA, "Busy")
        self.waitSomeTime( 3.0)

        lst = PySpectra.getGqeList()
        #
        # now and then len(lst) is not == 1
        #
        if len( lst) != 1: 
            for elm in lst: 
                print( "+++testMCAMenu: %s" % elm.name)
        self.assertEqual( len( lst), 1)
        self.assertEqual( lst[0].name, "eh_mca01")
        testMCAMenu.mcaWidgetClass.cb_clearMeasurement()
        lst = PySpectra.getGqeList()
        self.assertEqual( len( lst), 0)

        testMCAMenu.mcaWidgetClass.sampleTimeLine.setText( "-1")
        testMCAMenu.mcaWidgetClass.cb_startMeasurement()
        self.waitSomeTime( 1.0)
        self.assertEqual( testMCAMenu.mcaWidgetClass.statusMCA, "Busy")

        
        testMCAMenu.mcaWidgetClass.cb_startMeasurement()
        self.waitSomeTime( 1.0)
        self.assertEqual( testMCAMenu.mcaWidgetClass.statusMCA, "Idle")

        testMCAMenu.mcaWidgetClass.close()

        print( "testMCAMenu.testMCAMenu, DONE")
Ejemplo n.º 7
0
    def test_delete(self):

        print "testIFC.test_delete"
        PySpectra.command("cls")
        PySpectra.command("delete")
        max = 20
        PySpectra.command("setTitle \"s1,s2,s3,s4\"")
        PySpectra.command("create s1 0 10 %d" % max)
        PySpectra.command("create s2 0 10 %d" % max)
        PySpectra.command("create s3 0 10 %d" % max)
        PySpectra.command("create s4 0 10 %d" % max)
        PySpectra.command("display")
        PySpectra.processEventsLoop(1)
        gqeList = PySpectra.getGqeList()
        self.assertEqual(len(gqeList), 4)
        self.assertEqual(gqeList[0].name, "s1")
        self.assertEqual(gqeList[1].name, "s2")
        self.assertEqual(gqeList[2].name, "s3")
        self.assertEqual(gqeList[3].name, "s4")

        PySpectra.command("cls")
        PySpectra.command("delete s2")
        PySpectra.command("setTitle \"s1,s3,s4\"")
        PySpectra.command("display")
        PySpectra.processEventsLoop(1)
        gqeList = PySpectra.getGqeList()
        self.assertEqual(len(gqeList), 3)
        self.assertEqual(gqeList[0].name, "s1")
        self.assertEqual(gqeList[1].name, "s3")
        self.assertEqual(gqeList[2].name, "s4")

        PySpectra.command("cls")
        PySpectra.command("delete s3 s4")
        PySpectra.command("setTitle \"s1\"")
        PySpectra.command("display")
        PySpectra.processEventsLoop(1)
        gqeList = PySpectra.getGqeList()
        self.assertEqual(len(gqeList), 1)
        self.assertEqual(gqeList[0].name, "s1")
        print "testIFC.test_delete DONE"
        return
Ejemplo n.º 8
0
    def test_y2my(self):
        print "testIFC.test_y2my"
        PySpectra.cls()
        PySpectra.delete()
        PySpectra.command("create s1")
        PySpectra.command("y2my s1")

        lst = PySpectra.getGqeList()
        self.assertEqual(lst[1].name, "s1_y2my")
        self.assertEqual(len(lst), 2)
        print "testIFC.test_y2my DONE"

        return
Ejemplo n.º 9
0
    def testCreateDelete(self):
        print "testPySpectra.testCreateDelete"
        PySpectra.delete()
        PySpectra.setTitle("delete;create 4;display;delete")
        scanLst = PySpectra.getGqeList()
        self.assertEqual(len(scanLst), 0)
        PySpectra.Scan(name='t1')
        PySpectra.Scan(name='t2')
        PySpectra.Scan(name='t3')
        PySpectra.Scan(name='t4')
        PySpectra.display()
        scanLst = PySpectra.getGqeList()
        self.assertEqual(len(scanLst), 4)
        PySpectra.delete(['t1', 't2'])
        scanLst = PySpectra.getGqeList()
        self.assertEqual(len(scanLst), 2)
        self.assertEqual(scanLst[0].name, 't3')
        self.assertEqual(scanLst[1].name, 't4')
        PySpectra.delete()
        scanLst = PySpectra.getGqeList()
        self.assertEqual(len(scanLst), 0)

        print "testPySpectra.testCreateDelete, DONE"
Ejemplo n.º 10
0
def _getNumberOfOverlaid( nameList = None):
    '''
    returns the number of gqes which are overlaid to another, 
    used by e.g. graphics.display()
    '''
    count = 0
    for gqe in PySpectra.getGqeList():
        if nameList is not None: 
            if gqe.name not in nameList:
                continue
        if gqe.overlay is not None:
            count += 1

    return count
Ejemplo n.º 11
0
def getNumberOfGqesToBeDisplayed( nameList): 
    '''
    return the number of scans to be displayed.
    Scans that are overlaid do not require extra space
    and are therefore not counted.
    '''
    if len( nameList) == 0:
        nOverlay = 0
        for gqe in PySpectra.getGqeList():
            if gqe.overlay is not None:
                nOverlay += 1
        nGqe = len( PySpectra.getGqeList()) - nOverlay
        if nGqe < 1:
            nGqe = 1
    else:
        nOverlay = 0
        for name in nameList:
            if PySpectra.getGqe( name).overlay is not None:
                nOverlay += 1
        nGqe = len( nameList) - nOverlay
        if nGqe < 1:
            nGqe = 1
    #print( "graphics.getNoOfGqesToBeDisplayed: nGqe %d" %(nGqe))
    return nGqe
Ejemplo n.º 12
0
    def test_create1(self):
        print "testIFC.test_create1"
        PySpectra.cls()
        PySpectra.delete()
        PySpectra.command("create s1 0 10 100")
        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 1)
        self.assertEqual(lst[0].name, "s1")
        self.assertEqual(lst[0].nPts, 100)
        self.assertEqual(lst[0].xMin, 0.)
        self.assertEqual(lst[0].xMax, 10.)
        PySpectra.delete()
        print "testIFC.test_create1 DONE"

        return
Ejemplo n.º 13
0
    def test_readMca_v1(self):

        print "testPySpectra.test_readMca_v1"

        PySpectra.cls()
        PySpectra.delete()
        PySpectra.setTitle("the graphics window should contain 1 MCA plot")
        PySpectra.read("%s/test/data/tst_09153_mca_s1.fio" % pySpectraPath,
                       flagMCA=True)
        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 1)
        self.assertEqual(lst[0].name, "d1_mca01")
        self.assertEqual(lst[0].nPts, 2048)

        PySpectra.display()
        #PySpectra.show()
        PySpectra.processEventsLoop(1)

        print "testPySpectra.test_readMca_v1 DONE"
Ejemplo n.º 14
0
    def test_readMca_v2(self):

        print "testPySpectra.test_readMca_v2"

        PySpectra.cls()
        PySpectra.delete()
        PySpectra.setTitle("2 MCA plots")
        PySpectra.read("%s/test/data/tst_09154_mca_s1.fio" % pySpectraPath,
                       flagMCA=True)
        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 2)
        self.assertEqual(lst[0].name, "d1_mca01")
        self.assertEqual(lst[0].nPts, 8192)
        self.assertEqual(lst[1].name, "d1_mca02")
        self.assertEqual(lst[1].nPts, 8192)

        PySpectra.display()
        PySpectra.processEventsLoop(1)

        print "testPySpectra.test_readMca_v2 DONE"
Ejemplo n.º 15
0
    def testRead(self):
        print "testPySpectra.testRead"
        PySpectra.cls()
        PySpectra.delete()
        PySpectra.setTitle("create;write;read Scan( filename=...); 1 scan")
        scan = PySpectra.Scan(name='t1',
                              xLabel="up to 200 pts",
                              nPts=201,
                              yMin=-10.,
                              yMax=10.)
        ret = PySpectra.write(['t1'])

        PySpectra.delete()

        self.assertEqual(os.path.exists(ret), True)

        scan = PySpectra.Scan(name='t1', fileName=ret, x=1, y=2)

        scanLst = PySpectra.getGqeList()
        self.assertEqual(len(scanLst), 1)
        self.assertEqual(scanLst[0].name, "t1")
        self.assertEqual(scanLst[0].nPts, 201)
Ejemplo n.º 16
0
    def test_createScanByData(self):

        print "testPySpectra.test_createScanByData"

        PySpectra.cls()
        PySpectra.delete()
        PySpectra.setTitle("create scan by data")

        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 0)

        scan = PySpectra.Scan(name='t1',
                              x=[0, 1, 2, 3, 4],
                              y=[10, 12, 11, 14, 12])

        self.assertEqual(scan.name, 't1')
        self.assertEqual(scan.xMin, 0.)
        self.assertEqual(scan.xMax, 4.)
        self.assertEqual(scan.yMin, 10.)
        self.assertAlmostEqual(scan.yMax, 14.2)

        self.assertEqual(scan.nPts, 5)

        self.assertEqual(scan.x[0], 0)
        self.assertEqual(scan.x[4], 4)
        self.assertEqual(scan.y[0], 10)
        self.assertEqual(scan.y[4], 12)

        self.assertEqual(scan.currentIndex, 4)

        PySpectra.info("t1")
        PySpectra.info(["t1"])

        PySpectra.display()
        PySpectra.processEventsLoop(1)

        print "testPySpectra.test_createScanByData, DONE"
Ejemplo n.º 17
0
def setGqeVPs( nameList, flagDisplaySingle, clsFunc):
    '''
    set the gqe viewport, we use the at = (2,3,2) syntax
    which is (nrow, ncol, nplot)
    title and comment are ignored here. they are taken 
    care of in createPlotItem()

    if a gqe has an 'at' field, like (2,2,3), these values
    have higher priority.

    clsFunc is specified to be able to distinguish between mpl and pqt
    '''
    global _lenPlotted
    debug = False

    gqeList = PySpectra.getGqeList()

    if debug:
        print( "\nutils.setGqeVPs.BEGIN: gqeList %s, nameList %s" % \
            ( repr(  [ gqe.name for gqe in gqeList]), repr(  nameList)))

    if len( nameList) == 0:
        #
        # the number of used viewports is (len( gqeList) - numberOfOverlaid) 
        #
        usedVPs = len( gqeList) - _getNumberOfOverlaid()
        if usedVPs != _lenPlotted and _lenPlotted != -1: 
            clsFunc()
        _lenPlotted = usedVPs
        if usedVPs == 0:
            return 
        if usedVPs == 1:
            ncol = 1
            nrow = 1
        elif usedVPs == 2:
            ncol = 1
            nrow = 2
        else:
            ncol = int( math.ceil( math.sqrt( usedVPs)))
            if usedVPs > definitions.MANY_GQES: 
                ncol -= 1
            nrow = int( math.ceil( (float(usedVPs))/float(ncol)))
        nplot = 1 
    elif len( nameList) == 1:
        if _lenPlotted != 1 and _lenPlotted != -1: 
            clsFunc()
        _lenPlotted = 1
        ncol = 1
        nrow = 1
        nplot = 1
    else:
        #
        # the number of used viewports is (len( nameList) - numberOfOverlaid( nameList)) 
        #
        usedVPs = len( nameList) - _getNumberOfOverlaid( nameList)
        if usedVPs != _lenPlotted and _lenPlotted != -1: 
            clsFunc()
        _lenPlotted = usedVPs
        if usedVPs == 0:
            return 
        if usedVPs == 1:
            ncol = 1
            nrow = 1
        elif usedVPs == 2:
            ncol = 1
            nrow = 2
        else:
            ncol = int( math.ceil( math.sqrt( usedVPs)))
            if usedVPs > definitions.MANY_GQES: 
                ncol -= 1
            nrow = int( math.ceil( (float(usedVPs))/float(ncol)))
        nplot = 1 

    if debug:
        print( "utils.setGqeVPs: after first pass: nrow %d, ncol %d nplot %d" % ( nrow, ncol, nplot))

    for gqe in gqeList:
        #
        # overlay? - don't create a viewport gqe.
        #
        if gqe.overlay is not None and not flagDisplaySingle:
            #
            # maybe the gqe.overlay has beed deleted
            #
            if PySpectra.getGqe( gqe.overlay) is None:
                gqe.overlay = None
            else:
                continue

        if len( nameList) > 0:
            if gqe.name not in nameList:
                continue

        if gqe.plotItem is None:
            if gqe.at is None:
                gqe.ncol = ncol
                gqe.nrow = nrow
                gqe.nplot = nplot
            else: 
                gqe.nrow = gqe.at[0]
                gqe.ncol = gqe.at[1]
                gqe.nplot = gqe.at[2]
            if gqe.nrow*gqe.ncol < gqe.nplot:
                raise ValueError( "utils.setGqeVPs: nrow %d * ncol %d < nplot %d, at %s" % \
                                  (gqe.nrow, gqe.ncol, gqe.nplot, gqe.at))
        nplot += 1
    #
    # see if 2 GQEs occupie the same cell
    #
    for first in gqeList: 
        if first.overlay:
            continue

        if len( nameList) > 0:
            if first.name not in nameList:
                continue

        for second in gqeList: 
            if second.overlay:
                continue

            if first.name == second.name: 
                continue

            if len( nameList) > 0:
                if second.name not in nameList:
                    continue
            if first.nrow == second.nrow and \
               first.ncol == second.ncol and \
               first.nplot == second.nplot:
                raise ValueError( "utils.setGqeVPs: %s and %s in the same cell row, col, nplot: %d %d %d, nameList %s" % \
                    (first.name, second.name, first.nrow, first.ncol, first.nplot, repr( nameList)))

    
    if debug:
        for gqe in gqeList: 
            if gqe.overlay is None:
                print( "utils.setGqeVPs.END: %s row, col, nplot: %d %d %d" % \
                    (gqe.name, gqe.nrow, gqe.ncol, gqe.nplot))
            else: 
                print( "utils.setGqeVPs.END: %s overlaid to %s" % \
                    (gqe.name, gqe.overlay))
    return 
Ejemplo n.º 18
0
    def testToPyspLocalColumns(self):
        import random
        print "testZmqIfc.testToPyspLocalColumns"

        hsh = PySpectra.toPyspLocal({'command': ['cls', 'delete']})
        self.assertEqual(hsh['result'], 'done')

        MAX = 25
        pos = np.linspace(0, 10, MAX)
        d1 = np.random.random_sample((len(pos), )) * 1000.
        d2 = np.random.random_sample((len(pos), )) * 1000.

        hsh = PySpectra.toPyspLocal({
            'putData': {
                'title':
                "testing putData & columns",
                'comment':
                "a comment",
                'columns': [{
                    'name': "eh_mot01",
                    'data': pos
                }, {
                    'name': "eh_c01",
                    'data': d1
                }, {
                    'name': "eh_c02",
                    'data': d2,
                    'symbolColor': 'blue',
                    'symbol': '+',
                    'symbolSize': 5,
                    'xLog': False,
                    'yLog': False,
                    'showGridX': False,
                    'showGridY': False
                }]
            }
        })
        self.assertEqual(hsh['result'], 'done')
        PySpectra.toPyspLocal({'command': ['display']})
        self.assertEqual(hsh['result'], 'done')
        PySpectra.processEventsLoop(1)
        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 2)
        self.assertEqual(lst[0].name, "eh_c01")
        self.assertEqual(lst[1].name, "eh_c02")

        #
        # retrieve the data
        #
        hsh = PySpectra.toPyspLocal({'getData': True})
        self.assertEqual(hsh['result'], 'done')
        #
        # ... and compare.
        #
        for i in range(MAX):
            self.assertEqual(pos[i], hsh['getData']['EH_C01']['x'][i])
            self.assertEqual(d1[i], hsh['getData']['EH_C01']['y'][i])
            self.assertEqual(d2[i], hsh['getData']['EH_C02']['y'][i])

        print "testZmqIfc.testToPyspLocalColumns DONE"
        return
Ejemplo n.º 19
0
    def testToPyspLocalScan(self):
        import random
        print "testZmqIfc.testToPyspLocalScan"

        hsh = PySpectra.toPyspLocal({'command': ['cls', 'delete']})
        self.assertEqual(hsh['result'], 'done')

        MAX = 25
        pos = np.linspace(0, 10, MAX)
        d1 = np.random.random_sample((len(pos), )) * 1000.
        d2 = np.random.random_sample((len(pos), )) * 1000.

        PySpectra.toPyspLocal({'command': ['setTitle "testing Scan command"']})
        self.assertEqual(hsh['result'], 'done')

        hsh = PySpectra.toPyspLocal(
            {'Scan': {
                'name': "d1",
                'x': pos,
                'y': d1
            }})
        self.assertEqual(hsh['result'], 'done')
        hsh = PySpectra.toPyspLocal(
            {'Scan': {
                'name': "d2",
                'x': pos,
                'y': d2
            }})
        self.assertEqual(hsh['result'], 'done')

        PySpectra.toPyspLocal({'command': ['setComment \"a comment\"']})
        self.assertEqual(hsh['result'], 'done')
        PySpectra.toPyspLocal({'command': ['display']})
        self.assertEqual(hsh['result'], 'done')
        PySpectra.processEventsLoop(1)
        lst = PySpectra.getGqeList()
        self.assertEqual(len(lst), 2)
        self.assertEqual(lst[0].name, "d1")
        self.assertEqual(lst[1].name, "d2")

        #
        # retrieve the data and compare
        #
        hsh = PySpectra.toPyspLocal({'getData': True})
        for i in range(MAX):
            self.assertEqual(pos[i], hsh['getData']['D1']['x'][i])
            self.assertEqual(d1[i], hsh['getData']['D1']['y'][i])
            self.assertEqual(d2[i], hsh['getData']['D2']['y'][i])
        #
        # set y-values
        #
        PySpectra.toPyspLocal(
            {'command': ['setTitle "set y-values to linear"']})
        self.assertEqual(hsh['result'], 'done')
        for i in range(MAX):
            PySpectra.toPyspLocal(
                {'command': ['setY d1 %d %g' % (i, float(i) / 10.)]})
        #
        # and compare
        #
        o = PySpectra.getGqe('d1')
        for i in range(MAX):
            self.assertEqual(o.y[i], float(i) / 10.)

        PySpectra.toPyspLocal({'command': ['cls', 'display']})
        self.assertEqual(hsh['result'], 'done')
        PySpectra.processEventsLoop(1)

        print "testZmqIfc.testToPyspLocalScan DONE"
        return
Ejemplo n.º 20
0
def _displayImages(nameList):
    '''
    '''
    gqeList = PySpectra.getGqeList()
    for image in gqeList:
        if type(image) != PySpectra.Image:
            continue
        if len(nameList) > 0:
            if image.name not in nameList:
                continue
        _createPlotItem(image, nameList)
        if image.log:
            try:
                image.img = image.plotItem.imshow(
                    numpy.rot90(numpy.flipud(numpy.log(image.data)), k=3),
                    origin='lower',
                    cmap=plt.get_cmap(image.colorMap))
            except Exception as e:
                image.log = False
                print("mpl_graphics: log failed")
                print(repr(e))
                return

        else:
            if image.modulo != -1:
                image.img = image.plotItem.imshow(
                    numpy.rot90(numpy.flipud(image.data % image.modulo), k=3),
                    origin='lower',
                    cmap=plt.get_cmap(image.colorMap))
            else:
                image.img = image.plotItem.imshow(
                    numpy.rot90(numpy.flipud(image.data), k=3),
                    origin='lower',
                    cmap=plt.get_cmap(image.colorMap))

        axes = image.plotItem.axes
        Fig.canvas.draw()
        labels = [item.get_text() for item in axes.get_xticklabels()]
        labelsNew = []
        for l in labels:
            if len(l) == 0:
                labelsNew.append('')
                continue
            x = float(l) / float(
                image.width) * (image.xMax - image.xMin) + image.xMin
            labelsNew.append('%g' % x)
        axes.set_xticklabels(labelsNew)
        labels = [item.get_text() for item in axes.get_yticklabels()]
        labelsNew = []
        for l in labels:
            if len(l) == 0:
                labelsNew.append('')
                continue
            #
            # 14.1.2020
            #   int( l) replaces by float( l)
            #   problem was int( '0.0') caused an error
            #
            y = float(l) / float(
                image.height) * (image.yMax - image.yMin) + image.yMin
            labelsNew.append('%g' % y)
        axes.set_yticklabels(labelsNew)
    return
Ejemplo n.º 21
0
def display(nameList=None):
    '''
    display one or more or all scans

    Parameters
    ----------
    None: 
          display all scans
    Name: string
          a list of scans to be displayed

    Example
    -------
    PySpectra.display( [ 's1', 's2'])
      display scans s1 and s2
    PySpectra.display()
      display all scans

    Module: PySpectra.graphics.<graphLib>.graphics.py
    '''
    #
    # don't want to check for nameList is None below
    #
    #print( "mpl_graphics.display, nameList %s" % repr( nameList))
    if nameList is None:
        nameList = []

    if Fig is None:
        _initGraphic()

    #
    # Do not put a cls() here because it takes a lot of time, especially when
    # fast displays are done.
    # Try /home/kracht/Misc/pySpectra/test/testGQE.py testFillData

    #
    # see if the members of nameList arr in the gqeList
    #
    for nm in nameList:
        if PySpectra.getGqe(nm) is None:
            raise ValueError("graphics.display: %s is not in the gqeList" % nm)

    gqeList = PySpectra.getGqeList()
    #
    # if there is only one scan to be displayed, there is no overlay
    #
    flagDisplaySingle = False
    if len(nameList) == 1 or len(gqeList) == 1:
        flagDisplaySingle = True

    #
    # adjust the graphics window to the number of displayed scans
    #
    nDisplay = utils.getNumberOfGqesToBeDisplayed(nameList)
    _setSizeGraphicsWindow(nDisplay)

    _adjustFigure(nDisplay)

    #
    # set scan.nrow, scan.ncol, scan.nplot
    #
    utils.setGqeVPs(nameList, flagDisplaySingle, cls)

    _displayTitleComment(nameList)

    _displayImages(nameList)
    #
    # --- first pass: run through the scans in gqeList and display
    #     non-overlaid scans
    #
    for scan in gqeList:

        if type(scan) != PySpectra.Scan:
            continue

        #
        # overlay? - don't create a plot for this scan. Plot it
        # in the second pass. But it is displayed, if it is the only
        # scan or if it is the only scan mentioned in nameList
        #
        if scan.overlay is not None and not flagDisplaySingle:
            #
            # maybe the scan.overlay has beed deleted
            #
            if PySpectra.getGqe(scan.overlay) is None:
                scan.overlay = None
            else:
                continue

        if len(nameList) > 0:
            if scan.name not in nameList:
                continue
        #
        # if we re-use the  plotItem ( aka viewport ?),
        # we can use setData(), see below. That makes things much faster.
        #
        if scan.plotItem is None:
            try:
                #print( "graphics.display: creating plot for %s" % scan.name)
                _createPlotItem(scan, nameList)
            except ValueError as e:
                print("graphics.display: exception from createPlotItem")
                print("graphics.display: consider a 'cls'")
                print("graphics.display %s" % repr(e))
                return

            if type(scan) == PySpectra.Scan and scan.textOnly:
                continue

            if scan.doty:
                xDate = []
                #
                # [  0.01 ,   1.009,   2.008,   3.007,   4.006,   5.005,   6.004,
                #    7.003,   8.002,   9.001,  10.   ]
                # ->
                #  [ 737060.01 ,  737061.009,  737062.008,  737063.007,  737064.006,
                # 737065.005,  737066.004,  737067.003,  737068.002,  737069.001, 737070.]
                #
                for x in scan.x[:(scan.currentIndex + 1)]:
                    xDate.append(_doty2datetime(x))
                xDateMpl = matplotlib.dates.date2num(xDate)
                scan.xDateMpl = xDateMpl[:]
                hsh = _preparePlotParams(scan)
                scan.plotDataItem, = scan.plotItem.plot_date(
                    xDateMpl, scan.y[:(scan.currentIndex + 1)], **hsh)
            #
            # not doty
            #
            else:
                hsh = _preparePlotParams(scan)
                scan.plotDataItem, = scan.plotItem.plot(
                    scan.x[:(scan.currentIndex + 1)],
                    scan.y[:(scan.currentIndex + 1)], **hsh)
            #
            # setData is the function name in pyqtgraph
            #
            scan.plotDataItem.setData = scan.plotDataItem.set_data
            scan.lastIndex = scan.currentIndex

        if type(scan) == PySpectra.Scan and scan.textOnly:
            continue
        #
        # modify the scan
        #
        scan.plotItem = scan.plotItem

        #
        # check, if there is something to display
        #
        if scan.lastIndex == scan.currentIndex or \
           scan.currentIndex  == 0:
            #print( "mpl_display, currentIndex %s, lastIndex %s, continue" % (scan.currentIndex, scan.lastIndex))
            continue

        if scan.doty:
            pass
            #xDate = []
            #for x in scan.x[:(scan.currentIndex + 1)]:
            #    xDate.append( _doty2datetime( x))
            #xDateMpl = matplotlib.dates.date2num( xDate)
            #scan.plotItem.plot_date( xDateMpl, scan.y)
        else:
            scan.plotDataItem.set_data(scan.x[:(scan.currentIndex + 1)],
                                       scan.y[:(scan.currentIndex + 1)])
            #
            #  9.7.2019: setting x-limits of the scan
            #    - for aligning motors the x-axis should be auto-ranged,
            #      in both directions
            #    - for scans the x-axis should be fully visible from the beginning
            #
            if scan.autoscaleX:
                scan.plotItem.set_xlim(
                    min(scan.x[0], scan.x[scan.currentIndex]),
                    max(scan.x[0], scan.x[scan.currentIndex]))
            scan.plotItem.set_ylim(numpy.min(scan.y[:(scan.currentIndex + 1)]),
                                   numpy.max(scan.y[:(scan.currentIndex + 1)]))
        #
        # keep track of what has already been displayed
        #
        scan.lastIndex = scan.currentIndex

    #
    # ---
    # --- second pass: display overlaid scans
    # ---
    #
    for scan in gqeList:

        if type(scan) != PySpectra.Scan:
            continue
        #
        # if only one scan is displayed, there is no overlay
        #
        if len(nameList) == 1:
            break

        if scan.overlay is None:
            continue
        #
        # check, if theren is something to display
        #
        if scan.lastIndex == scan.currentIndex:
            continue

        if len(nameList) > 0 and scan.name not in nameList:
            continue
        target = PySpectra.getGqe(scan.overlay)
        if target is None or target.plotItem is None:
            raise ValueError(
                "mpl_graphics.display: %s tries to overlay to %s" %
                (scan.name, scan.overlay))
        #
        # instantiate a second axes that shares the same x-axis
        #
        scan.plotItem = target.plotItem.twinx()

        if scan.xLog:
            scan.plotItem.set_xscale("log")
        if scan.yLog:
            scan.plotItem.set_yscale("log")

        if len( PySpectra.getGqeList()) >= definitions.MANY_GQES or \
           scan.yTicksVisible == False:
            plt.setp(scan.plotItem.get_yticklabels(), visible=False)

        hsh = _preparePlotParams(scan)

        #
        # follow the target scan as far as the axes are concerned
        #
        if target.doty:
            scan.plotItem.plot_date(target.xDateMpl, scan.y, **hsh)
        else:
            scan.plotItem.plot(scan.x[:(scan.currentIndex + 1)],
                               scan.y[:(scan.currentIndex + 1)], **hsh)

        scan.lastIndex = scan.currentIndex
        if scan.autoscaleY:
            scan.plotItem.set_autoscaley_on(True)
        else:
            scan.plotItem.set_ylim(scan.yMin, scan.yMax)

        if scan.useTargetWindow:
            if target.autoscaleY:
                (mi, ma) = target.plotItem.get_ylim()
                scan.plotItem.set_ylim(mi, ma)
            else:
                scan.plotItem.set_ylim(target.yMin, target.yMax)

        if not scan.doty:
            if scan.autoscaleX:
                scan.plotItem.set_autoscalex_on(True)
            else:
                scan.plotItem.set_xlim(scan.xMin, scan.xMax)

    #
    # draw() is non-blocking
    #
    #plt.draw()
    Fig.canvas.flush_events()
    #plt.pause( 0.001)
    if Canvas is not None:
        try:
            Canvas.draw()
        except Exception as e:
            print("mpl_graphics.display: caught exception from Canvas.draw")
            print(repr(e))
    return
Ejemplo n.º 22
0
def createPDF(printer=None, fileName=None, flagPrint=False, format='DINA4'):
    '''
    - create a PDF file, the default name is pyspOutput.pdf 
    - a version of the last output file is created
    - if flagPrint is True, the file is sent to the PRINTER 
    - returns the name of the output file
    '''

    gqeList = PySpectra.getGqeList()
    if len(gqeList) == 0:
        return None

    flag = False
    if Fig is None:
        _initGraphic()
        flag = True

    setWsViewport(format)

    cls()
    display()

    if fileName is None:
        fileName = "pyspOutput.pdf"

    if fileName.find('.pdf') == -1:
        fileName += ".pdf"

    if os.path.exists("/usr/local/bin/vrsn"):
        if os.system("/usr/local/bin/vrsn -s -nolog %s" % fileName):
            print(
                "graphics.createPDF: failed to save the current version of %s"
                % fileName)

    try:
        #
        # the bbox_inches='tight' does not look good,
        # if there is only one plot on the paper
        #
        #Fig.savefig( fileName, bbox_inches='tight')
        Fig.savefig(fileName)
    except Exception as e:
        print("graphics.createPDF: failed to create %s" % fileName)
        print(repr(e))
        return None

    if flag:
        cls()
        close()

    if flagPrint:
        if printer is None:
            printer = os.getenv("PRINTER")
            if printer is None:
                if utils.getHostname() != definitions.hostTK:
                    return
                raise ValueError(
                    "mpl_graphics.createPDF: environment variable PRINTER not defined"
                )
        if os.system("/usr/bin/lpr -P %s %s" % (printer, fileName)):
            print("mpl_graphics.createPDF: failed to print %s on %s" %
                  (fileName, printer))
        else:
            pass
            #
            # it is not clear whether we should print a message here or in the application
            #
            # print( "createPDF: printed %s on %s" % (fileName, printer))

    return fileName