Пример #1
0
def measTuneRm(quad, **kwargs):
    """
    measure the tune response matrix
    """
    output = kwargs.pop("output", None)
    if output is True:
        output = outputFileName("respm", "tunerm")

    qls = getElements(quad)
    _logger.info("Tune RM: {0}".format([q.name for q in qls]))
    quads = []
    for i, q in enumerate(qls):
        pv = q.pv(field="b1", handle="setpoint")
        if not pv: continue
        assert len(pv) == 1, "More than 1 pv found for {0}".format(q.name)
        quads.append((q.name, "b1", pv[0]))
    tune = getElements("tune")
    if not tune:
        raise RuntimeError("Can not find tune element")
    assert "x" in tune[0].fields(), "Can not find tune x"
    assert "y" in tune[0].fields(), "Can not find tune y"

    nupvs = [
        tune[0].pv(field="x", handle="readback")[0],
        tune[0].pv(field="y", handle="readback")[0]
    ]
    m = np.zeros((2, len(quads)), 'd')

    for i, (name, fld, pv) in enumerate(quads):
        mc, dxlst, rawdat = measCaRmCol(pv, nupvs, **kwargs)
        m[:, i] = mc
        time.sleep(kwargs.get("wait", 1.5))
        if output:
            f = h5py.File(output)
            if pv in f:
                del f[pv]
            g = f.create_group(pv)
            g["m"] = m[:, i]
            g["m"].attrs["quad_name"] = name
            g["m"].attrs["quad_field"] = fld
            g["m"].attrs["quad_pv"] = pv
            g["tunes"] = rawdat
            g["tunes"].attrs["pv"] = nupvs
            g["dx"] = dxlst
            f.close()
    if output:
        f = h5py.File(output)
        if "m" in f:
            del f["m"]
        f["m"] = m
        f["m"].attrs["quad_name"] = [r[0] for r in quads]
        f["m"].attrs["quad_field"] = [r[1] for r in quads]
        f["m"].attrs["quad_pv"] = [r[2] for r in quads]
        f.close()

    return m
Пример #2
0
def measTuneRm(quad, **kwargs):
    """
    measure the tune response matrix
    """
    output = kwargs.pop("output", None)
    if output is True:
        output = outputFileName("respm", "tunerm")

    qls = getElements(quad)
    _logger.info("Tune RM: {0}".format([q.name for q in qls]))
    quads = []
    for i, q in enumerate(qls):
        pv = q.pv(field="b1", handle="setpoint")
        if not pv:
            continue
        assert len(pv) == 1, "More than 1 pv found for {0}".format(q.name)
        quads.append((q.name, "b1", pv[0]))
    tune = getElements("tune")
    if not tune:
        raise RuntimeError("Can not find tune element")
    assert "x" in tune[0].fields(), "Can not find tune x"
    assert "y" in tune[0].fields(), "Can not find tune y"

    nupvs = [tune[0].pv(field="x", handle="readback")[0], tune[0].pv(field="y", handle="readback")[0]]
    m = np.zeros((2, len(quads)), "d")

    for i, (name, fld, pv) in enumerate(quads):
        mc, dxlst, rawdat = measCaRmCol(pv, nupvs, **kwargs)
        m[:, i] = mc
        time.sleep(kwargs.get("wait", 1.5))
        if output:
            f = h5py.File(output)
            if pv in f:
                del f[pv]
            g = f.create_group(pv)
            g["m"] = m[:, i]
            g["m"].attrs["quad_name"] = name
            g["m"].attrs["quad_field"] = fld
            g["m"].attrs["quad_pv"] = pv
            g["tunes"] = rawdat
            g["tunes"].attrs["pv"] = nupvs
            g["dx"] = dxlst
            f.close()
    if output:
        f = h5py.File(output)
        if "m" in f:
            del f["m"]
        f["m"] = m
        f["m"].attrs["quad_name"] = [r[0] for r in quads]
        f["m"].attrs["quad_field"] = [r[1] for r in quads]
        f["m"].attrs["quad_pv"] = [r[2] for r in quads]
        f.close()

    return m
Пример #3
0
def measOrbitRm(bpmfld, corfld, **kwargs):
    """
    Measure the orbit response matrix

    :param list bpm: list of (bpm, field)
    :param list trim: list of (trim, field)
    :param str output: output filename
    :param str h5group: data group name for HDF5 output, "OrbitResponseMatrix"
    :param float minwait: waiting seconds before each orbit measurement.
    :param list dxlst:
    :param list dxmax: 
    :param int nx: default 4

    seealso :class:`~aphla.respmat.OrbitRespMat`, 
    :func:`~aphla.respmat.OrbitRespMat.measure`

    quit when beam current < Imin(0.1mA)
    """
    verbose = kwargs.pop("verbose", 0)
    output = kwargs.pop("output", None)
    Imin = kwargs.pop("Imin", 0.1)
    minwait = kwargs.get("minwait", 0.0)

    if output is True:
        output = outputFileName("respm", "orm")
    h5group = kwargs.pop("h5group", "OrbitResponseMatrix")

    _logger.info("Orbit RM shape (%d %d)" % (len(bpmfld), len(corfld)))
    # bpms, cors = [], []
    ## if it is EPICS
    # for fld in ["x", "y", "db0"]:
    #    for e in getElements(bpm):
    #        if fld not in e.fields(): continue
    #        for pv in e.pv(field=fld, handle="readback"):
    #            bpms.append((e.name, fld, pv))
    #    for e in getElements(cor):
    #        if fld not in e.fields(): continue
    #        for pv in e.pv(field=fld, handle="setpoint"):
    #            cors.append((e.name, fld, pv))
    # measure the column

    if "dxlst" in kwargs:
        dxlst = kwargs.pop("dxlst")
    elif "dxmax" in kwargs:
        dxmax, nx = np.abs(kwargs.pop("dxmax", 0.0)), kwargs.pop("nx", 4)
        dxlst = list(np.linspace(-dxmax, dxmax, nx))
    else:
        raise RuntimeError("need input for at least of the parameters: " "dxlst, dxmax")

    t0 = datetime.now()
    tau0, Icur0 = getLifetimeCurrent()
    m = np.zeros((len(bpmfld), len(corfld)), "d")
    if verbose > 0:
        print("total steps: %d" % len(corfld))
        kwargs["verbose"] = verbose - 1

    for i, (cor, fld) in enumerate(corfld):
        # save each column
        m[:, i], xlst, dat = measRmCol(bpmfld, cor, fld, dxlst, **kwargs)
        tau, Icur = getLifetimeCurrent()
        if verbose:
            print("%d/%d" % (i, len(corfld)), cor.name, np.min(m[:, i]), np.max(m[:, i]))

        if output:
            f = h5py.File(output)
            # g0 = f.require_group("OrbitResponseMatrix")
            g0 = f.require_group(h5group)
            grpname = "resp__%s.%s" % (cor.name, fld)
            if grpname in g0:
                del g0[pv]
            g = g0.create_group(grpname)
            g.attrs["lifetime"] = tau
            g.attrs["current"] = Icur
            g["m"] = m[:, i]
            g["m"].attrs["cor_name"] = cor.name
            g["m"].attrs["cor_field"] = fld
            g["m"].attrs["cor_dxlst_sp"] = dxlst
            g["m"].attrs["cor_xlst_rb"] = xlst
            # g["m"].attrs["cor_pv"] = cor.pv(field=fld, handle="setpoint")
            # g["m"].attrs["bpm_pv"] = [b.pv(field=fld) for b,fld in bpmfld]
            g["m"].attrs["bpm_name"] = [b.name for b, fld in bpmfld]
            g["m"].attrs["bpm_field"] = [fld for b, fld in bpmfld]
            g["orbit"] = dat
            # g["orbit"].attrs["pv"] = [b.pv(field=fld) for b,fld in bpmfld]
            g["cor"] = xlst
            f.close()
        if Icur < Imin:
            break

    t1 = datetime.now()
    tau1, Icur1 = getLifetimeCurrent()
    if output:
        # save the overall matrix
        f = h5py.File(output)
        g = f.require_group(h5group)
        if "m" in g:
            del g["m"]
        g["m"] = m
        g["m"].attrs["cor_name"] = [c.name for c, fld in corfld]
        g["m"].attrs["cor_field"] = [fld for c, fld in corfld]
        # corpvs = reduce(lambda x,y: x+y, [c.pv(field=fld) for c,fld in corfld])
        # g["m"].attrs["cor_pv"]    = corpvs
        g["m"].attrs["bpm_name"] = [b.name for b, fld in bpmfld]
        g["m"].attrs["bpm_field"] = [fld for b, fld in bpmfld]
        # g["m"].attrs["bpm_pv"]    = pv_bpm
        try:
            import getpass

            g["m"].attrs["_author_"] = getpass.getuser()
        except:
            pass
        g["m"].attrs["t_start"] = t0.strftime("%Y-%m-%d %H:%M:%S.%f")
        g["m"].attrs["t_end"] = t1.strftime("%Y-%m-%d %H:%M:%S.%f")
        g.attrs["timespan"] = (t1 - t0).total_seconds()
        g.attrs["current"] = [Icur0, Icur1]
        g.attrs["lifetime"] = [tau0, tau1]
        f.close()

    return m, output
Пример #4
0
def measOrbitRm(bpmfld, corfld, **kwargs):
    """
    Measure the orbit response matrix

    :param list bpm: list of (bpm, field)
    :param list trim: list of (trim, field)
    :param str output: output filename
    :param str h5group: data group name for HDF5 output, "OrbitResponseMatrix"
    :param float minwait: waiting seconds before each orbit measurement.
    :param list dxlst:
    :param list dxmax: 
    :param int nx: default 4

    seealso :class:`~aphla.respmat.OrbitRespMat`, 
    :func:`~aphla.respmat.OrbitRespMat.measure`

    quit when beam current < Imin(0.1mA)
    """
    verbose = kwargs.pop("verbose", 0)
    output = kwargs.pop("output", None)
    Imin = kwargs.pop("Imin", 0.1)
    minwait = kwargs.get("minwait", 0.0)

    if output is True:
        output = outputFileName("respm", "orm")
    h5group = kwargs.pop("h5group", "OrbitResponseMatrix")

    _logger.info("Orbit RM shape (%d %d)" % (len(bpmfld), len(corfld)))
    #bpms, cors = [], []
    ## if it is EPICS
    #for fld in ["x", "y", "db0"]:
    #    for e in getElements(bpm):
    #        if fld not in e.fields(): continue
    #        for pv in e.pv(field=fld, handle="readback"):
    #            bpms.append((e.name, fld, pv))
    #    for e in getElements(cor):
    #        if fld not in e.fields(): continue
    #        for pv in e.pv(field=fld, handle="setpoint"):
    #            cors.append((e.name, fld, pv))
    # measure the column

    if "dxlst" in kwargs:
        dxlst = kwargs.pop("dxlst")
    elif "dxmax" in kwargs:
        dxmax, nx = np.abs(kwargs.pop("dxmax", 0.0)), kwargs.pop("nx", 4)
        dxlst = list(np.linspace(-dxmax, dxmax, nx))
    else:
        raise RuntimeError("need input for at least of the parameters: "
                           "dxlst, dxmax")

    t0 = datetime.now()
    tau0, Icur0 = getLifetimeCurrent()
    m = np.zeros((len(bpmfld), len(corfld)), 'd')
    if verbose > 0:
        print("total steps: %d" % len(corfld))
        kwargs["verbose"] = verbose - 1

    for i, (cor, fld) in enumerate(corfld):
        # save each column
        m[:, i], xlst, dat = measRmCol(bpmfld, cor, fld, dxlst, **kwargs)
        tau, Icur = getLifetimeCurrent()
        if verbose:
            print("%d/%d" % (i, len(corfld)), cor.name, np.min(m[:, i]),
                  np.max(m[:, i]))

        if output:
            f = h5py.File(output)
            #g0 = f.require_group("OrbitResponseMatrix")
            g0 = f.require_group(h5group)
            grpname = "resp__%s.%s" % (cor.name, fld)
            if grpname in g0: del g0[pv]
            g = g0.create_group(grpname)
            g.attrs["lifetime"] = tau
            g.attrs["current"] = Icur
            g["m"] = m[:, i]
            g["m"].attrs["cor_name"] = cor.name
            g["m"].attrs["cor_field"] = fld
            g["m"].attrs["cor_dxlst_sp"] = dxlst
            g["m"].attrs["cor_xlst_rb"] = xlst
            #g["m"].attrs["cor_pv"] = cor.pv(field=fld, handle="setpoint")
            #g["m"].attrs["bpm_pv"] = [b.pv(field=fld) for b,fld in bpmfld]
            g["m"].attrs["bpm_name"] = [b.name for b, fld in bpmfld]
            g["m"].attrs["bpm_field"] = [fld for b, fld in bpmfld]
            g["orbit"] = dat
            #g["orbit"].attrs["pv"] = [b.pv(field=fld) for b,fld in bpmfld]
            g["cor"] = xlst
            f.close()
        if Icur < Imin: break

    t1 = datetime.now()
    tau1, Icur1 = getLifetimeCurrent()
    if output:
        # save the overall matrix
        f = h5py.File(output)
        g = f.require_group(h5group)
        if "m" in g:
            del g["m"]
        g["m"] = m
        g["m"].attrs["cor_name"] = [c.name for c, fld in corfld]
        g["m"].attrs["cor_field"] = [fld for c, fld in corfld]
        #corpvs = reduce(lambda x,y: x+y, [c.pv(field=fld) for c,fld in corfld])
        #g["m"].attrs["cor_pv"]    = corpvs
        g["m"].attrs["bpm_name"] = [b.name for b, fld in bpmfld]
        g["m"].attrs["bpm_field"] = [fld for b, fld in bpmfld]
        #g["m"].attrs["bpm_pv"]    = pv_bpm
        try:
            import getpass
            g["m"].attrs["_author_"] = getpass.getuser()
        except:
            pass
        g["m"].attrs["t_start"] = t0.strftime("%Y-%m-%d %H:%M:%S.%f")
        g["m"].attrs["t_end"] = t1.strftime("%Y-%m-%d %H:%M:%S.%f")
        g.attrs["timespan"] = (t1 - t0).total_seconds()
        g.attrs["current"] = [Icur0, Icur1]
        g.attrs["lifetime"] = [tau0, tau1]
        f.close()

    return m, output
Пример #5
0
def saveLattice(**kwargs):
    """
    save the current lattice info to a HDF5 file.

    Parameters
    -----------
    lattice : Lattice
        lattice object, default the current active lattice
    subgroup : str, default ""
        used for output file name
    note : str, default ""  (notes is deprecated)
    unitsys : str, None
        default "phy", 

    Returns
    -------
    out : str
        the output file name.

    Saved data with unitsys=None and "phy":

    - Magnet: BEND: b0, db0; QUAD: b1; SEXT: b2; COR: x, y;
    - BPM and UBPM: x, x0, xbba, xref0, xref1 (same for y)
    - RFCAVITY: f
    - DCCT: I, tau, Iavg

    Notes
    ------
    Besides all SR PVs, there are some BTS pvs saved without physics
    properties. The saved file does not known if the BTS pvs are readback or
    setpoint. This makes `putLattice` more safe when specifying put setpoint
    pvs only.

    Examples
    ---------
    >>> saveLattice(note="Good one")
    """
    # save the lattice
    output = kwargs.pop("output", 
                        outputFileName("snapshot", kwargs.get("subgroup","")))
    lat = kwargs.get("lattice", machines._lat)
    verbose = kwargs.get("verbose", 0)
    unitsys = kwargs.get("unitsys", "phy")
    notes = kwargs.pop("note", kwargs.pop("notes", ""))

    elemflds = [("BEND", ("b0", "db0")),
                ("QUAD", ("b1",)),
                ("SEXT", ("b2",)),
                ("COR", ("x", "y")),
                ("BPM", ("x", "y", "x0", "y0", "xbba", "ybba",
                         "xref0", "xref1", "yref0", "yref1", "ampl")),
                ("UBPM", ("x", "y", "x0", "y0", "xbba", "ybba",
                         "xref0", "xref1", "yref0", "yref1", "ampl")),
                ("RFCAVITY", ("f", "v", "phi")),
                ("DCCT", ("I", 'tau', "Iavg"))]
    t0 = datetime.now()
    nlive, ndead = _saveLattice(
        output, lat, elemflds, notes, **kwargs)

    h5f = h5py.File(output)
    h5g = h5f[lat.name]
    nameinfo = {}
    for elfam,flds in elemflds:
        for e in lat.getElementList(elfam, virtual=False):
            for fld in flds:
                for pv in e.pv(field=fld):
                    els = nameinfo.setdefault(pv, [])
                    els.append("%s.%s" % (e.name, fld)) 
                if not e.convertible(fld, None, unitsys): continue
                uname = e.getUnit(fld, unitsys=unitsys)
                pvsp = e.pv(field=fld, handle="setpoint")
                pvrb = e.pv(field=fld, handle="readback")
                for pv in pvsp + pvrb:
                    d0 = h5g[pv].value
                    d1 = e.convertUnit(fld, d0, None, unitsys)
                    s = "%s.%s.%s[%s]" % (e.name, fld, unitsys, uname)
                    h5g[pv].attrs[s] = d1
                for pv in pvsp:
                    h5g[pv].attrs["setpoint"] = 1

    for pv,els in nameinfo.items():
        h5g[pv].attrs["element.field"] = els

    t1 = datetime.now()
    try:
        import getpass
        h5g.attrs["_author_"] = getpass.getuser()
    except:
        pass
    h5g.attrs["t_start"] = t0.strftime("%Y-%m-%d %H:%M:%S.%f")
    h5g.attrs["t_end"] = t1.strftime("%Y-%m-%d %H:%M:%S.%f")

    h5f.close()
    
    return output
Пример #6
0
def saveLattice(**kwargs):
    """
    save the current lattice info to a HDF5 file.

    Parameters
    -----------
    lattice : Lattice
        lattice object, default the current active lattice
    subgroup : str, default ""
        used for output file name
    note : str, default ""  (notes is deprecated)
    unitsys : str, None
        default "phy", 

    Returns
    -------
    out : str
        the output file name.

    Saved data with unitsys=None and "phy":

    - Magnet: BEND: b0, db0; QUAD: b1; SEXT: b2; COR: x, y;
    - BPM and UBPM: x, x0, xbba, xref0, xref1 (same for y)
    - RFCAVITY: f
    - DCCT: I, tau, Iavg

    Notes
    ------
    Besides all SR PVs, there are some BTS pvs saved without physics
    properties. The saved file does not known if the BTS pvs are readback or
    setpoint. This makes `putLattice` more safe when specifying put setpoint
    pvs only.

    Examples
    ---------
    >>> saveLattice(note="Good one")
    """
    # save the lattice
    output = kwargs.pop("output",
                        outputFileName("snapshot", kwargs.get("subgroup", "")))
    lat = kwargs.get("lattice", machines._lat)
    verbose = kwargs.get("verbose", 0)
    unitsys = kwargs.get("unitsys", "phy")
    notes = kwargs.pop("note", kwargs.pop("notes", ""))

    elemflds = [("BEND", ("b0", "db0")), ("QUAD", ("b1", )),
                ("SEXT", ("b2", )), ("COR", ("x", "y")),
                ("BPM", ("x", "y", "x0", "y0", "xbba", "ybba", "xref0",
                         "xref1", "yref0", "yref1", "ampl")),
                ("UBPM", ("x", "y", "x0", "y0", "xbba", "ybba", "xref0",
                          "xref1", "yref0", "yref1", "ampl")),
                ("RFCAVITY", ("f", "v", "phi")),
                ("DCCT", ("I", 'tau', "Iavg"))]
    t0 = datetime.now()
    nlive, ndead = _saveLattice(output, lat, elemflds, notes, **kwargs)

    h5f = h5py.File(output)
    h5g = h5f[lat.name]
    nameinfo = {}
    for elfam, flds in elemflds:
        for e in lat.getElementList(elfam, virtual=False):
            for fld in flds:
                for pv in e.pv(field=fld):
                    els = nameinfo.setdefault(pv, [])
                    els.append("%s.%s" % (e.name, fld))
                if not e.convertible(fld, None, unitsys): continue
                uname = e.getUnit(fld, unitsys=unitsys)
                pvsp = e.pv(field=fld, handle="setpoint")
                pvrb = e.pv(field=fld, handle="readback")
                for pv in pvsp + pvrb:
                    d0 = h5g[pv].value
                    d1 = e.convertUnit(fld, d0, None, unitsys)
                    s = "%s.%s.%s[%s]" % (e.name, fld, unitsys, uname)
                    h5g[pv].attrs[s] = d1
                for pv in pvsp:
                    h5g[pv].attrs["setpoint"] = 1

    for pv, els in nameinfo.items():
        h5g[pv].attrs["element.field"] = els

    t1 = datetime.now()
    try:
        import getpass
        h5g.attrs["_author_"] = getpass.getuser()
    except:
        pass
    h5g.attrs["t_start"] = t0.strftime("%Y-%m-%d %H:%M:%S.%f")
    h5g.attrs["t_end"] = t1.strftime("%Y-%m-%d %H:%M:%S.%f")

    h5f.close()

    return output