Ejemplo n.º 1
0
def bkgStripRipple(rplDir, rplBas, e0, i0, liveTime, det, verbose=False):
    """
    bkgStripRipple(rplDir, rplBas, e0, i0, liveTime, det, verbose=False)

    Strip the background from a ripple file, writing the output to a
    a file with -bks appended to the name.
    
    Parameters
    ----------
    rplDir: string (with path terminator)
        The directory containing the ripple file
    rplBas: string
        The base name of the ripple file
    e0: number
        Accelerating voltage (kV)
    i0: number
        Probe current (nA)
    liveTime: number
        Llve time per pixel (sec)
    det: DTSA-II detector
        The detector (used to get channel depth)
    verbose: Boolean (False)
        Flag to print progress (row and elapsed time)

    """
    start = time.time()
    rplPth = rplDir + rplBas
    rplFil = rplPth + ".rpl"
    a1 = rplPth + "-bks.rpl"
    a2 = rplPth + "-bks.raw"
    sRip = openRipple(rplFil, e0, i0, liveTime, det)
    cols = sRip.getColumns()
    rows = sRip.getRows()
    # print((cols, rows))
    depth = det.getChannelCount()
    res = ept.RippleFile(cols, rows, depth, ept.RippleFile.UNSIGNED , 4,
                         ept.RippleFile.BIG_ENDIAN, a1, a2)
    for x in range(cols):
        for y in range(rows):
            if (y==0):
                if(x>0):
                    now = time.time()
                    delta = (now-start)/60
                    msg = "Started row %d of %d. " % (x+1, cols)
                    msg += "This script required %.1f min so far" % (delta)
                    print(msg)
                    if(delta > 60):
                        delta = delta/60
                        msg = "...or %.3f hr" % delta
                        print(msg)
            sRip.setPosition(x,y)
            spc = dt2.wrap(sRip)
            spc = epq.SpectrumUtils.applyZeroPeakDiscriminator(spc)
            spc = epq.PeakStripping.Clayton1987.getStrippedSpectrum(spc)
            spc = epq.SpectrumUtils.getPositiveSpectrum(spc)
            res.seek(y, x) # think this was the problem...
            res.write(epq.SpectrumUtils.toIntArray(spc)[0:depth])
    res.close()
Ejemplo n.º 2
0
def anaMcNiCuKa(spc, det, stdBase, maxCh=1200):
  props=spc.getProperties()
  e0 = props.getNumericProperty(epq.SpectrumProperties.BeamEnergy)
  lt = props.getNumericProperty(epq.SpectrumProperties.LiveTime)
  pc = props.getNumericProperty(epq.SpectrumProperties.FaradayBegin)
  wkDst = props.getNumericProperty(epq.SpectrumProperties.WorkingDistance)
  spc = jmg.cropSpec(spc, end=maxCh)
  unSpc = jmg.updateCommonSpecProps(spc, det, liveTime=lt, probeCur=pc, e0=e0, wrkDist=wkDst)
  dt2.display(unSpc)
  
  # define the transitions I want to measure
  tsNiKa = epq.XRayTransitionSet(epq.Element.Ni, epq.XRayTransitionSet.K_FAMILY)
  tsCuKa = epq.XRayTransitionSet(epq.Element.Cu, epq.XRayTransitionSet.K_FAMILY)
  trs = [tsNiKa, tsCuKa]
  relStd = "/%gkV/" % (e0)
  stdDir = stdBase + relStd
  niFile = stdDir + "Ni-sim.msa"
  cuFile = stdDir + "Cu-sim.msa"

  spc = dt2.wrap(ept.SpectrumFile.open(niFile)[0])
  props=spc.getProperties()
  e0 = props.getNumericProperty(epq.SpectrumProperties.BeamEnergy)
  lt = props.getNumericProperty(epq.SpectrumProperties.LiveTime)
  pc = props.getNumericProperty(epq.SpectrumProperties.FaradayBegin)
  wkDst = props.getNumericWithDefault(epq.SpectrumProperties.WorkingDistance, wkDst)
  spc = jmg.cropSpec(spc, end=maxCh)
  niSpc = jmg.updateCommonSpecProps(spc, det, liveTime=lt, probeCur=pc, e0=e0, wrkDist=wkDst)
  dt2.display(niSpc)

  spc = dt2.wrap(ept.SpectrumFile.open(cuFile)[0])
  props=spc.getProperties()
  e0 = props.getNumericProperty(epq.SpectrumProperties.BeamEnergy)
  lt = props.getNumericProperty(epq.SpectrumProperties.LiveTime)
  pc = props.getNumericProperty(epq.SpectrumProperties.FaradayBegin)
  wkDst = props.getNumericWithDefault(epq.SpectrumProperties.WorkingDistance, wkDst)
  spc = jmg.cropSpec(spc, end=maxCh)
  cuSpc = jmg.updateCommonSpecProps(spc, det, liveTime=lt, probeCur=pc, e0=e0, wrkDist=wkDst)
  dt2.display(cuSpc)
  niStd = {"El":dt2.element("Ni"), "Spc":niSpc}
  cuStd = {"El":dt2.element("Cu"), "Spc":cuSpc}
  stds  = [niStd, cuStd]
  theKR = jmg.compKRs(unSpc, stds, trs, det, e0)
  krNiCalc = theKR[0]
  krCuCalc = theKR[1]
  return [krNiCalc, krCuCalc]
Ejemplo n.º 3
0
def simSonoraSpc(tAl2O3, e0, det, wkDst=5, lt=100, pc=1, nTraj=1000, xtraParams={}):
    """simSonoraSpc(tAl2O3, e0, det, wkDst=5, lt=100, pc=1, nTraj=1000, xtraParams={})
    Simulate a spectrum from tAl2O3 nm of Al2O3 on Al recoreed at
    e0 kV using the DTSA detector det and a wkDst mm working distance for
    lt sec with a probe current of pc nA. Compute nTraj trajectories."""
    tAl = 100 # um
    al2o3 = dt2.material("Al2O3",density=3.95)
    al  = dt2.material("Al", density=2.70)
    lAl2O3 = [al2o3, tAl2O3*1.0e-9]
    lAl = [al, tAl*1.0e-6]
    lay = [lAl2O3, lAl]
    sNam = "%g-nm-Al2O3-on-Al-%g-kV" % (tAl2O3, e0)
    spc = dt2.wrap(mc3.multiFilm(lay, det, e0, True, nTraj, lt*pc, True, True, xtraParams))
    props=spc.getProperties()
    props.setTextProperty(epq.SpectrumProperties.SpectrumDisplayName, sNam)
    props.setNumericProperty(epq.SpectrumProperties.LiveTime, lt)
    props.setNumericProperty(epq.SpectrumProperties.FaradayBegin, pc)
    props.setNumericProperty(epq.SpectrumProperties.BeamEnergy, e0)
    props.setNumericProperty(epq.SpectrumProperties.WorkingDistance, wkDst)
    return(spc)
Ejemplo n.º 4
0
def simNiCuPetSpc(tNi, tCu, e0, det, wkDst=17, lt=100, pc=1, nTraj=1000):
  """simNiCuPetSpc(tNi, tCu, e0, det, wkDst=17, lt=100, pc=1, nTraj=1000)
  Simulate a spectrum from tNi nm of Ni on tCu nm of Cu on PET recoreded at
  e0 kV using the DTSA detector det and a wkDst mm working distance for
  lt sec with a probe current of pc nA. Compute nTraj trajectories."""
  tPET = 76 # um
  pet = dt2.material("C10H8O4",density=1.37)
  cu  = dt2.material("Cu", density=8.96)
  ni  = dt2.material("Ni", density=8.90)
  lNi   = [ni,  tNi*1.0e-9]
  lCu   = [cu,  tCu*1.0e-9]
  lPET  = [pet, tPET*1.0e-6]
  lay   = [lNi, lCu, lPET]
  sNam  = "%g-nm-Ni-%g-nm-Cu-on-PET-%g-kV" % (tNi, tCu, e0)
  spc = dt2.wrap(mc3.multiFilm(lay, det, e0, True, nTraj, lt*pc, True, True))
  props=spc.getProperties()
  props.setTextProperty(epq.SpectrumProperties.SpectrumDisplayName, sNam)
  props.setNumericProperty(epq.SpectrumProperties.LiveTime, lt)
  props.setNumericProperty(epq.SpectrumProperties.FaradayBegin, pc)
  props.setNumericProperty(epq.SpectrumProperties.BeamEnergy, e0)
  props.setNumericProperty(epq.SpectrumProperties.WorkingDistance, wkDst)
  return(spc)
Ejemplo n.º 5
0
def buildVectors(stds, path=None, strip=(), det=None):
    """buildVectors(stds, path=None,strip=())
	Construct a set of Schamber-style fast quant vectors
	stds = { "Fe" : "Fe std", "Cr": "Cr std", "Cd":s101 ... }
	path = "/home/nicholas/standards" or similar (None -> defaultPath)
	strip= ("C", "O", ...) a list of elements to strip (must also be in stds)"""
    procStds = {}
    strip = [element(elm) for elm in strip]
    e0 = None
    for elm, std in stds.iteritems():
        if isinstance(std, str):
            path = (path if path else defaultVecPath)
            std = readSpectrum("%s/%s" % (path, std))
        elif isinstance(std, dt2.ScriptableSpectrum):
            std = std.wrapped
            det = (det if det else std.getProperties().detector)
        procStds[dt2.element(elm)] = std
        e0 = (e0 if e0 else epq.ToSI.keV(dt2.wrap(std).beamEnergy()))
    sv = fq.SchamberVectors(det, e0)
    for elm, std in procStds.iteritems():
        sv.addStandard(elm, std, elm in strip)
    return sv.getVectorSet()
Ejemplo n.º 6
0
def base(det, e0, withPoisson, nTraj, dose, sf, bf, name, buildSample, buildParams, xtraParams):
   """base(det, e0, withPoisson, nTraj, dose, sf, bf, name, buildSample, buildParams) represents \
   a generic mechanism for Monte Carlo simulation of x-ray spectra.  The argument buildSample \
   is a method buildSample(monte,origin,buildParams) taking an instance of MonteCarloSS, the \
   position of the origin and a dictionary of build parameters.  This method should construct \
   the sample geometry.  The other arguments are the detector, the beam energy (keV), whether \
   to add Poisson noise, the number of electron trajectories to simulate, whether to simulate \
   characteristic secondary fluorescence and Bremsstrahlung secondary fluorescence, the name \
   to assign to the resulting spectrum."""
   if e0 < 0.1:
       raise "The beam energy must be larger than 0.1 keV."
   if nTraj < 1:
       raise "The number of electron trajectories must be larger than or equal to 1."
   if dose <= 0.0:
       raise "The electron dose must be larger than zero."
   name = name.strip()
   if xtraParams.has_key("Postfix"):
      name = "%s - %s" % (name, xtraParams["Postfix"])
   # Place the sample at the optimal location for the detector
   origin = epq.SpectrumUtils.getSamplePosition(det.getProperties())
   # Create a simulator and initialize it
   monte = nm.MonteCarloSS()
   if xtraParams.has_key("Gun"):
      gun = xtraParams["Gun"]
      gun.setCenter([0.0, 0.0, -0.099])
      monte.setElectronGun(gun)
   if xtraParams.has_key("PosX"):
      beamX  = xtraParams["PosX"]
      beamY  = xtraParams["PosY"]
      beamZ  = xtraParams["PosZ"]
      beamNM = xtraParams["nmSize"]
      beam=nm.GaussianBeam(beamNM*1.0e-9)
      beam.setCenter([beamX, beamY, beamZ]) 
      monte.setElectronGun(beam)
   chamber = monte.getChamber()
   if xtraParams.has_key("VP"):
       pathLength, gas = xtraParams["VP"]
       dim = 0.5 * nm.MonteCarloSS.ChamberRadius;
       dims = epu.Math2.plus(epu.Math2.v3(dim, dim, dim), epu.Math2.z3(2.0 * pathLength))
       pt = epu.Math2.plus(origin, epu.Math2.z3(0.5 * dim));
       shape = nm.MultiPlaneShape.createBlock(dims, pt, 0.0, 0.0, 0.0);
       msm = nm.BasicMaterialModel(gas);
       chamber = monte.addSubRegion(chamber, msm, shape);
   monte.setBeamEnergy(epq.ToSI.keV(e0))
   buildSample(monte, chamber, origin, buildParams)
   # Add event listeners to model characteristic radiation
   chXR = nm3.CharacteristicXRayGeneration3.create(monte)
   xrel = nm3.XRayTransport3.create(monte, det, chXR)
   brXR = nm3.BremsstrahlungXRayGeneration3.create(monte)
   brem = nm3.XRayTransport3.create(monte, det, brXR)
   chSF, brSF, bremFluor, charFluor  = None, None, None, None
   hasCharAcc = xtraParams.has_key('Characteristic Accumulator') and xtraParams['Characteristic Accumulator']
   if sf or hasCharAcc or xtraParams.has_key("Compton"):
      charFluor = nm3.FluorescenceXRayGeneration3.create(monte, chXR)
      if xtraParams.has_key("Compton"):
         charFluor.setIncludeCompton(True)
      chSF = nm3.XRayTransport3.create(monte, det, charFluor)
   hasBremFluorAcc = xtraParams.has_key('Brem Fluor Accumulator') and xtraParams['Brem Fluor Accumulator']
   if bf or hasBremFluorAcc:    
      bremFluor = nm3.FluorescenceXRayGeneration3.create(monte, brXR)       
      brSF = nm3.XRayTransport3.create(monte, det, bremFluor)
   hasTrans = xtraParams.has_key("Transitions")
   if hasTrans:
       if xtraParams.has_key("Emission Images"):
           eis = []
           dim = xtraParams["Emission Images"]
           for xrt in xtraParams["Transitions"]:
               size = xtraParams["Emission Size"]
               ei = nm3.EmissionImage3(size, size, xrt)
               xrel.addXRayListener(ei)
               if chSF:
                   chSF.addXRayListener(ei)
               if brSF:
                   brSF.addXRayListener(ei)
               ei.setXRange(origin[0] - 0.5 * dim, origin[0] + 0.5 * dim)
               ei.setYRange(origin[2] - 0.1 * dim, origin[2] + 0.9 * dim)
               eis.append(ei)
       if hasCharAcc:
           cxra = nm3.XRayAccumulator3(xtraParams["Transitions"], "Characteristic", dose * 1.0e-9)
           xrel.addXRayListener(cxra)
       hasCharFluorAcc = xtraParams.has_key('Char Fluor Accumulator') and xtraParams['Char Fluor Accumulator']
       if hasCharFluorAcc or chSF or sf:
           cfxra = nm3.XRayAccumulator3(xtraParams["Transitions"], "Characteristic Fluorescence", dose * 1.0e-9)
           chSF.addXRayListener(cfxra) 
       if hasBremFluorAcc or brSF or bf:
           bfxra = nm3.XRayAccumulator3(xtraParams["Transitions"], "Continuum Fluorescence", dose * 1.0e-9)
           brSF.addXRayListener(bfxra)
   contImgs = []
   if xtraParams.has_key('Continuum Images'):
       dim = xtraParams['Continuum Images']
       size = xtraParams['Continuum Size']
       energies = xtraParams['Continuum Energies']
       for eMin, eMax in energies:
           ci3 = nm3.ContinuumImage3(size, size, epq.ToSI.keV(eMin), epq.ToSI.keV(eMax))
           ci3.setXRange(origin[0] - 0.5 * dim, origin[0] + 0.5 * dim)
           ci3.setYRange(origin[2] - 0.1 * dim, origin[2] + 0.9 * dim)
           brem.addXRayListener(ci3)
           contImgs.append(ci3)
   doPRZ = xtraParams.has_key("PhiRhoZ")
   if doPRZ:
      depth = xtraParams["PhiRhoZ"]
      prz = nm3.PhiRhoZ3(xrel, origin[2] - 0.1 * depth, origin[2] + 1.1 * depth, 110)
      xrel.addXRayListener(prz)
   voxelated = xtraParams.has_key('Voxelated')
   vox = None
   if voxelated:
      dim = xtraParams['Voxelated']
      gen = xtraParams['GeneratedV']
      size = xtraParams['SizeV']
      vox = nm3.VoxelatedDetector((origin[0], origin[1], origin[2] - 0.1 * size), (size, size, size), (dim, dim, dim), gen)
      xrel.addXRayListener(vox)
   doTraj = xtraParams.has_key('Trajectories')
   if doTraj:
      dim = xtraParams['Trajectories']
      size = xtraParams['TrajSize']
      ti = nm.TrajectoryImage(size, size, dim)
      ti.setXRange(origin[0] - 0.5 * dim, origin[0] + 0.5 * dim)
      ti.setYRange(origin[2] - 0.1 * dim, origin[2] + 0.9 * dim)
      monte.addActionListener(ti)
   defOut = (dtsa2.DefaultOutput if dtsa2.DefaultOutput else dtsa2.reportPath())
   do = ("%s\\%s" % (xtraParams["Output"], dtsa2.normalizeFilename(name)) if xtraParams.has_key("Output") else "%s/%s" % (defOut, dtsa2.normalizeFilename(name)))
   do = do.replace("\\", "/")
   fdo = jio.File(do)
   fdo.mkdirs()
   doVRML = xtraParams.has_key('VRML')
   vrmlWr = None
   if doVRML:
      vrmlFile = jio.File.createTempFile("vrml", ".wrl", fdo)
      print "VRML in " + str(vrmlFile)
      vrmlWr = jio.FileWriter(vrmlFile)
      vrml = nm.TrajectoryVRML(monte, vrmlWr)
      vrml.setDisplayBackscatter(False)
      vrml.setDisplayXRayEvent(True)
      vrml.setMaxTrajectories(xtraParams['VRML'])
      vrml.setTrajectoryWidth(1.0e-9)
      vrml.setMaxRadius(1.0)
      vrml.setEmissive(True)
      vrml.addView("Y-Axis", epu.Math2.plus(origin, (0.0, 5.0e-6, 0.0)), origin)
      vrml.addView("Gun", epu.Math2.plus(origin, (0.0, 0.0, -5.0e-6)), origin)
      vrml.addView("X-Axis", epu.Math2.plus(origin, (-5.0e-6, 0.0, 0.0)), origin)
      vrml.renderSample()
      monte.addActionListener(vrml)
   scatter = None
   if xtraParams.has_key("Scatter"):
      scatter = nm.ScatterStats(epq.ToSI.eV(50.0))
      monte.addActionListener(scatter)
   # Reset the detector and run the electrons
   det.reset()
   monte.runMultipleTrajectories(nTraj)
   # Get the spectrum and assign properties
   spec = det.getSpectrum((dose * 1.0e-9) / (nTraj * epq.PhysicalConstants.ElectronCharge))
   props = spec.getProperties()
   props.setNumericProperty(epq.SpectrumProperties.LiveTime, dose)
   props.setNumericProperty(epq.SpectrumProperties.FaradayBegin, 1.0)
   props.setNumericProperty(epq.SpectrumProperties.BeamEnergy, e0)
   epq.SpectrumUtils.rename(spec, name)
   if withPoisson:
      spec = epq.SpectrumUtils.addNoiseToSpectrum(spec, 1.0)
   printAcc = xtraParams.has_key('Print Accumulators') and xtraParams['Print Accumulators']
   if printAcc:
      sw0 = jio.StringWriter()
      sw = jio.PrintWriter(sw0)
   if hasTrans or scatter:
      pw = None
      if hasCharAcc or (hasBremFluorAcc and bf) or (hasCharFluorAcc and sf) or scatter:
         jio.File(do).mkdirs()
         pw = jio.PrintWriter("%s/Intensity.csv" % do)
         pw.println(name)
      if hasCharAcc:
         pw.println("Characteristic") 
         cxra.dump(pw)
         if printAcc:
             sw.println("Characteristic") 
             cxra.dump(sw)
      if hasBremFluorAcc and brSF and bf:
         pw.println("Bremsstrahlung Fluorescence")
         bfxra.dump(pw)
         if printAcc:
             sw.println("Bremsstrahlung Fluorescence") 
             bfxra.dump(sw)
      if hasCharFluorAcc and chSF and sf:
         pw.println("Characteristic Fluorescence")
         cfxra.dump(pw)
         if printAcc:
             sw.println("Characteristic Fluorescence")
             cfxra.dump(sw)
      if printAcc:
          print sw0.toString()
          sw.close()
          sw0.close()
      if scatter:
         scatter.header(pw)
         scatter.dump(pw)
      if pw:
         pw.close()
      imgs = []
      if xtraParams.has_key("Emission Images"):
         nm3.EmissionImageBase.scaleEmissionImages(eis)
         print eis
         print do          
         nm3.EmissionImage3.dumpToFiles(eis, do)
         print u"Writing emission images to %s" % do
         imgs.extend(eis)
      if xtraParams.has_key("Continuum Images"):
         imgs.extend(contImgs)      
         nm3.EmissionImageBase.scaleEmissionImages(imgs)
         print contImgs
         print do          
         nm3.ContinuumImage3.dumpToFiles(contImgs, do)
         print u"Writing continuum images to %s" % do
   if doPRZ:
       jio.File(do).mkdirs()
       pw = jio.PrintWriter(u"%s/PhiRhoZ.csv" % do)
       prz.write(pw)
       pw.close()
       print u"Writing emission images to %s" % do
   if doTraj:
      ti.dumpToFile(do)
      print u"Writing trajectory images to %s" % do
   if vrmlWr:
       vrmlWr.close()
   if vox:
      jio.File(do).mkdirs()
      objs = list(vox.getAccumulatorObjects())
      xx = {}
      for obj in objs:
          iio.write(vox.createXZSum(400, obj), "png", jio.File(do, "Voxelated[XZ,Sum][%s].png" % obj))
          iio.write(vox.createXYSum(400, obj), "png", jio.File(do, "Voxelated[XY,Sum][%s].png" % obj))
          iio.write(vox.createXZView(400, obj), "png", jio.File(do, "Voxelated[XZ, Max][%s].png" % obj))
          iio.write(vox.createXYView(400, obj), "png", jio.File(do, "Voxelated[XY, Max][%s].png" % obj))
          vox.writeXZPlanar(400, obj, jio.File(do, "Voxilated[XZ,planar,%s].tif" % obj))
          vox.writeXYPlanar(400, obj, jio.File(do, "Voxilated[XY,planar,%s].tif" % obj))
          for f in (0.1, 0.5, 0.8, 0.9):
              iio.write(vox.createXZFraction(400, obj, f), "png", jio.File(do, "Voxelated[XZ,f=%g][%s].png" % (f, obj)))
          xx[obj] = vox.createRadialCDF(origin, obj)
      hdr = "Radius"
      for obj in objs:
          hdr = "%s\t%s" % (hdr, obj)
      print hdr
      first = xx[objs[0]]
      for i, (d, f) in enumerate(first):
          ln = "%g" % d
          for obj in objs:
              rcdf = xx[obj][i]
              ln = "%s\t%g" % (ln, rcdf[1])
          print ln
   #if bremFluor:
       #print "Stats[Scale] = %s" % bremFluor.getScaleStats()         
   return dtsa2.wrap(spec)