Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This page holds a few example code-snippets for use in pyana analysis. The analysis is written in python and uses MatPlotLib.PyPlot for plotting of data. Compare with myana user examples to see how (some of) the same things can be done using the myana analysis framework. The most reliable place for up-to-date information about all the event getters in pyana, see: https://confluence.slac.stanford.edu/display/PCDS/Pyana+Reference+Manual#PyanaReferenceManual-Classpyana.event.Event

For all the examples, you may assume that the pyana module contains a class with at least 'beginjob', 'event' and 'endjob' functions that starts something like this:

Code Block
none
none
titleoutline of a pyana module
import numpy as np
import matplotlib.pyplot as plt
from pypdsdata import xtc

class mypyana(object):
    def __init__(self,source=""):
        self.source = source
        self.counter = None

    def beginjob(self,evt,env):
   self.array = []   # really just a list

    def beginjob(self,evt,env):
        self.counter = 0

    def event(self,evt,env):
        self.counter += 1

        # snippet code goes here
        thedata = evt.get(xtc.TypeId.Type.Id_SomeType, self.source )
        self.array.append( thedata.somevalue )

    def endjob(self,evt,env):
       print "Job done! Processed %d events. " % self.counter

       # place for plotting etc

BeamLine Data: EBeam

To read out energy, charge and position of the beam from the beamline data, use getEBeam(). It returns a class/structure that has the following members/fields:

Code Block
nonenone

def event(self,evt,env):

    ebeam = evt.getEBeam()
       # convert from python list to a numpy array
    try :
        beamChrg self.array = ebeamnp.fEbeamCharge
        beamEnrg = ebeam.fEbeamL3Energyarray( self.array )

       # beamPosX = ebeam.fEbeamLTUPosXplot graph
       plt.plot(self.array)

BeamLine Data: EBeam

To read out energy, charge and position of the beam from the beamline data, use getEBeam(). It returns a class/structure that has the following members/fields:

Code Block
none
none
titlegetEBeam

def event(self,evt,env):

    ebeam = evt.getEBeam() beamPosY = ebeam.fEbeamLTUPosY
        beamAngX = ebeam.fEbeamLTUAngX
        beamAngY = ebeam.fEbeamLTUAngY
    try :
   beamPkCr     beamChrg = ebeam.fEbeamPkCurrBC2fEbeamCharge
        printbeamEnrg = "ebeam: ", beamChrg, beamEnrg, beamPosX, beamPosY, beamAngX, beamAngY, beamPkCr
ebeam.fEbeamL3Energy
        beamPosX = ebeam.fEbeamLTUPosX
        beamPosY = ebeam.fEbeamLTUPosY
     except:
   beamAngX = ebeam.fEbeamLTUAngX
   print "No EBeam object found"

BeamLine Data: FEE Gas Detector

To read out the energy from the front end enclosure (FEE) gas detector, use getFeeGasDet(). This returns and array of 4 numbers:

Code Block
nonenone
  beamAngY = ebeam.fEbeamLTUAngY
    fee_energy_array    beamPkCr = evtebeam.getFeeGasDet()fEbeamPkCurrBC2
    gdENRC11 = fee_energy_array[0]
  print "ebeam: gdENRC12", = fee_energy_array[1]
    gdENRC21 = fee_energy_array[2]beamChrg, beamEnrg, beamPosX, beamPosY, beamAngX, beamAngY, beamPkCr
    gdENRC22except:
 = fee_energy_array[3]

    energy = (gdENRC21print -"No gdENRC22)EBeam /object 2
    # or use the first two that has a different gain:
    energy = (gdENRC11 - gdENRC12) / 2
found"

BeamLine Data:

...

FEE Gas Detector

To read out fit time and charge of the phase cavity, use getPhaseCavity() which returns a structure with the following fieldsthe energy from the front end enclosure (FEE) gas detector, use getFeeGasDet(). This returns and array of 4 numbers:

Code Block
none
none
titlegetFeeGasDet
    fee_energy_array pc = evt.getPhaseCavitygetFeeGasDet()
     try:
gdENRC11 = fee_energy_array[0]
    gdENRC12 = fee_energy_array[1]
    pcFitTime1gdENRC21 = pc.fFitTime1fee_energy_array[2]
    gdENRC22 = fee_energy_array[3]

   pcFitTime2 energy = pc.fFitTime2
         pcCharge1 = pc.fCharge1(gdENRC21 + gdENRC22) / 2.0
    # or use the first pcCharge2two = pc.fCharge2
   that has a different gain:
    energy = (gdENRC11 + gdENRC12) / 2.0

BeamLine Data: Phase Cavity

To read out fit time and charge of the phase cavity, use getPhaseCavity() which returns a structure with the following fields:

Code Block
none
none
titlegetPhaseCavity

     pc = evt.getPhaseCavity()
     tryprint "PhaseCavity: ", pcFitTime1,  pcFitTime2, pcCharge1, pcCharge2
      except :
         printpcFitTime1 "No Phase Cavity object found"

Encoder data (delay scanner)

Code Block
nonenone

def event(self,evt,env):
    try:= pc.fFitTime1
         pcFitTime2 = pc.fFitTime2
        encoder pcCharge1 = evt.get(xtc.TypeId.Type.Id_EncoderData, self.enc_source )
pc.fCharge1
         encoder_valuepcCharge2 = encoderpc.value()fCharge2
    except:
      print "PhaseCavity: print "No, encoderpcFitTime1, found inpcFitTime2, thispcCharge1, event"pcCharge2
        return

You could combine it with phase cavity time, and compute a time delay from it, for example (I don't know the origin of these parameters!):

Code Block
nonenone
except :
    # Encoder Parameters to convert toprint picoseconds
"No Phase Cavity  delay_a = -80.0e-6;object found"

Event code

Code Block
none
none
titleEnvData

def event(self, evt, env):
    delay_bevrdata = 0.52168;
evt.getEvrData("NoDetector-0|Evr-0")
    
 delay_c = 299792458;
 for i in delay_0 = 0;
range (evrdata.numFifoEvents()):
    delay_time = (delay_a * encoder_value + delay_b)*1.e-3 / delay_c) 
    delay_time = 2 * delay_time / 1.0e-12 + delay_0 + pcFitTime1

Time data

The time of the event can be obtained within the event function:

...


def event ( self, evt, env ) :
    event_time = evt.getTime().seconds() + 1.0e-9*evt.getTime().nanoseconds() )
print "Event code: ", evrdata.fifoEvent(i).EventCode

In the example above, the address of the EvrData object is given as "NoDetector-0|Evr-0". The address may be different in other cases, so make sure you have the correct address. If you don't know what it is, you can use 'pyxtcreader -vv <xtcfile> | less' to browse your xtcfile and look for it. Look for a lines with 'contains=EvrConfig_V' or 'contains=EvrData_V'. The address will be found on the same line in 'src=DetInfo(<address>)'

Encoder data (delay scanner)

Code Block
none
none
titleEncoderData

def event(self,evt,env):
    try:
        encoder = evt.get(xtc.TypeId.Type.Id_EncoderData, self.enc_source )
        encoder_value = encoder.value()
    except

IPIMB diode data

This is data from sets of 4 diodes around the beam line (Intensity Position, Intensity Monitoring Boards)
that measures the beam intensity in four spots, from which we can also deduce the position of the beam.

Currently there are two data structures that holds data from the same type of devices. Depending on DAQ
configuration, they are either DetInfo type or BldInfo type. Here are examples for extracting both types
in the user module event function:

Code Block
nonenone
titleDetInfo

def event(self, evt, env):
    # raw data
    ipmRaw = evt.get(xtc.TypeId.Type.Id_IpimbData, source )
    try:
        chprint = [ipmRaw.channel0(),
    "No encoder found in this event"
          ipmRaw.channel1(),
   return

You could combine it with phase cavity time, and compute a time delay from it, for example (I don't know the origin of these parameters!):

Code Block
none
none

    # Encoder Parameters to convert   ipmRaw.channel2(),to picoseconds
    delay_a = -80.0e-6;
    delay_b = 0.52168;
  ipmRaw.channel3() ]
 delay_c = 299792458;
    delay_0         = 0;

    delay_time = (delay_a * chencoder_voltvalue = [ipmRaw.channel0Volts(),
   + delay_b)*1.e-3 / delay_c) 
    delay_time = 2 * delay_time / 1.0e-12 + delay_0 + pcFitTime1

Time data

The time of the event can be obtained within the event function:

Code Block
none
none
titlegetTime

def event ipmRaw.channel1Volts() self,
 evt, env ) :
    event_time = evt.getTime().seconds() + 1.0e-9*evt.getTime().nanoseconds() )

IPIMB diode data

This is data from sets of 4 diodes around the beam line (Intensity Position, Intensity Monitoring Boards)
that measures the beam intensity in four spots, from which we can also deduce the position of the beam.

Currently there are two data structures that holds data from the same type of devices. Depending on DAQ
configuration, they are either DetInfo type or BldInfo type. Here are examples for extracting both types
in the user module event function:

Code Block
none
none
titleDetInfo

def event(self, evt, env):
    # raw data
    ipmRaw = evt.get(xtc.TypeId.Type.Id_IpimbData, source )
    try          ipmRaw.channel2Volts(),
                   ipmRaw.channel3Volts() ]
    except:
        pass

    # feature-extracted data
    ipmFex = evt.get(xtc.TypeId.Type.Id_IpmFex, source )
    try:
         # array of 4 numbers
         fex_channel = ipmFex.channel 

         # scalar values
         fex_sum = ipmFex.sum 
         fex_xpos = ipmFex.xpos
         fex_ypos = ipmFex.ypos

     except:
         pass

Code Block
nonenone
titleBldInfo

def event(self, evt, env):
ch = [ipmRaw.channel0(),
      ipm = evt.getSharedIpimbValue("HFX-DG3-IMB-02")
    # or equivalently: ipmRaw.channel1(),
    # ipm = evt.get(xtc.TypeId.Type.Id_SharedIpimb, "HFX-DG3-IMB-02")
          ipmRaw.channel2(),
       try: 
      ipmRaw.channel3() ]
 ### Raw data ###
        # arrays of 4 numbers:
        ch_volt = [ipmipmRaw.ipimbData.channel0channel0Volts(),
              ipm.ipimbData.channel1(),
              ipm.ipimbData.channel2ipmRaw.channel1Volts(),
              ipm.ipimbData.channel3()]
        ch_volt = [ipm.ipimbData.channel0VoltsipmRaw.channel2Volts(),
                   ipmipmRaw.ipimbData.channel1Voltschannel3Volts(),]
    except:
        pass

    # feature-extracted data
    ipm.ipimbData.channel2Volts(),
  ipmFex = evt.get(xtc.TypeId.Type.Id_IpmFex, source )
    try:
         # array of  ipm.ipimbData.channel3Volts()]

4 numbers
         ### Feature-extracted data ###
fex_channel = ipmFex.channel 

         # arrayscalar of 4 numbers:
values
         fex_channelssum = ipmipmFex.ipmFexData.channelsum 
        
        # scalars:
        fex_sum = ipm.ipmFexData.sum 
        fex_xpos = ipmipmFex.ipmFexData.xpos
         fex_ypos = ipmipmFex.ipmFexData.ypos

     except:
         pass

Acqiris waveform data

This method can be used for any detector/device that has Acqiris waveform data. Edit the self.address field to get the detector of your choice.

Initialize class members:


Code Block
none
none
titleBldInfo

def event(self, evt, env):
Code Block
    def __init__ ( self ):
    ipm = evt.getSharedIpimbValue("HFX-DG3-IMB-02")
    # initializeor dataequivalently:
    # ipm   self.address =  "AmoITof-0|Acqiris-0"
= evt.get(xtc.TypeId.Type.Id_SharedIpimb, "HFX-DG3-IMB-02")
    try: 
        ### self.data = []Raw data ###
        # arrays of 4 numbers:
        self.counterch = 0

If you're curious to see any of the Acqiris configuration, e.g. how many channels do we have, you can inspect the AcqConfig object:

Code Block

[ipm.ipimbData.channel0(),
          def beginjob ( self, evt, env ) :
 ipm.ipimbData.channel1(),
           cfg = env.getConfig( _pdsdata.xtc.TypeId.Type.Id_AcqConfig, self.address )
 ipm.ipimbData.channel2(),
            self.num = cfgipm.ipimbData.nbrChannels()

The read the event waveform data (an array) and append it to the self.data list:

Code Block
channel3()]
    def event ( self, evt, env ) : ch_volt = [ipm.ipimbData.channel0Volts(),
        channel = 0
        acqData = evtipm.ipimbData.getAcqValue( self.address, channel, env)
channel1Volts(),
          if acqData :
       ipm.ipimbData.channel2Volts(),
     self.counter+=1
            wf = acqDataipm.ipimbData.waveformchannel3Volts()]

   #  returns a waveform array### of numpy.ndarray type.Feature-extracted data ###
        # array of  self.data.append(wf)

At the end of the job, take the average and plot it:

Code Block
4 numbers:
    def   endjob( self, env ) :

 fex_channels = ipm.ipmFexData.channel 
        
    data = np.array(self.data)  # thisscalars:
 is an array of shape (Nevents, nSamples)

     fex_sum = ipm.ipmFexData.sum 
    # take the mean offex_xpos all events for each sampling time= ipm.ipmFexData.xpos
        xsfex_ypos = np.mean(data, axis=0)ipm.ipmFexData.ypos

        plt.plot(xs)

except:
         plt.xlabel('Seconds')pass

Acqiris waveform data

This method can be used for any detector/device that has Acqiris waveform data. Edit the self.address field to get the detector of your choice.

Initialize class members:

Code Block
none
none
    def __init__ ( self plt.ylabel('Volts'):
        plt.show()

Which gives you a plot like this
Image Removed

Display images from princeton camera

When plotting with MatPlotLib, we don't need to set the limits of the histogram manually, thus we don't need to read the Princeton configuration for this. If we want to sum the image from several events, we must first define and initialize some variables:

# initialize data
        self.address =  "AmoITof-0|Acqiris-0"
        self.data = []
        self.counter = 0

If you're curious to see any of the Acqiris configuration, e.g. how many channels do we have, you can inspect the AcqConfig object:

Code Block
none
none

    def beginjob ( self, evt, env ) 
Code Block

   def __init__ ( self ):
        #cfg initialize data
        = env.getConfig( _pdsdata.xtc.TypeId.Type.Id_AcqConfig, self.address =  "SxrEndstation-0|Princeton-0")
        self.datanum = Nonecfg.nbrChannels()

In each event, we add the image array returned from the getPrincetonValue functionThe read the event waveform data (an array) and append it to the self.data list:

Code Block
none
none
    def event ( self, evt, env ) :
        channel = 0
       frame acqData = evt.getPrincetonValuegetAcqValue( self.address, channel, env)
        if frameacqData :
           # accumulate the data
 self.counter+=1
            wf if= selfacqData.datawaveform() is None :
# returns a waveform array           self.data = np.float_(frame.data())
           else :of numpy.ndarray type.
               self.data += frame.dataappend(wf)

At the end of the job, display/save the arraytake the average and plot it:

Code Block
none
none
    def endjob( self, env ) :

        plt.imshow( data = np.array(self.data/self.countpass, origin='lower')
        plt.colorbar()
        plt.show()  # this is an array of shape (Nevents, nSamples)

        # savetake the full image to a png filemean of all events for each sampling time
        plt.imsave(fname="pyana_princ_image.png",arr=self.xs = np.mean(data, originaxis='lower')

Note that imsave saves the image only, pixel by pixel. If you want a view of the figure itself, lower resolution, you can save it from the interactive window you get from plt.show().
Image Removed

CsPad data

Here's an example of getting CsPad data from an event:

Code Block
nonenone

def event(self,evt,env):
    quads = evt.getCsPadQuads(self.img_source, env0)

        plt.plot(xs)

        plt.xlabel('Seconds')
    if  not quads : plt.ylabel('Volts')
        print '*** cspad information is missing ***'
        return
        
    # dump information about quadrants
    print "Number of quadrants: %d" % len(quads)
    
    for q in quads:
        print "  Quadrant %d" % q.quad()plt.show()

Which gives you a plot like this
Image Added

Princeton camera image

When plotting with MatPlotLib, we don't need to set the limits of the histogram manually, thus we don't need to read the Princeton configuration for this. If we want to sum the image from several events, we must first define and initialize some variables:

Code Block
none
none

   def __init__ ( self ):
        print# "initialize data
   virtual_channel: %s" % q.virtual_channel()
  self.address =     print " "SxrEndstation-0|Princeton-0"
   lane:   %s" % self.data = None

In each event, we add the image array returned from the getPrincetonValue function:

Code Block
none
none
titlegetPrincetonValue
q.lane()
  def event ( self, evt, env print) ":

    tid: %s" % q.tid(frame = evt.getPrincetonValue( self.address, env)
        print "if frame :
       acq_count: %s" % q.acq_count()
     # accumulate the data
    print "    op_code: %s" %if q.op_code()self.data is None :
        print "    seq_count: %s" % q.seq_count() self.data = np.float_(frame.data())
        print "  else  ticks:
 %s" % q.ticks()
        print "    fiducials: %s" % q.fiducials()
        print "    frame_type: %s" % q.frame_type(self.data += frame.data()

At the end of the job, display/save the array:

Code Block

   def endjob( self, env ) :
        plt.imshow( self.data/self.countpass, origin='lower')
        print "plt.colorbar()
     sb_temp: %s" % map(q.sb_temp, range(4))plt.show()

        # save the full 
image to a png file
    # image data as 3-dimentional array
        data = q.data()

...

 plt.imsave(fname="pyana_princ_image.png",arr=self.data, origin='lower')

Note that imsave saves the image only, pixel by pixel. If you want a view of the figure itself, lower resolution, you can save it from the interactive window you get from plt.show().
Image Added

PnCCD image

Code Block
none
none
titlegetPnCcdValue
def beginjobevent(self,evt,env):
    configtry:
        frame = envevt.getConfiggetPnCcdValue(xtc.TypeId.Type.Id_CspadConfig, self.img_source self.source, env )
    if not config:
  image      print '*** cspad config object is missing ***'= frame.data()
        returnexcept:
        
    quads = range(4)
pass

Other image (FCCD*,Opal,PIM (TM6740), ... )

These all use the generic getFrameValue function:

Code Block
none
none
titlegetFrameValue

def event(self,evt,env):
    print try:
    print "Cspad configuration"
  frame = print "  N quadrantsevt.getFrameValue( self.source )
     : %d" % config.numQuadsimage = frame.data()
    print "  Quad mask     : %#x" % config.quadMask()except:
    print "   pass

FCCD (Fast CCD) image

The Fast CCD is read out as two 8-bit images, therefore you need this extra line to convert it to the right format.

Code Block
none
none
titlegetFrameValue

def event(self,evt,env):
    try:
        frame = evt.getFrameValue( self.source )
        image = frame.data()
    except:
        pass

    # convert to 16-bit integer
    image.dtype = np.uint16

CsPad data

Here's an example of getting CsPad data from an event:

Code Block
none
none
titlegetCsPadQuads

def event(self,evt,env):
    quads = evt.getCsPadQuads(self.img_source, env)
    if not quads :
        print '*** cspad information is missing ***'
        return
        
    # dump information about quadrants
    print "Number of quadrants: %d" % len(quads)
    
    for q in quads:
        print "  Quadrant %d" % q.quad()
        print "    virtual_channel: %s" % q.virtual_channel()
        print "    lane: %s" % q.lane()
        print "    tid: %s" % q.tid()
        print "    acq_count: %s" % q.acq_count()
        print "    op_code: %s" % q.op_code()
        print "    seq_count: %s" % q.seq_count()
        print "    ticks: %s" % q.ticks()
        print "    fiducials: %s" % q.fiducials()
        print "    frame_type: %s" % q.frame_type()
        print "    sb_temp: %s" % map(q.sb_temp, range(4))
            
        # image data as 3-dimentional array
        data = q.data()

So far so good. 'quads' is a list of CsPad Element objects, and not necessarily ordered in the expected way. So you'll need to use q.quad() to obtain the quad number.
q.data() gives you a 3D numpy array [row][col][sec]. Here sections will be ordered as expected, but be aware in case of missing sections, that you may need to check the
configuration object. You can get that from the env object, typically something you do in beginjob:

Code Block
none
none

def beginjob(self,evt,env):
    config = env.getConfig(xtc.TypeId.Type.Id_CspadConfig, self.img_source)
    if not config:
        print '*** cspad config object is missing ***'
        return        
    print "Cspad configuration"
    print "  N quadrants   : %d" % config.numQuads()
    print "  Quad mask     : %#x" % config.quadMask()
    print "  payloadSize   : %d" % config.payloadSize()
    print "  badAsicMask0  : %#x" % config.badAsicMask0()
    print "  badAsicMask1  : %#x" % config.badAsicMask1()
    print "  asicMask      : %#x" % config.asicMask()
    print "  numAsicsRead  : %d" % config.numAsicsRead()

   # get the indices of sections in use:
   qn = range(0,config.numQuads())               
   self.sections = map(config.sections, qn )        

If you want to draw the whole CsPad image, there's currently no pyana function that does this. Pyana only supplies the pixels in a numpy array, and the
exact location of each pixel depends on the conditions at the time of data collection. A simplified way of making the image can be seen in cspad_simple.py(newer version (cspad.py) available if you check out the XtcExplorer package).

CSPad pixel coordinates.

The CSPad detector image can be drawn by positioning the sections from the data array into a large image array. This is done in cspad_simple.py above. The positions are extracted from optical meterology measurements and additional calibrations. Alternatively one can find the coordinate of each individual pixel from a pixel map, based on the same optical metrology measurements. This is described in details here

Epics Process Variables and ControlConfig

EPICS data is different from DAQ event data. It stores the conditions and settings of the instruments, but values typically change more slowly than your
average shot-by-shot data, and EPICS data is typically updated only when it changes, or every second, or similar. It is not stored in the 'evt' (event) object,
but in the 'env' (environment) object. You typically would read it only at the beginning of each job or if your doing a scan, you'd read it in every calibration cycle:

Code Block
none
none
titleenv.epicsStore()

def begincalibcycle(self,evt,env):

    ## The returned value should be of the type epics.EpicsPvTime.
    pv = env.epicsStore().value( pv_name )
    if not pvpayloadSize   : %d" % config.payloadSize()
    print "  badAsicMask0  : %#x" % config.badAsicMask0()
    print "  badAsicMask1  : %#x" % config.badAsicMask1()
    print "  asicMask      : %#x" % config.asicMask()
    print "  numAsicsRead  : %d" % config.numAsicsRead()
    try:
        # older versions maylogging.warning('EPICS PV %s does not have all methodsexist', pv_name)
    else:
    print "  roiMask value = pv.value 
   : [%s]" % ', '.join([hex(config.roiMask(q)) for q in quads]) status = pv.status 
        print "  numAsicsStored: %s" % str(map(config.numAsicsStored, quads)alarm_severity = pv.severity 
Code Block
none
none
titleControlConfig

def begincalibcycle(self,evt,env):
    ctrl_config = env.getConfig(xtc.TypeId.Type.Id_ControlConfig)
    except:
    nControls = ctrl_config.npvControls()
  pass
  for  print "  sectionsic in range (0, nControls ):

       : %s"cpv % str(map(config.sections, quads))= ctrl_config.pvControl(ic)
    print
    name = cpv.name()
        value = cpv.value()