示例#1
0
    def test_update(self):
        """
        same data different mask
        """
        bpmlst = [e.name for e in ap.getElements('BPM')]
        trimlst = ['ch1g6c15b', 'cl2g6c14b', 'cm1g4c26a']
        trimlst1 = trimlst[0:1]
        trimlst2 = trimlst[1:2]

        #trimx = ['CXH1G6C15B']
        trims = ap.getElements(trimlst)
        for t in trims: 
            t.x = 0
            t.y = 0

        nametag = time.strftime("%Y%m%d_%H%M.hdf5")
        fname1 = "orm_update_1_" + nametag
        fname2 = "orm_update_2_" + nametag
        orm1 = ap.measOrbitRm(bpmlst, trimlst1, fname1, verbose=2)
        orm2 = ap.measOrbitRm(bpmlst, trimlst2, fname2, verbose=2)

        ormdata_dst = ap.OrmData(fname1)
        ormdata_src = ap.OrmData(fname2)
        
        ormdata_dst.update(ormdata_src)

        self.assertIn(trimlst2[0], ormdata_dst.getTrimNames())
示例#2
0
    def test_measure_orm_sub1_l2(self):
        #trimlst = ['ch1g6c15b', 'cl2g6c14b', 'cm1g4c26a']
        trimlst = ['cl2g6c14b']
        #trimx = ['CXH1G6C15B']
        bpmlst = [e.name for e in ap.getElements('BPM')]
        trims = ap.getElements(trimlst)
        for t in trims: 
            t.x = 0
            t.y = 0

        fname = time.strftime("orm_sub1_%Y%m%d_%H%M.hdf5")
        orm1 = ap.measOrbitRm(bpmlst, trimlst, fname, verbose=2)

        ormdat = ap.apdata.OrmData(fname)
        
        corr = trims[0] 
        x0 = corr.x
        obt0 = ap.getOrbit(spos=True)
        dxlst = np.linspace(-1e-4, 1e-4, 5) + x0
        obt = []
        for i,dx in enumerate(dxlst):
            corr.x = dx
            time.sleep(3)
            obt.append(ap.getOrbit(spos=True))

        jbpm = 36
        bpm = ap.getExactElement(bpmlst[jbpm])
        mij = ormdat.get(bpm.name, 'x', corr.name, 'x')
        dxobt = [obt[i][jbpm,0] for i in range(len(dxlst))]
        plt.clf()
        plt.plot(dxlst, dxobt, 'r--o')
        plt.plot(dxlst, mij*dxlst + obt0[jbpm,0])
        plt.savefig(figname("test_measure_orm_sub1_linearity.png"))
        corr.x = x0
示例#3
0
    def test_orbit_bump(self):
        v0 = ap.getOrbit()
        bpm = ap.getElements("BPM")
        hcor = ap.getElements("HCOR")
        hcor1 = ap.getElements("cx*")
        vcor = ap.getElements("VCOR")
        vcor1 = ap.getElements("cy*")
        # for e in hcor:
        #    print e.name, e.pv(field='x')

        self.assertGreater(len(v0), 0)
        self.assertGreaterEqual(len(bpm), 180)
        self.assertEqual(len(hcor1), 180)
        self.assertGreaterEqual(len(hcor), 180)
        self.assertEqual(len(vcor1), 180)
        self.assertGreaterEqual(len(vcor), 180)

        # maximum deviation
        mx, my = max(abs(v0[:, 0])), max(abs(v0[:, 1]))
        ih = np.random.randint(0, len(hcor), 3)
        iv = np.random.randint(0, len(vcor), 4)

        for i in ih:
            hcor[i].x = hcor[i].x + np.random.rand() * 1e-6
        for i in iv:
            vcor[i].y = vcor[i].y + np.random.rand() * 1e-6

        ap.hlalib.waitStableOrbit(v0, minwait=5)

        v1 = ap.getOrbit()
        self.assertNotEqual(np.std(v1[:, 0]), np.std(v0[:, 0]))
        self.logger.info("resetting trims")
        ap.hlalib._reset_trims()
        time.sleep(10)
示例#4
0
    def test_orbit_bump(self):
        v0 = ap.getOrbit()
        bpm = ap.getElements('BPM')
        hcor = ap.getElements('HCOR')
        hcor1 = ap.getElements('cx*')
        vcor = ap.getElements('VCOR')
        vcor1 = ap.getElements('cy*')
        #for e in hcor:
        #    print e.name, e.pv(field='x')

        self.assertGreater(len(v0), 0)
        self.assertGreaterEqual(len(bpm), 180)
        self.assertEqual(len(hcor1), 180)
        self.assertGreaterEqual(len(hcor), 180)
        self.assertEqual(len(vcor1), 180)
        self.assertGreaterEqual(len(vcor), 180)

        # maximum deviation
        mx, my = max(abs(v0[:,0])), max(abs(v0[:,1]))
        ih = np.random.randint(0, len(hcor), 3)
        iv = np.random.randint(0, len(vcor), 4)

        for i in ih: hcor[i].x = hcor[i].x+np.random.rand()*1e-6
        for i in iv: vcor[i].y = vcor[i].y+np.random.rand()*1e-6

        ap.hlalib.waitStableOrbit(v0, minwait=5)

        v1 = ap.getOrbit()
        self.assertNotEqual(np.std(v1[:,0]), np.std(v0[:,0]))
        self.logger.info("resetting trims")
        ap.hlalib._reset_trims()
        time.sleep(10)
示例#5
0
 def test_orm_x1(self):
     hcor = ap.getElements('HCOR')[2]
     bpm1 = ap.getElements('BPM')[5]
     bpm2 = ap.getElements('BPM')[51]
     x0 = hcor.x
     b1, b2 = bpm1.x, bpm2.x
     d = np.zeros((7, 3), 'd')
     for i,dx in enumerate(np.linspace(-1e-4, 1e-4, len(d))):
         hcor.x = x0 + dx
         d[i,0] = hcor.x
         time.sleep(4)
         d[i,1] = bpm1.x
         d[i,2] = bpm2.x
     #
     ormd = ap.machines._lat.ormdata
     bpmr, trimr = [(bpm1.name, 'x'), (bpm2.name, 'x')], [(hcor.name, 'x')]
     m, b, t = ormd.getMatrix(bpmr, trimr, full=False)
     import matplotlib.pylab as plt
     plt.clf()
     plt.plot(d[:,0], d[:,1], 'bo--')
     plt.plot(d[:,0], m[0,0]*d[:,0] + b1, 'b-')
     plt.plot(d[:,0], d[:,2], 'rv--')
     plt.plot(d[:,0], m[1,0]*d[:,0] + b2, 'r-')
     plt.savefig(figname("test_orm.png"))
     hcor.x = x0
示例#6
0
    def test_correct_orbit(self):
        ap.hlalib._reset_trims()

        # a list of horizontal corrector
        hcor = ap.getElements("HCOR")
        hcor_v0 = [e.x for e in hcor]
        # a list of vertical corrector
        vcor = ap.getElements("VCOR")
        vcor_v0 = [e.y for e in vcor]

        bpm = ap.getElements("BPM")
        bpm_v0 = np.array([(e.x, e.y) for e in bpm], "d")

        norm0 = (np.linalg.norm(bpm_v0[:, 0]), np.linalg.norm(bpm_v0[:, 1]))

        ih = np.random.randint(0, len(hcor), 4)
        for i in ih:
            hcor[i].x = np.random.rand() * 1e-5

        iv = np.random.randint(0, len(vcor), 4)
        for i in iv:
            vcor[i].y = np.random.rand() * 1e-5

        # raw_input("Press Enter to correct orbit...")
        time.sleep(4)

        cor = []
        # cor.extend([e.name for e in hcor])
        # cor.extend([e.name for e in vcor])
        cor.extend([hcor[i].name for i in ih])
        cor.extend([vcor[i].name for i in iv])

        bpm_v1 = np.array([(e.x, e.y) for e in bpm], "d")
        norm1 = (np.linalg.norm(bpm_v1[:, 0]), np.linalg.norm(bpm_v1[:, 1]))

        self.assertGreater(norm1[0], norm0[0])

        ap.correctOrbit([e.name for e in bpm], cor)
        ap.correctOrbit(bpm, cor)

        # raw_input("Press Enter to recover orbit...")
        bpm_v2 = np.array([(e.x, e.y) for e in bpm], "d")
        # print "Euclidian norm:",
        norm2 = (np.linalg.norm(bpm_v2[:, 0]), np.linalg.norm(bpm_v2[:, 1]))
        self.assertLess(norm2[0], norm1[0])
        self.assertLess(norm2[1], norm1[1])

        for i in ih:
            hcor[i].x = hcor_v0[i]

        for i in iv:
            vcor[i].y = vcor_v0[i]

        time.sleep(4)
        # raw_input("Press Enter ...")
        bpm_v3 = np.array([(e.x, e.y) for e in bpm], "d")
        # print "Euclidian norm:",
        norm3 = (np.linalg.norm(bpm_v3[:, 0]), np.linalg.norm(bpm_v3[:, 1]))
        self.assertLess(norm3[0], norm1[0])
        self.assertLess(norm3[0], norm1[0])
示例#7
0
    def test_correct_orbit(self):
        ap.hlalib._reset_trims()

        # a list of horizontal corrector
        hcor = ap.getElements('HCOR')
        hcor_v0 = [e.x for e in hcor]
        # a list of vertical corrector
        vcor = ap.getElements('VCOR')
        vcor_v0 = [e.y for e in vcor]

        bpm = ap.getElements('BPM')
        bpm_v0 = np.array([(e.x, e.y) for e in bpm], 'd')

        norm0 = (np.linalg.norm(bpm_v0[:,0]), np.linalg.norm(bpm_v0[:,1]))

        ih = np.random.randint(0, len(hcor), 4)
        for i in ih:
            hcor[i].x = np.random.rand() * 1e-5

        iv = np.random.randint(0, len(vcor), 4)
        for i in iv:
            vcor[i].y = np.random.rand() * 1e-5

        #raw_input("Press Enter to correct orbit...")
        time.sleep(6)

        cor = []
        #cor.extend([e.name for e in hcor])
        #cor.extend([e.name for e in vcor])
        cor.extend([hcor[i].name for i in ih])
        cor.extend([vcor[i].name for i in iv])

        bpm_v1 = np.array([(e.x, e.y) for e in bpm], 'd')
        norm1 = (np.linalg.norm(bpm_v1[:,0]), np.linalg.norm(bpm_v1[:,1]))

        self.assertGreater(norm1[0], norm0[0])

        ap.correctOrbit([e.name for e in bpm], cor)
        ap.correctOrbit(bpm, cor)

        #raw_input("Press Enter to recover orbit...")
        bpm_v2 = np.array([(e.x, e.y) for e in bpm], 'd')
        #print "Euclidian norm:", 
        norm2 = (np.linalg.norm(bpm_v2[:,0]), np.linalg.norm(bpm_v2[:,1]))
        self.assertLess(norm2[0], norm1[0])
        self.assertLess(norm2[1], norm1[1])

        for i in ih:
            hcor[i].x = hcor_v0[i]

        for i in iv:
            vcor[i].y = vcor_v0[i]

        time.sleep(4)
        #raw_input("Press Enter ...")
        bpm_v3 = np.array([(e.x, e.y) for e in bpm], 'd')
        #print "Euclidian norm:", 
        norm3 = (np.linalg.norm(bpm_v3[:,0]), np.linalg.norm(bpm_v3[:,1]))
        self.assertLess(norm3[0], norm1[0])
        self.assertLess(norm3[0], norm1[0])
示例#8
0
    def test_tune_l0(self):
        logging.info("test_tune")
        self.assertEqual(len(ap.getElements('tune')), 1)
        tune = ap.getElements('tune')[0]
        pvx = tune.pv(field='x')[0]
        pvy = tune.pv(field='y')[0]

        nux, nuy = tune.x, tune.y
        self.assertTrue(nux > 30.0)
        self.assertTrue(nuy > 15.0)
示例#9
0
 def test_measure_orm_l2(self):
     bpms = ap.getElements('BPM')
     trims = ap.getElements('COR')
     
     # if jenkins run this test, measure whole ORM
     nbpm, ntrim = 5, 2
     if "JENKINS_URL" in os.environ and \
        int(os.environ.get("BUILD_NUMBER", "0")) % 2 == 0:
         nbpm, ntrim = len(bpms), len(trims)
     bpmlst = [b.name for b in bpms[:nbpm]]
     trimlst = [t.name for t in trims[:ntrim]]
     fname = time.strftime("orm_%Y%m%d_%H%M.hdf5")
     ap.measOrbitRm(bpmlst, trimlst, fname, verbose=2, minwait=5)
示例#10
0
    def test_orbit_read_l0(self):
        self.logger.info("reading orbit")    
        self.assertGreater(len(ap.getElements('BPM')), 0)
        bpm = ap.getElements('BPM')
        for i,e in enumerate(bpm):
            self.assertGreaterEqual(abs(e.x), 0)
            self.assertGreaterEqual(abs(e.y), 0)

        v = ap.getOrbit()
        self.assertGreater(len(v), 0)
        v = ap.getOrbit('*')
        self.assertGreater(len(v), 0)
        v = ap.getOrbit('p[lhm]*')
        self.assertGreater(len(v), 0)
示例#11
0
    def test_orbit_read(self):
        self.logger.info("reading orbit")
        self.assertGreater(len(ap.getElements("BPM")), 0)
        bpm = ap.getElements("BPM")
        for i, e in enumerate(bpm):
            self.assertGreaterEqual(abs(e.x), 0)
            self.assertGreaterEqual(abs(e.y), 0)

        v = ap.getOrbit()
        self.assertGreater(len(v), 0)
        v = ap.getOrbit("*")
        self.assertGreater(len(v), 0)
        v = ap.getOrbit("p[lhm]*")
        self.assertGreater(len(v), 0)
示例#12
0
    def test_getelements_l0(self):
        # get an empty list []
        el = ap.getElements('AABBCC')
        self.assertEqual(len(el), 0)
        # get a [None]
        el = ap.getElements(['AABBCC'])
        self.assertEqual(len(el), 1)
        self.assertIsNone(el[0])

        el = ap.getElements(BPM1)
        self.assertEqual(len(el), 1)
        self.assertTrue(isinstance(el[0], ap.element.CaElement))

        elems = self.lat.getElementList('BPM')
        self.assertEqual(len(elems), 180)
示例#13
0
    def test_vbpm_l0(self):
        vbpms = ap.getElements('HLA:VBPM', include_virtual=True)
        self.assertIsNotNone(vbpms)
        vbpm = vbpms[0]
        self.assertIn('x', vbpm.fields())
        self.assertIn('y', vbpm.fields())

        bpms = ap.getElements('BPM')
        nbpm = len(bpms)
        self.assertEqual(len(vbpm.x), nbpm)
        self.assertEqual(len(vbpm.y), nbpm)
        self.assertEqual(len(vbpm.sb), nbpm)
        #print vbpm.x, np.std(vbpm.x)
        #print vbpm.y, np.std(vbpm.y)
        self.assertGreaterEqual(np.std(vbpm.x), 0.0)
        self.assertGreaterEqual(np.std(vbpm.y), 0.0)
示例#14
0
    def test_vbpm(self):
        vbpms = ap.getElements("HLA:VBPM", include_virtual=True)
        self.assertIsNotNone(vbpms)
        vbpm = vbpms[0]
        self.assertIn("x", vbpm.fields())
        self.assertIn("y", vbpm.fields())

        bpms = ap.getElements("BPM")
        nbpm = len(bpms)
        self.assertEqual(len(vbpm.x), nbpm)
        self.assertEqual(len(vbpm.y), nbpm)
        self.assertEqual(len(vbpm.sb), nbpm)
        # print vbpm.x, np.std(vbpm.x)
        # print vbpm.y, np.std(vbpm.y)
        self.assertGreaterEqual(np.std(vbpm.x), 0.0)
        self.assertGreaterEqual(np.std(vbpm.y), 0.0)
示例#15
0
    def test_dcct_current_l0(self):
        self.assertGreater(ap.getCurrent(), 100.0)

        dccts = ap.getElements('dcct')
        self.assertEqual(len(dccts), 1)
        dcct = dccts[0]
        # current
        #pv = u'SR:C00-BI:G00{DCCT:00}CUR-RB'
        pv = PV_SR_DCCT
        vsrtag = 'aphla.sys.V2SR'
        self.assertEqual(dcct.name,    'dcct')
        #self.assertEqual(dcct.devname, 'DCCT')
        self.assertEqual(dcct.family,  'DCCT')
        self.assertEqual(len(dcct.pv()), 1)
        #self.assertEqual(dcct.pv(tag='aphla.eget'), [pv])
        self.assertEqual(dcct.pv(tag=vsrtag), [pv])
        #self.assertEqual(dcct.pv(tags=['aphla.eget', vsrtag]), [pv])

        self.assertIn('value', dcct.fields())
        self.assertGreater(dcct.value, 1.0)
        self.assertLess(dcct.value, 600.0)

        self.assertGreater(dcct.value, 1.0)
        self.assertGreater(ap.eget('DCCT', 'value', unitsys=None), 1.0)
        self.assertEqual(len(ap.eget('DCCT', ['value'], unitsys=None)), 1)
        self.assertGreater(ap.eget('DCCT', ['value'], unitsys=None)[0], 1.0)
示例#16
0
def chooseElement(fam):
    elems = ap.getElements(fam)
    allelems = [(e.name, Qt.Checked) if e.isEnabled() else
                (e.name, Qt.Unchecked) for e in elems]
    enabled_0 = [i for i, e in enumerate(elems) if e.isEnabled()]
    extra_cols = [('s [m]', [e.sb for e in elems])]
    form = ElementPickDlg(allelems,
                          title="Choose {0}".format(fam),
                          extra_cols=extra_cols)

    if form.exec_():
        enabled = form.checkedIndices()
        el0, el1 = [], []
        for i, e in enumerate(elems):
            if i in enabled_0 and i not in enabled:
                el0.append(i)
            elif i not in enabled_0 and i in enabled:
                el1.append(i)
            if i in enabled: e.setEnabled(True)
            else: e.setEnabled(False)

        if el0:
            _logger.info("{0} {1} '{2}' are disabled".format(
                len(el0), fam, [elems[i].name for i in el0]))
        if el1:
            _logger.info("{0} {1} '{2}' are enabled".format(
                len(el1), fam, [elems[i].name for i in el1]))
示例#17
0
def chooseElement(fam):
    elems = ap.getElements(fam)
    allelems  = [(e.name, Qt.Checked) if e.isEnabled()
                 else (e.name, Qt.Unchecked) for e in elems]
    enabled_0 = [i for i,e in enumerate(elems) if e.isEnabled()]
    extra_cols = [('s [m]', [e.sb for e in elems])]
    form = ElementPickDlg(allelems, title="Choose {0}".format(fam),
                          extra_cols = extra_cols)

    if form.exec_(): 
        enabled = form.checkedIndices()
        el0, el1 = [], []
        for i,e in enumerate(elems):
            if i in enabled_0 and i not in enabled:
                el0.append(i)
            elif i not in enabled_0 and i in enabled:
                el1.append(i)
            if i in enabled: e.setEnabled(True)
            else: e.setEnabled(False)

        if el0:
            _logger.info("{0} {1} '{2}' are disabled".format(
                len(el0), fam, [elems[i].name for i in el0]))
        if el1:
            _logger.info("{0} {1} '{2}' are enabled".format(
                len(el1), fam, [elems[i].name for i in el1]))
示例#18
0
文件: nsls2id.py 项目: willrogers/hla
def chooseBpmCor(ID, userBpm=False):
    """
    choose bpm and corrector
    """
    bpms = ap.getElements("BPM")
    if userBpm:
        bpms += ap.getElements("UBPM")
    bpmfields = []
    for bpm in bpms:
        bpmflds.append([bpm, "x"])
        bpmflds.append([bpm, "y"])

    corfields = []
    for i in range(len(ID.cch)):
        corflds.append([ID, "cch" + "%i" % i])

    return bpmFields, corFields
示例#19
0
def chooseBpmCor(ID, userBpm=False):
    """
    choose bpm and corrector
    """
    bpms = ap.getElements('BPM')
    if userBpm:
        bpms += ap.getElements('UBPM')
    bpmfields = []
    for bpm in bpms:
        bpmflds.append([bpm,'x'])
        bpmflds.append([bpm,'y'])

    corfields = []
    for i in range(len(ID.cch)):
        corflds.append([ID,'cch'+'%i'%i])

    return bpmFields, corFields
示例#20
0
def chooseBpmCor(ID, userBpm=False):
    """
    choose bpm and corrector
    """
    bpms = ap.getElements('BPM')
    if userBpm:
        bpms += ap.getElements('UBPM')
    bpmfields = []
    for bpm in bpms:
        bpmflds.append([bpm,'x'])
        bpmflds.append([bpm,'y'])

    corfields = []
    for i in range(len(ID.cch)):
        corflds.append([ID,'cch'+'%i'%i])

    return bpmFields, corFields
示例#21
0
    def test_measure_orm_sub2_l2(self):
        #trim = ap.getElements('ch1g6c15b')[0]
        trim = ap.getElements('cl2g6c30b')[0]
        bpmlst = [e.name for e in ap.getElements('BPM')]
        trim.put('x', 0.0, unitsys=None)

        fname = time.strftime("orm_sub1_%Y%m%d_%H%M.hdf5")
        ormline = ap.orm.RmCol(bpmlst, trim)
        ormline.measure(['x', 'y'], 'x', verbose = 2)

        # plotting
        if PLOTTING:
            npts, nbpmrow = np.shape(ormline.rawresp)
            plt.figure()
            for j in range(nbpmrow):
                plt.plot(ormline.rawkick[:], ormline.rawresp[:,j], '-o')
            plt.savefig(figname("rm_orm_sub1_%s.png" % trim.name))
示例#22
0
    def test_cor_l0(self):
        hcor = ap.getElements('HCOR')
        self.assertEqual(len(hcor), 180)

        vcor = ap.getElements('VCOR')
        self.assertEqual(len(vcor), 180)

        cor = ap.getElements('COR')
        self.assertEqual(len(cor), 180)

        idcor = ap.getElements('IDCOR')
        self.assertGreater(len(idcor), 0)

        idsimcor = ap.getElements('IDSIMCOR')
        self.assertGreater(len(idsimcor), 0)

        self.assertEqual(len(idcor), len(idsimcor))
示例#23
0
    def test_trim_bpm(self):
        trims = [e.name for e in ap.getElements('COR')]
        for trim in trims:
            self.assertTrue(self.ormdata.hasTrim(trim))

        bpmx = ap.getGroupMembers(['BPM', 'C0[2-4]'], op='intersection')
        self.assertEqual(len(bpmx), 18)
        for bpm in bpmx:
            self.assertTrue(self.ormdata.hasBpm(bpm.name))
示例#24
0
    def test_eget(self):
        v, h = ap.eget('BPM', 'x', header=True)
        self.assertEqual(len(v), len(ap.getElements('BPM')))
        self.assertEqual(len(v), len(h))
        # a tuple of (name, 'x')
        self.assertEqual(len(h[0]), 2)

        v, h = ap.eget('BPM', ['x'], header=True)
        self.assertEqual(len(v), len(ap.getElements('BPM')))
        self.assertEqual(len(v), len(h))
        # a list [(name, 'x')]
        self.assertEqual(len(h[0]), 1)

        v, h = ap.eget('BPM', ['x', 'y', 'x'], header=True)
        self.assertEqual(len(v), len(ap.getElements('BPM')))
        self.assertEqual(len(v), len(h))
        # a list [(name, 'x')]
        self.assertEqual(len(h[0]), 3)
示例#25
0
    def measDispersion(self):
        p = ApMdiSubPlot(live=False)
        p.setAttribute(Qt.WA_DeleteOnClose)
        curves = [
            p.aplot.curve1,
            p.aplot.addCurve(),  # x and xref
            p.aplot.addCurve(),
            p.aplot.addCurve()  # y and yref
        ]
        for curv in curves:
            curv.setStyle(Qwt.QwtPlotCurve.Lines)
        curves[0].setPen(QPen(Qt.red, 1.3, Qt.DashLine))
        curves[1].setPen(QPen(Qt.red, 1.5))
        curves[2].setPen(QPen(Qt.blue, 1.3, Qt.DashLine))
        curves[3].setPen(QPen(Qt.blue, 1.5))
        curves[2].setSymbol(
            Qwt.QwtSymbol(Qwt.QwtSymbol.Triangle, QBrush(Qt.blue),
                          QPen(Qt.black, 1), QSize(8, 8)))

        #p.aplot.curve1.setStyle(Qwt.QwtPlotCurve.)

        #p.setWindowTitle("[%s.%s] %s %s" % (mach, lat, title, fld))
        self.mdiarea.addSubWindow(p)
        #print "Show"
        p.show()
        #plots.append(p)

        #bpms = ap.getGroupMembers(['C20', 'BPM']) + \
        #    ap.getGroupMembers(['C21', 'BPM'])
        bpms = ap.getElements('BPM')
        xl = min([q.sb for q in bpms])
        xr = max([q.se for q in bpms])
        s, btx, bty = [], [], []
        try:
            etaref = ap.getEta([q.name for q in bpms], spos=True)
            curves[1].setData(etaref[:, -1], etaref[:, 0], None)
            curves[3].setData(etaref[:, -1], etaref[:, 1], None)

            fullmagprof = ap.machines.getLattice().getBeamlineProfile()
            magprof = [v for v in fullmagprof if max(v[0]) > xl \
                           and min(v[0]) < xr]
            p.aplot.setMagnetProfile(magprof)
            #p.wid.autoScaleXY()
            p.aplot.replot()

            disp = ap.measDispersion(bpms, verbose=2)
            curves[0].setData(disp[:, -1], disp[:, 0], None)
            curves[2].setData(disp[:, -1], disp[:, 1], None)
            p.wid.autoScaleXY()
            p.aplot.replot()
            _logger.info("dispersion eta measured")
        except:
            _logger.error("error at measEta")
            raise

        _logger.info("finished eta measurement.")
示例#26
0
    def measDispersion(self):
        p = ApMdiSubPlot(live=False)
        p.setAttribute(Qt.WA_DeleteOnClose)
        curves = [p.aplot.curve1, p.aplot.addCurve(),  # x and xref
                  p.aplot.addCurve(), p.aplot.addCurve() # y and yref
                  ]
        for curv in curves: curv.setStyle(Qwt.QwtPlotCurve.Lines)
        curves[0].setPen(QPen(Qt.red, 1.3, Qt.DashLine))
        curves[1].setPen(QPen(Qt.red, 1.5))
        curves[2].setPen(QPen(Qt.blue, 1.3, Qt.DashLine))
        curves[3].setPen(QPen(Qt.blue, 1.5))
        curves[2].setSymbol(Qwt.QwtSymbol(Qwt.QwtSymbol.Triangle,
                                          QBrush(Qt.blue),
                                          QPen(Qt.black, 1),
                                          QSize(8, 8)))
        
        #p.aplot.curve1.setStyle(Qwt.QwtPlotCurve.)

        #p.setWindowTitle("[%s.%s] %s %s" % (mach, lat, title, fld))
        self.mdiarea.addSubWindow(p)
        #print "Show"
        p.show()
        #plots.append(p)

        #bpms = ap.getGroupMembers(['C20', 'BPM']) + \
        #    ap.getGroupMembers(['C21', 'BPM'])
        bpms = ap.getElements('BPM')
        xl = min([q.sb for q in bpms])
        xr = max([q.se for q in bpms])
        s, btx, bty = [], [], []
        try:
            etaref = ap.getEta([q.name for q in bpms], spos=True)
            curves[1].setData(etaref[:,-1], etaref[:,0], None)
            curves[3].setData(etaref[:,-1], etaref[:,1], None)

            fullmagprof = ap.machines.getLattice().getBeamlineProfile()
            magprof = [v for v in fullmagprof if max(v[0]) > xl \
                           and min(v[0]) < xr]
            p.aplot.setMagnetProfile(magprof)
            #p.wid.autoScaleXY()
            p.aplot.replot()


            disp = ap.measDispersion(bpms, verbose=2)
            curves[0].setData(disp[:,-1], disp[:,0], None)
            curves[2].setData(disp[:,-1], disp[:,1], None)
            p.wid.autoScaleXY()
            p.aplot.replot()
            _logger.info("dispersion eta measured")
        except:
            _logger.error("error at measEta")
            raise

        _logger.info("finished eta measurement.")
示例#27
0
    def test_local_bump(self):
        hcor = ap.getElements('HCOR')
        hcor_v0 = [e.x for e in hcor]
        vcor = ap.getElements('VCOR')
        vcor_v0 = [e.y for e in vcor]

        bpm = ap.getElements('BPM')
        bpm_v0 = [[e.x, e.y] for e in bpm]

        bpm_v1 = [[e.x, e.y] for e in bpm]

        bpm_v1[0] = [0, 0]
        bpm_v1[1] = [0, 1e-4]
        bpm_v1[2] = [2e-4, 1e-4]
        bpm_v1[3] = [5e-7, 1e-4]
        bpm_v1[4] = [0, 1e-4]
        bpm_v1[5] = [0, 1e-4]
        for i in range(6, len(bpm)):
            bpm_v1[i] = [0, 0]

        ap.setLocalBump(bpm, hcor+vcor, bpm_v1)
示例#28
0
    def test_local_bump(self):
        hcor = ap.getElements("HCOR")
        hcor_v0 = [e.x for e in hcor]
        vcor = ap.getElements("VCOR")
        vcor_v0 = [e.y for e in vcor]

        bpm = ap.getElements("BPM")
        bpm_v0 = [[e.x, e.y] for e in bpm]

        bpm_v1 = [[e.x, e.y] for e in bpm]

        bpm_v1[0] = [0, 0]
        bpm_v1[1] = [0, 1e-4]
        bpm_v1[2] = [2e-4, 1e-4]
        bpm_v1[3] = [5e-7, 1e-4]
        bpm_v1[4] = [0, 1e-4]
        bpm_v1[5] = [0, 1e-4]
        for i in range(6, len(bpm)):
            bpm_v1[i] = [0, 0]

        ap.setLocalBump(bpm, hcor + vcor, bpm_v1)
示例#29
0
def openLocalBump():
    """create local bump"""
    corbitdlg = OrbitCorrDlg(
        ap.getElements(wx.data.names()), 
        s, x, y, xunit = xunit, yunit=yunit,
        stepsize = 200e-6, 
        orbit_plots=(wx, wy),
        correct_orbit = self.correctOrbit)
    #corbitdlg.resize(600, 500)
    corbitdlg.setWindowTitle("Create Local Bump")
    corbitdlg.show()
    corbitdlg.raise_()
    corbitdlg.activateWindow()
def get_pv_names(mode):
    ''' Given a certain ring mode as a string, return all available pvs  '''
    ap.machines.load(mode)
    result = set()

    elements = ap.getElements('*')
    for element in elements:
        pvs = element.pv()
        if (len(pvs) > 0):
            pv_name = pvs[0].split(':')[0]
            result.add(pv_name)

    return result
def get_pv_names(mode):
    ''' Given a certain ring mode as a string, return all available pvs  '''
    ap.machines.load(mode)
    result = set()

    elements = ap.getElements('*')
    for element in elements:
        pvs = element.pv()
        if(len(pvs) > 0):
            pv_name = pvs[0].split(':')[0]
            result.add(pv_name)

    return result
示例#32
0
    def test_local_bump(self):
        hcor = ap.getElements('HCOR')
        hcor_v0 = [e.x for e in hcor]
        vcor = ap.getElements('VCOR')
        vcor_v0 = [e.y for e in vcor]

        bpm = ap.getElements('BPM')
        bpm_v0 = [[e.x, e.y] for e in bpm]

        bpm_v1 = [[e.x, e.y] for e in bpm]

        for i in range(0, len(bpm)):
            bpm_v1[i] = [0, 0]
        x1, x2 = 1e-4, 2e-4
        bpm_v1[20][0] = x1
        bpm_v1[21][0] = x1
        bpm_v1[22][0] = x1
        bpm_v1[23][0] = x2
        bpm_v1[24][0] = x2
        bpm_v1[25][0] = x1
        bpm_v1[26][0] = x1

        bpm_v1[100][1] = x2
        bpm_v1[101][1] = x2
        bpm_v1[102][1] = x1
        bpm_v1[103][1] = x1
        bpm_v1[104][1] = x2
        bpm_v1[105][1] = x2

        ap.setLocalBump(bpm, hcor+vcor, bpm_v1, repeat=10, verbose=3)

        import matplotlib.pylab as plt
        plt.clf()
        v = ap.getOrbit(spos=True)
        plt.plot(v[:,-1], v[:,0], '-.')
        plt.plot(v[:,-1], v[:,1], '--')
        plt.savefig(figname("test_localbump.png"))
示例#33
0
    def test_chained_quad(self):
        pvs = ['V:3-BSR-MG{QL3G2C29A_T1:3694}Fld:I', 
               'V:3-BSR-MG{QL3G2C29A_T2:7304}Fld:I', 
               'V:3-BSR-MG{QL3G2C29A_T3:10914}Fld:I']
        qs = ap.getElements('ql3g2c29a')
        self.assertEqual(len(qs), 1)
        k1 = ap.caget(pvs)
        self.assertLess(k1[1]/k1[0] - 1.0, 0.005)
        self.assertLess(k1[2]/k1[0] - 1.0, 0.005)

        qs[0].k1 = k1[0] * (1+0.01)
        k1b = ap.caget(pvs)
        self.assertGreater(qs[0].k1 / k1[0] - 1, 0.005)
        self.assertLess(k1b[1]/k1b[0] - 1.0, 0.005)
        self.assertLess(k1b[2]/k1b[0] - 1.0, 0.005)
示例#34
0
def openLocalBump():
    """create local bump"""
    corbitdlg = OrbitCorrDlg(ap.getElements(wx.data.names()),
                             s,
                             x,
                             y,
                             xunit=xunit,
                             yunit=yunit,
                             stepsize=200e-6,
                             orbit_plots=(wx, wy),
                             correct_orbit=self.correctOrbit)
    #corbitdlg.resize(600, 500)
    corbitdlg.setWindowTitle("Create Local Bump")
    corbitdlg.show()
    corbitdlg.raise_()
    corbitdlg.activateWindow()
示例#35
0
    def test_golden(self):
        f = open("golden.txt", "w")
        cors = ap.getElements('COR')
        for c in cors:
            c.x = 0.0
            c.y = 0.0
        time.sleep(2)
        obt0a = ap.getOrbit(spos=True)
        for scale in [1.0, 0.9, 0.8, 0.7, 0.6]:
            ap.correctOrbit(scale=scale, wait=3)
        time.sleep(6)
        obt0 = ap.getOrbit(spos=True)
        d0 = np.zeros((len(cors), 2), 'd')
        for i,c in enumerate(cors):
            d0[i,0] = c.x
            d0[i,1] = c.y
            c.setGolden('x', d0[i,0], unitsys=None)
            c.setGolden('y', d0[i,1], unitsys=None)
            f.write("{0} x {1}\n".format(c.name, d0[i,0]))
            f.write("{0} y {1}\n".format(c.name, d0[i,1]))
        f.close()
        # now reset the orbit
        time.sleep(5)
        for c in cors:
            c.x = 0.0
            c.y = 0.0
        for i,c in enumerate(cors):
            c.reset('x', data='golden')
            c.reset('y', data='golden')
        time.sleep(6)
        d1 = np.zeros((len(cors), 2), 'd')
        for i,c in enumerate(cors):
            d1[i,0] = c.x
            d1[i,1] = c.y
        obt1 = ap.getOrbit(spos=True)

        plt.subplot(311)
        plt.plot(obt0a[:,-1], obt0a[:,0], 'g-')
        plt.plot(obt0[:,-1], obt0[:,0], 'r-')
        plt.plot(obt1[:,-1], obt1[:,0], 'b--')
        plt.subplot(312)
        plt.plot(d1[:,0] - d0[:,0], 'r-')
        plt.plot(d1[:,1] - d0[:,1], 'b--')
        plt.subplot(313)
        plt.plot(obt0[:,-1], obt1[:,0] - obt0[:,0], 'r-x')
        plt.plot(obt1[:,-1], obt1[:,1] - obt0[:,1], 'b-o')
        plt.savefig(figname("test_golden.png"))
示例#36
0
    def test_chained_quad(self):
        pvs = [
            "V:3-BSR-MG{QL3G2C29A_T1:3694}Fld:I",
            "V:3-BSR-MG{QL3G2C29A_T2:7304}Fld:I",
            "V:3-BSR-MG{QL3G2C29A_T3:10914}Fld:I",
        ]
        qs = ap.getElements("ql3g2c29a")
        self.assertEqual(len(qs), 1)
        k1 = ap.caget(pvs)
        self.assertLess(k1[1] / k1[0] - 1.0, 0.005)
        self.assertLess(k1[2] / k1[0] - 1.0, 0.005)

        qs[0].k1 = k1[0] * (1 + 0.01)
        k1b = ap.caget(pvs)
        self.assertGreater(qs[0].k1 / k1[0] - 1, 0.005)
        self.assertLess(k1b[1] / k1b[0] - 1.0, 0.005)
        self.assertLess(k1b[2] / k1b[0] - 1.0, 0.005)
示例#37
0
    def test_bba_l2(self):
        """test bba"""
        # hard coded quad and its strength
        q, cor, bpm = ap.getElements(['ql3g2c29a', 'cl2g2c29a', 'pl2g2c29a'])
        q.put("k1", -1.4894162702, unitsys=None)
        cor.put("x", 0.0, unitsys=None)
        cor.put("y", 0.0, unitsys=None)

        #print q.fields(), q.get('k1', unitsys=None)

        inp = { 'quad': (q, 'k1'), 'cor': (cor, 'x'),
                'bpm': (bpm, 'x'),
                'quad_dkick': -6e-2, 
                'cor_dkicks': np.linspace(-6e-6, 1e-4, 5) }

        bba = ap.bba.BbaBowtie(**inp)
        bba.align()
        bba.plot()
示例#38
0
    def test_bpm_l0(self):
        bpms = ap.getElements('BPM')
        self.assertGreaterEqual(len(bpms), 180)

        bpm = bpms[0]
        #self.assertEqual(bpm.pv(field='xref'), [pvxbba, pvxgold])
        self.assertGreater(bpm.index, 1)
        self.assertFalse(bpm.virtual)
        self.assertEqual(bpm.virtual, 0)
        #self.assertEqual(len(bpm.value), 2)

        self.assertIn('x', bpm.fields())
        self.assertIn('y', bpm.fields())
        self.assertEqual(len(bpm.get(['x', 'y'])), 2)
        self.assertEqual(len(ap.eget('BPM', 'x')), len(bpms))
        self.assertEqual(len(ap.eget('BPM', ['x', 'y'])), len(bpms))

        self.assertGreater(ap.getDistance(bpms[0].name, bpms[1].name), 0.0)
示例#39
0
    def test_corr_orbit_l2(self):
        self._random_kick(3)
        obt = ap.getOrbit()
        bpm = ap.getElements('BPM')[60:101]
        trim = ap.getGroupMembers(['*', '[HV]COR'], op='intersection')
        v0 = ap.getOrbit('p*', spos=True)
        ap.correctOrbit(bpm, trim, repeat=5, scale=0.9)
        time.sleep(4)
        v1 = ap.getOrbit('p*', spos=True)

        import matplotlib.pylab as plt
        plt.clf()
        ax = plt.subplot(211) 
        fig = plt.plot(v0[:,-1], v0[:,0], 'r-x', label='X(before)') 
        fig = plt.plot(v1[:,-1], v1[:,0], 'g-o', label='X(after)')
        plt.legend()
        ax = plt.subplot(212)
        fig = plt.plot(v0[:,-1], v0[:,1], 'r-x', label='Y(before)')
        fig = plt.plot(v1[:,-1], v1[:,1], 'g-o', label='Y(after)')
        plt.legend()
        plt.savefig(figname("test_nsls2_orbit_correct.png"))
示例#40
0
    def test_bpm_l0(self):
        bpms = ap.getElements('BPM')
        self.assertGreaterEqual(len(bpms), 180*3)

        for i in range(1, len(bpms)):
            self.assertGreater(bpms[i].sb, bpms[i-1].sb)
            self.assertGreater(bpms[i].se, bpms[i-1].se)

        bpm = bpms[0]
        #self.assertEqual(bpm.pv(field='xref'), [pvxbba, pvxgold])
        self.assertGreater(bpm.index, 1)
        self.assertFalse(bpm.virtual)
        self.assertEqual(bpm.virtual, 0)
        #self.assertEqual(len(bpm.value), 2)

        self.assertIn('x', bpm.fields())
        self.assertIn('y', bpm.fields())
        self.assertEqual(len(bpm.get(['x', 'y'], unitsys=None)), 2)
        self.assertEqual(len(ap.eget('BPM', 'x', unitsys=None)), len(bpms))
        self.assertEqual(len(ap.eget('BPM', ['x', 'y'], unitsys=None)), len(bpms))

        self.assertGreater(ap.getDistance(bpms[0].name, bpms[1].name), 0.0)
示例#41
0
    def test_bpm_l0(self):
        bpms = ap.getElements("BPM")
        self.assertGreaterEqual(len(bpms), 180 * 3)

        for i in range(1, len(bpms)):
            self.assertGreater(bpms[i].sb, bpms[i - 1].sb)
            self.assertGreater(bpms[i].se, bpms[i - 1].se)

        bpm = bpms[0]
        # self.assertEqual(bpm.pv(field='xref'), [pvxbba, pvxgold])
        self.assertGreater(bpm.index, 1)
        self.assertFalse(bpm.virtual)
        self.assertEqual(bpm.virtual, 0)
        # self.assertEqual(len(bpm.value), 2)

        self.assertIn("x", bpm.fields())
        self.assertIn("y", bpm.fields())
        self.assertEqual(len(bpm.get(["x", "y"], unitsys=None)), 2)
        self.assertEqual(len(ap.eget("BPM", "x", unitsys=None)), len(bpms))
        self.assertEqual(len(ap.eget("BPM", ["x", "y"], unitsys=None)), len(bpms))

        self.assertGreater(ap.getDistance(bpms[0].name, bpms[1].name), 0.0)
示例#42
0
import aphla as ap
ap.enableLog("aphla.log")
ap.machines.load("tpsv1")
print "Elements:", len(ap.getElements("*"))
for i, e in enumerate(ap.getElements("c*")):
    print i, e.pv(field='x', handle="readback"), \
        e.pv(field='x', handle="setpoint")
示例#43
0
import aphla as ap
ap.enableLog("aphla.log")
ap.machines.load("tpsv1")
print "Elements:", len(ap.getElements("*"))
for i,e in enumerate(ap.getElements("c*")):
    print i, e.pv(field='x', handle="readback"), \
        e.pv(field='x', handle="setpoint")

示例#44
0
    def __init__(self, filter_spec = [ [{},False] ]):
        """
        The optional input argument "filter_spec" must be either an empty
        list, or a list of lists, each of contains a dictionary and a bool.
        The keys of each dictionary must be property names of the Element
        object. The bool is the exclusion flag. If true, then the matching is
        reversed. The values of each dictionary are user-supplied filter
        strings. When the argument is empty, there will be no initial
        filtering. If not empty, filtering specified by each dictionary and
        exclusion flag will be applied in the order the dictionary appears
        in the list.

        For example, "filter_spec" may look like

        filter_spec = [ [{'family':'*COR', 'cell':'C01'}, False],
                        [{'family':'H*'}                , True ] ]

        Then, the initial filtering proceeds as follows. First, filtering
        of '*COR' on 'family' and 'C01' on 'cell' will be applied. The
        application ordering depends on the order the dictionary iterates
        the items, i.e., unpredictable, but the result does not change.
        Since the exclusion flag is False for this tuple, selection will
        not be reversed. The resulting list is saved to self.matched[0].

        As a second step, filtering of 'H*' on 'family' will be applied on
        ALL THE ELEMENTS, NOT on the elements based on self.matched[0].
        This filtered result will be now reversed, because the exclusion
        flag for this tuple is True. The resulting list is saved to
        self.matched[1].

        Finally, we will take intersection of self.matched[0] & self.matched[1]
        to come up with the final filtered list self.combined_matched.

        """

        Qt.QObject.__init__(self)


        # key   = property name of Element object
        # value = displayed column name for tables showing choices and matches
        self.elem_property_vs_col_name = \
            {'name':'Name', 'devname':'Dev. Name', 'cell':'Cell',
             'family':'Family', 'girder':'Girder', 'group':'Group',
             'index':'Lat. Index', 'length':'Eff.Len', 'phylen':'Phys. Len.',
             'pv':'PV', 'sb':'sb', 'se':'se', 'symmetry':'Symmetry',
             'virtual':'Virtual', 'sequence':'Sequence'}

        # key   = property name of Element object & exclusion flag
        # value = displayed column name for table showing filters
        self.filter_property_vs_col_name = \
            self.elem_property_vs_col_name.copy()
        self.filter_property_vs_col_name.update({'exclude':'Excl.'}) # adding extra column

        # Specify the default column order you want for tables showing
        # choices and matches.
        self.elem_property_list = ['family', 'name', 'devname', 'cell',
                                   'girder', 'symmetry', 'group', 'virtual',
                                   'sb', 'se', 'pv', 'length', 'phylen',
                                   'index', 'sequence']
        self.col_name_list = [self.elem_property_vs_col_name[prop]
                         for prop in self.elem_property_list]
        self.choice_dict = dict.fromkeys(self.elem_property_list)

        # Specify the default column order you want for table showing
        # filters.
        self.filter_property_list = self.elem_property_list[:]
        self.filter_property_list.insert(0, 'exclude')
        self.filter_col_name_list = [self.filter_property_vs_col_name[prop]
                         for prop in self.filter_property_list]
        self.filter_dict = dict.fromkeys(self.filter_property_list)

        self.numeric_filter_list = ['index', 'phylen', 'length', 'sb', 'se']
        self.not_implemented_filter_list = ['sequence']

        self.filter_spec = filter_spec

        self.allElements = ap.getElements('*')

        # Initialization of matching data information
        self.matched = [ [True]*len(self.allElements) ]
        self.combine_matched_list()
        self.update_choice_dict()

        # Apply initial filters provided by a user, if any.
        if self.filter_spec:
            isCaseSensitive = False
            self.filterData(range(len(self.filter_spec)), isCaseSensitive)

        self.selectedElements = []