コード例 #1
0
def main():
    filename = sys.argv[1]
    with open(filename) as f:
        for _ in range(2):
            next(f)
        data = [map(float, line.split()) for line in f]
    result = PyChooch.calc(data, "Se", "K")
    print(result)
コード例 #2
0
    def doChooch(self, elt, edge, scan_directory, archive_directory, prefix):
        """
        Descript. :
        """
        symbol = "_".join((elt, edge))

        scan_file_prefix = os.path.join(scan_directory, prefix) 
        archive_file_prefix = os.path.join(archive_directory, prefix)

        if os.path.exists(scan_file_prefix + ".raw"):
            i = 1
            while os.path.exists(scan_file_prefix + ".raw"):
                  i = i + 1
            scan_file_prefix += "_%d" % i
            archive_file_prefix += "_%d" % i

        scan_file_raw_filename = os.path.extsep.join((scan_file_prefix, "raw"))
        archive_file_raw_filename = os.path.extsep.join((archive_file_prefix, "raw"))
        scan_file_efs_filename = os.path.extsep.join((scan_file_prefix, "efs"))
        archive_file_efs_filename = os.path.extsep.join((archive_file_prefix, "efs"))
        scan_file_png_filename = os.path.extsep.join((scan_file_prefix, "png"))
        archive_file_png_filename = os.path.extsep.join((archive_file_prefix, "png"))

        try:
            if not os.path.exists(scan_directory):
                os.makedirs(scan_directory)
            if not os.path.exists(archive_directory):
                os.makedirs(archive_directory)
        except:
            logging.getLogger("HWR").exception("EMBLEnergyScan: could not create energy scan result directory.")
            self.store_energy_scan()
            self.emit("energyScanFailed", ())
            return

        try:
            scan_file_raw = open(scan_file_raw_filename, "w")
            archive_file_raw = open(archive_file_raw_filename, "w")
        except:
            logging.getLogger("HWR").exception("EMBLEnergyScan: could not create energy scan result raw file")
            self.store_energy_scan()
            self.emit("energyScanFailed", ())
            return
        else:
            scanData = []
            for i in range(len(self.scanData)):
                x = float(self.scanData[i][0])
                x = x < 1000 and x * 1000.0 or x 
                y = float(self.scanData[i][1])
                scanData.append((x, y))
                scan_file_raw.write("%f,%f\r\n" % (x, y))
                archive_file_raw.write("%f,%f\r\n" % (x, y)) 
            scan_file_raw.close()
            archive_file_raw.close()
            self.scanInfo["scanFileFullPath"] = str(scan_file_raw_filename)

        pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = \
             PyChooch.calc(scanData, elt, edge, scan_file_efs_filename)

        rm = (pk + 30) / 1000.0
        pk = pk / 1000.0
        savpk = pk
        ip = ip / 1000.0
        comm = ""
        logging.getLogger("HWR").info("EMBLEnergyScan : Results th. Edge %s ; chooch results are pk=%f, ip=%f, rm=%f" %\
               (self.thEdgeThreshold, pk, ip, rm))

        """if math.fabs(self.thEdge - ip) > self.thEdgeThreshold:
          pk = 0
          ip = 0
          rm = self.thEdge + 0.03
          comm = 'Calculated peak (%f) is more that 10eV away from the theoretical value (%f). Please check your scan' % (savpk, self.thEdge)
   
          logging.getLogger("HWR").warning('EMBLEnergyScan: calculated peak (%f) is more that 20eV %s the theoretical value (%f). Please check your scan and choose the energies manually' % (savpk, (self.thEdge - ip) > 0.02 and "below" or "above", self.thEdge))"""

        try:
            fi = open(scan_file_efs_filename)
            fo = open(archive_file_efs_filename, "w")
        except:
            self.store_energy_scan()
            self.emit("energyScanFailed", ())
            return
        else:
            fo.write(fi.read())
            fi.close()
            fo.close()

        self.scanInfo["peakEnergy"] = pk
        self.scanInfo["inflectionEnergy"] = ip
        self.scanInfo["remoteEnergy"] = rm
        self.scanInfo["peakFPrime"] = fpPeak
        self.scanInfo["peakFDoublePrime"] = fppPeak
        self.scanInfo["inflectionFPrime"] = fpInfl
        self.scanInfo["inflectionFDoublePrime"] = fppInfl
        self.scanInfo["comments"] = comm

        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = zip(*chooch_graph_data)
        chooch_graph_x = list(chooch_graph_x)
        for i in range(len(chooch_graph_x)):
            chooch_graph_x[i] = chooch_graph_x[i] / 1000.0

        #logging.getLogger("HWR").info("EMBLEnergyScan: Saving png" )
        # prepare to save png files
        title = "%s  %s  %s\n%.4f  %.2f  %.2f\n%.4f  %.2f  %.2f" % \
              ("energy", "f'", "f''", pk, fpPeak, fppPeak, ip, fpInfl, fppInfl) 
        fig = Figure(figsize = (15, 11))
        ax = fig.add_subplot(211)
        ax.set_title("%s\n%s" % (scan_file_efs_filename, title))
        ax.grid(True)
        ax.plot(*(zip(*scanData)), **{"color": 'black'})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2 = fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color = 'blue'))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color = 'red'))
        canvas = FigureCanvasAgg(fig)

        self.scanInfo["jpegChoochFileFullPath"] = str(archive_file_png_filename)
        try:
            logging.getLogger("HWR").info("Rendering energy scan and Chooch graphs to PNG file : %s", scan_file_png_filename)
            canvas.print_figure(scan_file_png_filename, dpi = 80)
        except:
            logging.getLogger("HWR").exception("could not print figure")
        try:
            logging.getLogger("HWR").info("Saving energy scan to archive directory for ISPyB : %s", archive_file_png_filename)
            canvas.print_figure(archive_file_png_filename, dpi = 80)
        except:
            logging.getLogger("HWR").exception("could not save figure")

        self.store_energy_scan()

        logging.getLogger("HWR").info("<chooch> returning" )
        self.emit('choochFinished', (pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, 
                 rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title))
        return pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, \
                 chooch_graph_y1, chooch_graph_y2, title
コード例 #3
0
    def doChooch(self, scanObject, elt, edge, scanArchiveFilePrefix,
                 scanFilePrefix):
        symbol = "_".join((elt, edge))
        scanArchiveFilePrefix = "_".join((scanArchiveFilePrefix, symbol))

        logging.getLogger("HWR").exception("running chooch in mxcube (%s)" %
                                           scanArchiveFilePrefix)

        i = 1
        while os.path.isfile(
                os.path.extsep.join((scanArchiveFilePrefix + str(i), "raw"))):
            i = i + 1

        scanArchiveFilePrefix = scanArchiveFilePrefix + str(i)
        archiveRawScanFile = os.path.extsep.join(
            (scanArchiveFilePrefix, "raw"))
        rawScanFile = os.path.extsep.join((scanFilePrefix, "raw"))
        scanFile = os.path.extsep.join((scanFilePrefix, "efs"))

        if not os.path.exists(os.path.dirname(scanArchiveFilePrefix)):
            os.makedirs(os.path.dirname(scanArchiveFilePrefix))

        try:
            f = open(rawScanFile, "w")
            pyarch_f = open(archiveRawScanFile, "w")
        except BaseException:
            logging.getLogger("HWR").exception(
                "could not create raw scan files")
            self.storeEnergyScan()
            self.emit("energyScanFailed", ())
            return
        else:
            scanData = []

            if scanObject is None:
                raw_data_file = os.path.join(os.path.dirname(scanFilePrefix),
                                             "data.raw")
                try:
                    raw_file = open(raw_data_file, "r")
                except BaseException:
                    self.storeEnergyScan()
                    self.emit("energyScanFailed", ())
                    return

                for line in raw_file.readlines()[2:]:
                    (x, y) = line.split("\t")
                    x = float(x.strip())
                    y = float(y.strip())
                    x = x < 1000 and x * 1000.0 or x
                    scanData.append((x, y))
                    f.write("%f,%f\r\n" % (x, y))
                    pyarch_f.write("%f,%f\r\n" % (x, y))
            else:
                for i in range(len(scanObject.x)):
                    x = float(scanObject.x[i])
                    x = x < 1000 and x * 1000.0 or x
                    y = float(scanObject.y[i])
                    scanData.append((x, y))
                    f.write("%f,%f\r\n" % (x, y))
                    pyarch_f.write("%f,%f\r\n" % (x, y))

            f.close()
            pyarch_f.close()
            self.scanInfo["scanFileFullPath"] = str(archiveRawScanFile)

        logging.getLogger("HWR").info(
            "th. Edge %s ; calculating results with chooch " % (self.thEdge))
        pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = PyChooch.calc(
            scanData, elt, edge, scanFile)
        rm = (pk + 30) / 1000.0
        pk = pk / 1000.0
        savpk = pk
        ip = ip / 1000.0
        comm = ""
        logging.getLogger("HWR").info(
            "th. Edge %s ; chooch results are pk=%f, ip=%f, rm=%f" %
            (self.thEdge, pk, ip, rm))

        if math.fabs(self.thEdge - ip) > self.thEdgeThreshold:
            pk = 0
            ip = 0
            rm = self.thEdge + 0.03
            comm = (
                "Calculated peak (%f) is more that 10eV away from the theoretical value (%f). Please check your scan"
                % (savpk, self.thEdge))

            logging.getLogger("HWR").warning(
                "EnergyScan: calculated peak (%f) is more that 20eV %s the theoretical value (%f). Please check your scan and choose the energies manually"
                % (savpk, (self.thEdge - ip) > 0.02 and "below"
                   or "above", self.thEdge))

        archiveEfsFile = os.path.extsep.join((scanArchiveFilePrefix, "efs"))
        try:
            fi = open(scanFile)
            fo = open(archiveEfsFile, "w")
        except BaseException:
            self.storeEnergyScan()
            self.emit("energyScanFailed", ())
            return
        else:
            fo.write(fi.read())
            fi.close()
            fo.close()

        self.scanInfo["peakEnergy"] = pk
        self.scanInfo["inflectionEnergy"] = ip
        self.scanInfo["remoteEnergy"] = rm
        self.scanInfo["peakFPrime"] = fpPeak
        self.scanInfo["peakFDoublePrime"] = fppPeak
        self.scanInfo["inflectionFPrime"] = fpInfl
        self.scanInfo["inflectionFDoublePrime"] = fppInfl
        self.scanInfo["comments"] = comm

        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = zip(
            *chooch_graph_data)
        chooch_graph_x = list(chooch_graph_x)
        for i in range(len(chooch_graph_x)):
            chooch_graph_x[i] = chooch_graph_x[i] / 1000.0

        logging.getLogger("HWR").info("<chooch> Saving png")
        # prepare to save png files
        title = "%10s  %6s  %6s\n%10s  %6.2f  %6.2f\n%10s  %6.2f  %6.2f" % (
            "energy",
            "f'",
            "f''",
            pk,
            fpPeak,
            fppPeak,
            ip,
            fpInfl,
            fppInfl,
        )
        fig = Figure(figsize=(15, 11))
        ax = fig.add_subplot(211)
        ax.set_title("%s\n%s" % (scanFile, title))
        ax.grid(True)
        ax.plot(*(zip(*scanData)), **{"color": "black"})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2 = fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color="blue"))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color="red"))
        canvas = FigureCanvasAgg(fig)

        escan_png = os.path.extsep.join((scanFilePrefix, "png"))
        escan_archivepng = os.path.extsep.join((scanArchiveFilePrefix, "png"))
        self.scanInfo["jpegChoochFileFullPath"] = str(escan_archivepng)
        try:
            logging.getLogger("HWR").info(
                "Rendering energy scan and Chooch graphs to PNG file : %s",
                escan_png)
            canvas.print_figure(escan_png, dpi=80)
        except BaseException:
            logging.getLogger("HWR").exception("could not print figure")
        try:
            logging.getLogger("HWR").info(
                "Saving energy scan to archive directory for ISPyB : %s",
                escan_archivepng,
            )
            canvas.print_figure(escan_archivepng, dpi=80)
        except BaseException:
            logging.getLogger("HWR").exception("could not save figure")

        self.storeEnergyScan()
        self.scanInfo = None

        logging.getLogger("HWR").info("<chooch> returning")
        self.emit(
            "chooch_finished",
            (
                pk,
                fppPeak,
                fpPeak,
                ip,
                fppInfl,
                fpInfl,
                rm,
                chooch_graph_x,
                chooch_graph_y1,
                chooch_graph_y2,
                title,
            ),
        )
        return (
            pk,
            fppPeak,
            fpPeak,
            ip,
            fppInfl,
            fpInfl,
            rm,
            chooch_graph_x,
            chooch_graph_y1,
            chooch_graph_y2,
            title,
        )
コード例 #4
0
    def doChooch(self, elt, edge, scanArchiveFilePrefix, scanFilePrefix):
        #symbol = "_".join((elt, edge))
        #scanArchiveFilePrefix = "_".join((scanArchiveFilePrefix, symbol))

        #i = 1
        #while os.path.isfile(os.path.extsep.join((scanArchiveFilePrefix + str(i), "raw"))):
            #i = i + 1

        #scanArchiveFilePrefix = scanArchiveFilePrefix + str(i) 
        #archiveRawScanFile=os.path.extsep.join((scanArchiveFilePrefix, "raw"))
        rawScanFile=os.path.extsep.join((scanFilePrefix, "raw"))
        scanFile=os.path.extsep.join((scanFilePrefix, "efs"))
        logging.info('SOLEILEnergyScan doChooch rawScanFile %s, scanFile %s' % (rawScanFile, scanFile))
        #if not os.path.exists(os.path.dirname(scanArchiveFilePrefix)):
            #os.makedirs(os.path.dirname(scanArchiveFilePrefix))
        
        #try:
            #f=open(rawScanFile, "w")
            #pyarch_f=open(archiveRawScanFile, "w")
        #except:
            #logging.getLogger("HWR").exception("could not create raw scan files")
            #self.storeEnergyScan()
            #self.emit("energyScanFailed", ())
            #return
        #else:
            #scanData = []
            
            #if scanObject is None:                
                #raw_data_file = os.path.join(os.path.dirname(scanFilePrefix), 'data.raw')
                #try:
                    #raw_file = open(raw_data_file, 'r')
                #except:
                    #self.storeEnergyScan()
                    #self.emit("energyScanFailed", ())
                    #return
                
                #for line in raw_file.readlines()[2:]:
                    #(x, y) = line.split('\t')
                    #x = float(x.strip())
                    #y = float(y.strip())
                    #x = x < 1000 and x*1000.0 or x
                    #scanData.append((x, y))
                    #f.write("%f,%f\r\n" % (x, y))
                    #pyarch_f.write("%f,%f\r\n"% (x, y))
            #else:
                #for i in range(len(scanObject.x)):
                    #x = float(scanObject.x[i])
                    #x = x < 1000 and x*1000.0 or x 
                    #y = float(scanObject.y[i])
                    #scanData.append((x, y))
                    #f.write("%f,%f\r\n" % (x, y))
                    #pyarch_f.write("%f,%f\r\n"% (x, y)) 

            #f.close()
            #pyarch_f.close()
            #self.scanInfo["scanFileFullPath"]=str(archiveRawScanFile)
        scanData = self.xanes.raw
        logging.info('scanData %s' % scanData)
        logging.info('PyChooch file %s' % PyChooch.__file__)
        pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = PyChooch.calc(scanData, elt, edge, scanFile)
        rm=(pk+30)/1000.0
        pk=pk/1000.0
        savpk = pk
        ip=ip/1000.0
        comm = ""

        self.thEdge = self.xanes.e_edge
        logging.getLogger("HWR").info("th. Edge %s ; chooch results are pk=%f, ip=%f, rm=%f" % (self.thEdge, pk,ip,rm))
        logging.info('math.fabs(self.thEdge - ip) %s' % math.fabs(self.thEdge - ip))
        logging.info('self.thEdgeThreshold %s' % self.thEdgeThreshold)
        
        logging.getLogger("HWR").warning('EnergyScan: calculated peak (%f) is more that 20eV %s the theoretical value (%f). Please check your scan and choose the energies manually' % (savpk, (self.thEdge - ip) < self.thEdgeThreshold and "below" or "above", self.thEdge))
        
        if math.fabs(self.thEdge - ip) > self.thEdgeThreshold:
          logging.info('Theoretical edge too different from the one just determined')
          pk = 0
          ip = 0
          rm = self.thEdge + 0.03
          comm = 'Calculated peak (%f) is more that 10eV away from the theoretical value (%f). Please check your scan' % (savpk, self.thEdge)
   
          logging.getLogger("HWR").warning('EnergyScan: calculated peak (%f) is more that 20eV %s the theoretical value (%f). Please check your scan and choose the energies manually' % (savpk, (self.thEdge - ip) < self.thEdgeThreshold and "below" or "above", self.thEdge))

        archiveEfsFile=os.path.extsep.join((scanArchiveFilePrefix, "efs"))

        logging.info('archiveEfsFile %s' % archiveEfsFile)

        # Check access to archive directory
        dirname = os.path.dirname(archiveEfsFile)
        if not os.path.exists(dirname): 
            try:
               os.makedirs( dirname )
               logging.getLogger("user_level_log").info( "Chooch. Archive path (%s) created"  % dirname)
            except OSError:
               logging.getLogger("user_level_log").error( "Chooch. Archive path is not accessible (%s)" % dirname)
               return None
            except:
               import traceback
               logging.getLogger("user_level_log").error( "Error creating archive path (%s) \n   %s" % (dirname, traceback.format_exc()))
               return None
        else:
            if not os.path.isdir(dirname):
               logging.getLogger("user_level_log").error( "Chooch. Archive path does not seem to be a valid directory (%s)" % dirname)
               return None

        try:
          fi=open(scanFile)
          fo=open(archiveEfsFile, "w")
        except:
          import traceback
          logging.getLogger("user_level_log").error( traceback.format_exc())
          self.storeEnergyScan()
          self.emit("energyScanFailed", ())
          return None
        else:
          fo.write(fi.read())
          fi.close()
          fo.close()

        logging.info('archive saved')
        self.scanInfo["peakEnergy"]=pk
        self.scanInfo["inflectionEnergy"]=ip
        self.scanInfo["remoteEnergy"]=rm
        self.scanInfo["peakFPrime"]=fpPeak
        self.scanInfo["peakFDoublePrime"]=fppPeak
        self.scanInfo["inflectionFPrime"]=fpInfl
        self.scanInfo["inflectionFDoublePrime"]=fppInfl
        self.scanInfo["comments"] = comm
        logging.info('self.scanInfo %s' % self.scanInfo)
        
        logging.info('chooch_graph_data %s' % str(chooch_graph_data))
        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = zip(*chooch_graph_data)
        chooch_graph_x = list(chooch_graph_x)
        logging.info('chooch_graph_x %s' %  str(chooch_graph_x))
        for i in range(len(chooch_graph_x)):
          chooch_graph_x[i]=chooch_graph_x[i]/1000.0

        logging.getLogger("HWR").info("<chooch> Saving png" )
        # prepare to save png files
        title="%10s  %6s  %6s\n%10s  %6.2f  %6.2f\n%10s  %6.2f  %6.2f" % ("energy", "f'", "f''", pk, fpPeak, fppPeak, ip, fpInfl, fppInfl) 
        fig=Figure(figsize=(15, 11))
        ax=fig.add_subplot(211)
        ax.set_title("%s\n%s" % (scanFile, title))
        ax.grid(True)
        ax.plot(*(zip(*scanData)), **{"color":'black'})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2=fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color='blue'))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color='red'))
        canvas=FigureCanvasAgg(fig)

        escan_png = os.path.extsep.join((scanFilePrefix, "png"))
        escan_archivepng = os.path.extsep.join((scanArchiveFilePrefix, "png")) 
        self.scanInfo["jpegChoochFileFullPath"]=str(escan_archivepng)
        try:
          logging.getLogger("HWR").info("Rendering energy scan and Chooch graphs to PNG file : %s", escan_png)
          canvas.print_figure(escan_png, dpi=80)
        except:
          logging.getLogger("HWR").exception("could not print figure")
        try:
          logging.getLogger("HWR").info("Saving energy scan to archive directory for ISPyB : %s", escan_archivepng)
          canvas.print_figure(escan_archivepng, dpi=80)
        except:
          logging.getLogger("HWR").exception("could not save figure")

        self.storeEnergyScan()
        self.scanInfo=None

        logging.getLogger("HWR").info("<chooch> returning" )
        self.emit('chooch_finished', (pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title))
        self.choochResults = pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title
        return pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title
コード例 #5
0
    def doChooch(self, elt, edge, scan_directory, archive_directory, prefix):
        """
        Descript. :
        """
        symbol = "_".join((elt, edge))
        scan_file_prefix = os.path.join(scan_directory, prefix)
        archive_file_prefix = os.path.join(archive_directory, prefix)

        if os.path.exists(scan_file_prefix + ".raw"):
            i = 1
            while os.path.exists(scan_file_prefix + "%d.raw" % i):
                i = i + 1
            scan_file_prefix += "_%d" % i
            archive_file_prefix += "_%d" % i

        scan_file_raw_filename = os.path.extsep.join((scan_file_prefix, "raw"))
        archive_file_raw_filename = os.path.extsep.join(
            (archive_file_prefix, "raw"))
        scan_file_efs_filename = os.path.extsep.join((scan_file_prefix, "efs"))
        archive_file_efs_filename = os.path.extsep.join(
            (archive_file_prefix, "efs"))
        scan_file_png_filename = os.path.extsep.join((scan_file_prefix, "png"))
        archive_file_png_filename = os.path.extsep.join(
            (archive_file_prefix, "png"))

        try:
            if not os.path.exists(scan_directory):
                os.makedirs(scan_directory)
            if not os.path.exists(archive_directory):
                os.makedirs(archive_directory)
        except:
            logging.getLogger("HWR").exception(
                "EMBLEnergyScan: could not create energy scan result directory."
            )
            self.store_energy_scan()
            self.emit("energyScanFailed", ())
            return

        try:
            scan_file_raw = open(scan_file_raw_filename, "w")
            archive_file_raw = open(archive_file_raw_filename, "w")
        except:
            logging.getLogger("HWR").exception(
                "EMBLEnergyScan: could not create energy scan result raw file")
            self.store_energy_scan()
            self.emit("energyScanFailed", ())
            return
        else:
            scanData = []
            for i in range(len(self.scanData)):
                x = float(self.scanData[i][0])
                x = x < 1000 and x * 1000.0 or x
                y = float(self.scanData[i][1])
                scanData.append((x, y))
                scan_file_raw.write("%f,%f\r\n" % (x, y))
                archive_file_raw.write("%f,%f\r\n" % (x, y))
            scan_file_raw.close()
            archive_file_raw.close()
            self.scanInfo["scanFileFullPath"] = str(scan_file_raw_filename)

        pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = \
             PyChooch.calc(scanData, elt, edge, scan_file_efs_filename)

        rm = (pk + 30) / 1000.0
        pk = pk / 1000.0
        savpk = pk
        ip = ip / 1000.0
        comm = ""
        #IK TODO clear this
        self.scanInfo['edgeEnergy'] = 0.1
        self.thEdge = self.scanInfo['edgeEnergy']
        logging.getLogger("HWR").info(
            "th. Edge %s ; chooch results are pk=%f, ip=%f, rm=%f" %
            (self.thEdge, pk, ip, rm))

        #should be better, but OK for time being
        self.thEdgeThreshold = 0.01
        if math.fabs(self.thEdge - ip) > self.thEdgeThreshold:
            pk = 0
            ip = 0
            rm = self.thEdge + 0.03
            comm = 'Calculated peak (%f) is more that 10eV away from the theoretical value (%f). Please check your scan' % \
                   (savpk, self.thEdge)

            logging.getLogger("HWR").warning('EnergyScan: calculated peak (%f) is more that 20eV %s the theoretical value (%f). Please check your scan and choose the energies manually' % \
                     (savpk, (self.thEdge - ip) > 0.02 and "below" or "above", self.thEdge))

        try:
            fi = open(scan_file_efs_filename)
            fo = open(archive_file_efs_filename, "w")
        except:
            self.store_energy_scan()
            self.emit("energyScanFailed", ())
            return
        else:
            fo.write(fi.read())
            fi.close()
            fo.close()

        self.scanInfo["peakEnergy"] = pk
        self.scanInfo["inflectionEnergy"] = ip
        self.scanInfo["remoteEnergy"] = rm
        self.scanInfo["peakFPrime"] = fpPeak
        self.scanInfo["peakFDoublePrime"] = fppPeak
        self.scanInfo["inflectionFPrime"] = fpInfl
        self.scanInfo["inflectionFDoublePrime"] = fppInfl
        self.scanInfo["comments"] = comm

        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = list(
            zip(*chooch_graph_data))
        chooch_graph_x = list(chooch_graph_x)
        for i in range(len(chooch_graph_x)):
            chooch_graph_x[i] = chooch_graph_x[i] / 1000.0

        #logging.getLogger("HWR").info("EMBLEnergyScan: Saving png" )
        # prepare to save png files
        title = "%s  %s  %s\n%.4f  %.2f  %.2f\n%.4f  %.2f  %.2f" % \
              ("energy", "f'", "f''", pk, fpPeak, fppPeak, ip, fpInfl, fppInfl)
        fig = Figure(figsize=(15, 11))
        ax = fig.add_subplot(211)
        ax.set_title("%s\n%s" % (scan_file_efs_filename, title))
        ax.grid(True)
        ax.plot(*(list(zip(*scanData))), **{"color": 'black'})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2 = fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color='blue'))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color='red'))
        canvas = FigureCanvasAgg(fig)

        self.scanInfo["jpegChoochFileFullPath"] = str(
            archive_file_png_filename)
        try:
            logging.getLogger("HWR").info(
                "Rendering energy scan and Chooch graphs to PNG file : %s",
                scan_file_png_filename)
            canvas.print_figure(scan_file_png_filename, dpi=80)
        except:
            logging.getLogger("HWR").exception("could not print figure")
        try:
            logging.getLogger("HWR").info(
                "Saving energy scan to archive directory for ISPyB : %s",
                archive_file_png_filename)
            canvas.print_figure(archive_file_png_filename, dpi=80)
        except:
            logging.getLogger("HWR").exception("could not save figure")

        self.store_energy_scan()

        logging.getLogger("HWR").info("<chooch> returning")
        self.emit('choochFinished',
                  (pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm,
                   chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title))
        return pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, \
                 chooch_graph_y1, chooch_graph_y2, title
コード例 #6
0
    def doChooch(self, elt, edge, scanArchiveFilePrefix, scanFilePrefix):
        symbol = "_".join((elt, edge))
        scanArchiveFilePrefix = "_".join((scanArchiveFilePrefix, symbol))

        i = 1
        while os.path.isfile(os.path.extsep.join((scanArchiveFilePrefix + str(i), "raw"))):
            i = i + 1

        scanArchiveFilePrefix = scanArchiveFilePrefix + str(i) 
        archiveRawScanFile=os.path.extsep.join((scanArchiveFilePrefix, "raw"))
        rawScanFile=os.path.extsep.join((scanFilePrefix, "raw"))
        scanFile=os.path.extsep.join((scanFilePrefix, "efs"))

        if not os.path.exists(os.path.dirname(scanArchiveFilePrefix)):
            os.makedirs(os.path.dirname(scanArchiveFilePrefix))
        
        try:
            f=open(rawScanFile, "w")
            pyarch_f=open(archiveRawScanFile, "w")
        except:
            logging.getLogger("HWR").exception("could not create raw scan files")
            self.storeEnergyScan()
            self.emit("energyScanFailed", ())
            return
        else:
            scanData = []
            
            raw_data_file = os.path.join(os.path.dirname(scanFilePrefix), 'data.raw')
            try:
                raw_file = open(raw_data_file, 'r')
            except:
                self.storeEnergyScan()
                self.emit("energyScanFailed", ())
                return

            for line in raw_file.readlines()[2:]:
                (x, y) = line.split('\t')
                x = float(x.strip())
                y = float(y.strip())
                #x = x < 1000 and x*1000.0 or x
                scanData.append((x, y))
                f.write("%f,%f\r\n" % (x, y))
                pyarch_f.write("%f,%f\r\n"% (x, y))


            f.close()
            pyarch_f.close()
            self.energy_scan_parameters["scanFileFullPath"]=str(archiveRawScanFile)

        pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = PyChooch.calc(scanData, elt, edge, scanFile)
        rm=(pk+30)/1000.0
        pk=pk/1000.0
        savpk = pk
        ip=ip/1000.0
        comm = ""
        self.thEdge = self.energy_scan_parameters['edgeEnergy']
        logging.getLogger("HWR").info("th. Edge %s ; chooch results are pk=%f, ip=%f, rm=%f" % (self.thEdge, pk,ip,rm))

        #should be better, but OK for time being
        self.thEdgeThreshold = 0.01
        if math.fabs(self.thEdge - ip) > self.thEdgeThreshold:
          pk = 0
          ip = 0
          rm = self.thEdge + 0.03
          comm = 'Calculated peak (%f) is more that 10eV away from the theoretical value (%f). Please check your scan' % (savpk, self.thEdge)
   
          logging.getLogger("HWR").warning('EnergyScan: calculated peak (%f) is more that 20eV %s the theoretical value (%f). Please check your scan and choose the energies manually' % (savpk, (self.thEdge - ip) > 0.02 and "below" or "above", self.thEdge))

        archiveEfsFile=os.path.extsep.join((scanArchiveFilePrefix, "efs"))
        try:
          fi=open(scanFile)
          fo=open(archiveEfsFile, "w")
        except:
          self.storeEnergyScan()
          self.emit("energyScanFailed", ())
          return
        else:
          fo.write(fi.read())
          fi.close()
          fo.close()

        self.energy_scan_parameters["peakEnergy"]=pk
        self.energy_scan_parameters["inflectionEnergy"]=ip
        self.energy_scan_parameters["remoteEnergy"]=rm
        self.energy_scan_parameters["peakFPrime"]=fpPeak
        self.energy_scan_parameters["peakFDoublePrime"]=fppPeak
        self.energy_scan_parameters["inflectionFPrime"]=fpInfl
        self.energy_scan_parameters["inflectionFDoublePrime"]=fppInfl
        self.energy_scan_parameters["comments"] = comm

        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = zip(*chooch_graph_data)
        chooch_graph_x = list(chooch_graph_x)
        for i in range(len(chooch_graph_x)):
          chooch_graph_x[i]=chooch_graph_x[i]/1000.0

        logging.getLogger("HWR").info("<chooch> Saving png" )
        # prepare to save png files
        title="%10s  %6s  %6s\n%10s  %6.2f  %6.2f\n%10s  %6.2f  %6.2f" % ("energy", "f'", "f''", pk, fpPeak, fppPeak, ip, fpInfl, fppInfl) 
        fig=Figure(figsize=(15, 11))
        ax=fig.add_subplot(211)
        ax.set_title("%s\n%s" % (scanFile, title))
        ax.grid(True)
        ax.plot(*(zip(*scanData)), **{"color":'black'})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2=fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color='blue'))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color='red'))
        canvas=FigureCanvasAgg(fig)

        escan_png = os.path.extsep.join((scanFilePrefix, "png"))
        escan_archivepng = os.path.extsep.join((scanArchiveFilePrefix, "png")) 
        self.energy_scan_parameters["jpegChoochFileFullPath"]=str(escan_archivepng)
        try:
          logging.getLogger("HWR").info("Rendering energy scan and Chooch graphs to PNG file : %s", escan_png)
          canvas.print_figure(escan_png, dpi=80)
        except:
          logging.getLogger("HWR").exception("could not print figure")
        try:
          logging.getLogger("HWR").info("Saving energy scan to archive directory for ISPyB : %s", escan_archivepng)
          canvas.print_figure(escan_archivepng, dpi=80)
        except:
          logging.getLogger("HWR").exception("could not save figure")

        self.energy_scan_parameters['endTime']=time.strftime("%Y-%m-%d %H:%M:%S")
        self.storeEnergyScan()

        logging.getLogger("HWR").info("<chooch> returning" )
        self.emit('chooch_finished', (pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title))
        return pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title
コード例 #7
0
import PyChooch
import sys

if __name__ == '__main__':
    filename = sys.argv[1]
    f = open(filename)
    data = []
    i = 0

    for l in f:
        i = i + 1
        if (i > 2):
            data.append(list(map(float, l.split())))

    #print(data)

    print(PyChooch.calc(data, "Se", "K"))
コード例 #8
0
    def doChooch(self, elt, edge, scanArchiveFilePrefix, scanFilePrefix):
        """
        Descript. :
        """
        symbol = "_".join((elt, edge))
        scanArchiveFilePrefix = "_".join((scanArchiveFilePrefix, symbol))
        i = 1
        while os.path.isfile(os.path.extsep.join((scanArchiveFilePrefix + str(i), "raw"))):
            i = i + 1
        
        scanArchiveFilePrefix = scanArchiveFilePrefix + str(i)
        archiveRawScanFile = os.path.extsep.join((scanArchiveFilePrefix, "raw"))
        rawScanFile = os.path.extsep.join((scanFilePrefix, "raw"))
        scanFile = os.path.extsep.join((scanFilePrefix, "efs"))
        if not os.path.exists(os.path.dirname(scanArchiveFilePrefix)):
            os.makedirs(os.path.dirname(scanArchiveFilePrefix))
        try:
            f = open(rawScanFile, "w")
            pyarch_f = open(archiveRawScanFile, "w")
        except:
            logging.getLogger("HWR").exception("could not create raw scan files")
            self.store_energy_scan()
            self.emit("energyScanFailed", ())
            return
        else:
            scanData = []
            for i in range(len(self.scan_data)):
                x = float(self.scan_data[i][0])
                x = x < 1000 and x * 1000.0 or x
                y = float(self.scan_data[i][1])
                scanData.append((x, y))
                f.write("%f,%f\r\n" % (x, y))
                pyarch_f.write("%f,%f\r\n" % (x, y))
            f.close()
            pyarch_f.close()
            self.scan_info["scanFileFullPath"] = str(archiveRawScanFile)

        
        pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = PyChooch.calc(scanData, elt, edge, scanFile)

        rm = (pk + 30) / 1000.0
        pk = pk / 1000.0
        savpk = pk
        ip = ip / 1000.0
        comm = ""
        logging.getLogger("HWR").info("th. Edge %s ; chooch results are pk=%f, ip=%f, rm=%f" %\
               (self.thEdgeThreshold, pk, ip, rm))
        
        archiveEfsFile = os.path.extsep.join((scanArchiveFilePrefix, "efs"))
        try:
            fi = open(scanFile)
            fo = open(archiveEfsFile, "w")
        except:
            self.store_energy_scan()
            self.emit("energyScanFailed", ())
            return
        else:
            fo.write(fi.read())
            fi.close()
            fo.close()

        self.scan_info["peakEnergy"] = pk
        self.scan_info["inflectionEnergy"] = ip
        self.scan_info["remoteEnergy"] = rm
        self.scan_info["peakFPrime"] = fpPeak
        self.scan_info["peakFDoublePrime"] = fppPeak
        self.scan_info["inflectionFPrime"] = fpInfl
        self.scan_info["inflectionFDoublePrime"] = fppInfl
        self.scan_info["comments"] = comm

        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = zip(*chooch_graph_data)
        chooch_graph_x = list(chooch_graph_x)
        for i in range(len(chooch_graph_x)):
            chooch_graph_x[i] = chooch_graph_x[i] / 1000.0

        logging.getLogger("HWR").info("<chooch> Saving png" )
        # prepare to save png files
        title = "%10s  %6s  %6s\n%6.2f  %6.2f  %6.2f\n%6.2f  %6.2f  %6.2f" % \
              ("energy", "f'", "f''", pk, fpPeak, fppPeak, ip, fpInfl, fppInfl)
        fig = Figure(figsize = (15, 11))
        ax = fig.add_subplot(211)
        ax.set_title("%s\n%s" % (scanFile, title))
        ax.grid(True)
        ax.plot(*(zip(*scanData)), **{"color": 'black'})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2 = fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color = 'blue'))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color = 'red'))
        canvas = FigureCanvasAgg(fig)

        escan_png = os.path.extsep.join((scanFilePrefix, "png"))
        escan_archivepng = os.path.extsep.join((scanArchiveFilePrefix, "png"))
        self.scan_info["jpegChoochFileFullPath"] = str(escan_archivepng)
        try:
            logging.getLogger("HWR").info("Rendering energy scan and Chooch graphs to PNG file : %s", escan_png)
            canvas.print_figure(escan_png, dpi = 80)
        except:
            logging.getLogger("HWR").exception("could not print figure")
        try:
            logging.getLogger("HWR").info("Saving energy scan to archive directory for ISPyB : %s", escan_archivepng)
            canvas.print_figure(escan_archivepng, dpi = 80)
        except:
            logging.getLogger("HWR").exception("could not save figure")

        self.store_energy_scan()

        logging.getLogger("HWR").info("<chooch> returning" )
        self.emit('choochFinished', pk, fppPeak, fpPeak, ip, fppInfl, fpInfl,
                 rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title)
        return pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, \
                 chooch_graph_y1, chooch_graph_y2, title
コード例 #9
0
    def doChooch(self, scanObject, scanDesc):
                 #elt, 
                 #edge):
                 #scanArchiveFilePrefix = 'scanArchiveFilePrefix', 
                 #scanFilePrefix = 'scanFilePrefix'):
                     
        logging.getLogger().info("EnergyScan: doChooch")
        print('scanObject', scanObject)
        print('scanDesc', scanDesc)
        #archiveRawScanFile=os.path.extsep.join((scanArchiveFilePrefix, "raw"))
        #rawScanFile=os.path.extsep.join((scanFilePrefix, "raw"))
        #scanFile=os.path.extsep.join((scanFilePrefix, "efs"))
      
        #if not os.path.exists(os.path.dirname(scanArchiveFilePrefix)):
            #os.mkdir(os.path.dirname(scanArchiveFilePrefix))
        
        #try:
            #f=open(rawScanFile, "w")
            #pyarch_f=open(archiveRawScanFile, "w")
        #except:
            #logging.getLogger("HWR").exception("could not create raw scan files")
            #self.storeEnergyScan()
            #self.emit("energyScanFailed", ())
            #return
        #else:
            #scanData = []
            #for i in range(len(scanObject.x)):
                    #x = float(scanObject.x[i])
                    #x = x < 1000 and x*1000.0 or x 
                    #y = float(scanObject.y[i])
                    #scanData.append((x, y))
                    #f.write("%f,%f\r\n" % (x, y))
                    #pyarch_f.write("%f,%f\r\n"% (x, y)) 
            #f.close()
            #pyarch_f.close()
            #self.scanInfo["scanFileFullPath"]=str(archiveRawScanFile)
        
        filenameIn = self.filenameIn
        filenameOut = filenameIn[:-3] + 'efs'
        scanData = []
        
        contents = file(filenameIn).readlines()
        file(filenameIn).close()
        
        for value in contents:
          if value[0] != '#' :
              vals = value.split()
              x = float(vals[0])
              x = x < 1000 and x*1000.0 or x #This is rather cryptic but seems to work (MS 11.03.13)
              y = float(vals[1])
              #if y == 0.0:
                  #self.scanCommandFailed()
                  #self.scanStatus.setText("data not valid for chooch")
                  #print "data not valid for chooch"
                  #return
              scanData.append((x, y))
              
        elt = scanDesc['element']
        edge = scanDesc['edgeEnergy']
        
        try:
            pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = PyChooch.calc(scanData,
                                                                                    elt, 
                                                                                    edge, 
                                                                                    filenameOut)
        except:
            pk = self.thEdge
            rm = (pk + 50.) / 1000.0
            savpk = pk
            ip = pk - 5. / 1000.0
            logging.getLogger("HWR").info("Chooch failed badly")
            #, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = self.thEdge, 
            
        rm = (pk + 50.) / 1000.0
        pk = pk / 1000.0
        savpk = pk
        ip = ip / 1000.0
        comm = ""
        logging.getLogger("HWR").info("th. Edge %s ; chooch results are pk=%f, ip=%f, rm=%f" % (self.thEdge,  pk, ip, rm))

        if math.fabs(self.thEdge - ip) > 0.01:
            pk = 0
            ip = 0
            rm = self.thEdge + 0.05
            comm = 'Calculated peak (%f) is more that 10eV away from the theoretical value (%f). Please check your scan' % (savpk, self.thEdge)
    
            logging.getLogger("HWR").warning('EnergyScan: calculated peak (%f) is more that 10eV %s the theoretical value (%f). Please check your scan and choose the energies manually' % (savpk, (self.thEdge - ip) > 0.01 and "below" or "above", self.thEdge))
        
        scanFile = filenameIn
        archiveEfsFile = filenameOut #os.path.extsep.join((scanArchiveFilePrefix, "efs"))
        try:
            fi = open(scanFile)
            fo = open(archiveEfsFile, "w")
        except:
            self.storeEnergyScan()
            self.emit("energyScanFailed", ())
            return
        else:
            fo.write(fi.read())
            fi.close()
            fo.close()

        self.scanInfo["peakEnergy"]=pk
        self.scanInfo["inflectionEnergy"]=ip
        self.scanInfo["remoteEnergy"]=rm
        self.scanInfo["peakFPrime"]=fpPeak
        self.scanInfo["peakFDoublePrime"]=fppPeak
        self.scanInfo["inflectionFPrime"]=fpInfl
        self.scanInfo["inflectionFDoublePrime"]=fppInfl
        self.scanInfo["comments"] = comm

        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = list(zip(*chooch_graph_data))
        chooch_graph_x = list(chooch_graph_x)
        for i in range(len(chooch_graph_x)):
          chooch_graph_x[i]=chooch_graph_x[i]/1000.0

        logging.getLogger("HWR").info("<chooch> Saving png" )
        # prepare to save png files
        title="%10s  %6s  %6s\n%10s  %6.2f  %6.2f\n%10s  %6.2f  %6.2f" % ("energy", "f'", "f''", pk, fpPeak, fppPeak, ip, fpInfl, fppInfl) 
        fig=Figure(figsize=(15, 11))
        ax=fig.add_subplot(211)
        ax.set_title("%s\n%s" % (scanFile, title))
        ax.grid(True)
        ax.plot(*(list(zip(*scanData))), **{"color":'black'})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2=fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color='blue'))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color='red'))
        canvas=FigureCanvasAgg(fig)

        escan_png = filenameOut[:-3] + 'png' #.replace('.esf', '.png') #os.path.extsep.join((scanFilePrefix, "png"))
        escan_archivepng = filenameOut[:-4] + '_archive.png'  #os.path.extsep.join((scanArchiveFilePrefix, "png")) 
        self.scanInfo["jpegChoochFileFullPath"]=str(escan_archivepng)
        try:
            logging.getLogger("HWR").info("Rendering energy scan and Chooch graphs to PNG file : %s", escan_png)
            canvas.print_figure(escan_png, dpi=80)
        except:
            logging.getLogger("HWR").exception("could not print figure")
        try:
            logging.getLogger("HWR").info("Saving energy scan to archive directory for ISPyB : %s", escan_archivepng)
            canvas.print_figure(escan_archivepng, dpi=80)
        except:
            logging.getLogger("HWR").exception("could not save figure")

        self.storeEnergyScan()
        self.scanInfo=None

        logging.getLogger("HWR").info("<chooch> returning" )
        return pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title
コード例 #10
0
    def doChooch(self, elt, edge, scanArchiveFilePrefix, scanFilePrefix):
        """
        Descript. :
        """
        symbol = "_".join((elt, edge))
        scanArchiveFilePrefix = "_".join((scanArchiveFilePrefix, symbol))
        i = 1
        while os.path.isfile(os.path.extsep.join((scanArchiveFilePrefix + str(i), "raw"))):
            i = i + 1
        
        scanArchiveFilePrefix = scanArchiveFilePrefix + str(i)
        archiveRawScanFile = os.path.extsep.join((scanArchiveFilePrefix, "raw"))
        rawScanFile = os.path.extsep.join((scanFilePrefix, "raw"))
        scanFile = os.path.extsep.join((scanFilePrefix, "efs"))
        if not os.path.exists(os.path.dirname(scanArchiveFilePrefix)):
            os.makedirs(os.path.dirname(scanArchiveFilePrefix))
        try:
            f = open(rawScanFile, "w")
            pyarch_f = open(archiveRawScanFile, "w")
        except:
            logging.getLogger("HWR").exception("could not create raw scan files")
            self.store_energy_scan()
            self.emit("energyScanFailed", ())
            return
        else:
            scanData = []
            for i in range(len(self.scan_data)):
                x = float(self.scan_data[i][0])
                x = x < 1000 and x * 1000.0 or x
                y = float(self.scan_data[i][1])
                scanData.append((x, y))
                f.write("%f,%f\r\n" % (x, y))
                pyarch_f.write("%f,%f\r\n" % (x, y))
            f.close()
            pyarch_f.close()
            self.scan_info["scanFileFullPath"] = str(archiveRawScanFile)

        
        pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, chooch_graph_data = PyChooch.calc(scanData, elt, edge, scanFile)

        rm = (pk + 30) / 1000.0
        pk = pk / 1000.0
        savpk = pk
        ip = ip / 1000.0
        comm = ""
        logging.getLogger("HWR").info("th. Edge %s ; chooch results are pk=%f, ip=%f, rm=%f" %\
               (self.thEdgeThreshold, pk, ip, rm))
        
        archiveEfsFile = os.path.extsep.join((scanArchiveFilePrefix, "efs"))
        try:
            fi = open(scanFile)
            fo = open(archiveEfsFile, "w")
        except:
            self.store_energy_scan()
            self.emit("energyScanFailed", ())
            return
        else:
            fo.write(fi.read())
            fi.close()
            fo.close()

        self.scan_info["peakEnergy"] = pk
        self.scan_info["inflectionEnergy"] = ip
        self.scan_info["remoteEnergy"] = rm
        self.scan_info["peakFPrime"] = fpPeak
        self.scan_info["peakFDoublePrime"] = fppPeak
        self.scan_info["inflectionFPrime"] = fpInfl
        self.scan_info["inflectionFDoublePrime"] = fppInfl
        self.scan_info["comments"] = comm

        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = zip(*chooch_graph_data)
        chooch_graph_x = list(chooch_graph_x)
        for i in range(len(chooch_graph_x)):
            chooch_graph_x[i] = chooch_graph_x[i] / 1000.0

        logging.getLogger("HWR").info("<chooch> Saving png" )
        # prepare to save png files
        title = "%10s  %6s  %6s\n%6.2f  %6.2f  %6.2f\n%6.2f  %6.2f  %6.2f" % \
              ("energy", "f'", "f''", pk, fpPeak, fppPeak, ip, fpInfl, fppInfl)
        fig = Figure(figsize = (15, 11))
        ax = fig.add_subplot(211)
        ax.set_title("%s\n%s" % (scanFile, title))
        ax.grid(True)
        ax.plot(*(zip(*scanData)), **{"color": 'black'})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2 = fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color = 'blue'))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color = 'red'))
        canvas = FigureCanvasAgg(fig)

        escan_png = os.path.extsep.join((scanFilePrefix, "png"))
        escan_archivepng = os.path.extsep.join((scanArchiveFilePrefix, "png"))
        self.scan_info["jpegChoochFileFullPath"] = str(escan_archivepng)
        try:
            logging.getLogger("HWR").info("Rendering energy scan and Chooch graphs to PNG file : %s", escan_png)
            canvas.print_figure(escan_png, dpi = 80)
        except:
            logging.getLogger("HWR").exception("could not print figure")
        try:
            logging.getLogger("HWR").info("Saving energy scan to archive directory for ISPyB : %s", escan_archivepng)
            canvas.print_figure(escan_archivepng, dpi = 80)
        except:
            logging.getLogger("HWR").exception("could not save figure")

        self.store_energy_scan()

        logging.getLogger("HWR").info("<chooch> returning" )
        self.emit('choochFinished', pk, fppPeak, fpPeak, ip, fppInfl, fpInfl,
                 rm, chooch_graph_x, chooch_graph_y1, chooch_graph_y2, title)
        return pk, fppPeak, fpPeak, ip, fppInfl, fpInfl, rm, chooch_graph_x, \
                 chooch_graph_y1, chooch_graph_y2, title
コード例 #11
0
    def doChooch(self, elt, edge, directory, archive_directory, prefix):
        self.energy_scan_parameters["endTime"] = time.strftime(
            "%Y-%m-%d %H:%M:%S")

        raw_data_file = os.path.join(directory, "data.raw")

        symbol = "_".join((elt, edge))
        archive_prefix = "_".join((prefix, symbol))
        raw_scan_file = os.path.join(directory, (archive_prefix + ".raw"))
        efs_scan_file = raw_scan_file.replace(".raw", ".efs")
        raw_arch_file = os.path.join(archive_directory,
                                     (archive_prefix + "1" + ".raw"))
        i = 0
        while os.path.isfile(raw_arch_file):
            i += 1
            raw_arch_file = os.path.join(archive_directory,
                                         (archive_prefix + str(i) + ".raw"))

        if not os.path.exists(archive_directory):
            os.makedirs(archive_directory)
        try:
            f = open(raw_scan_file, "w")
        except IOError:
            self.storeEnergyScan()
            self.emit("energyScanFailed", ())
            return
        else:
            scan_data = []
            try:
                with open(raw_data_file, "r") as raw_file:
                    for line in raw_file.readlines()[2:]:
                        try:
                            (x, y) = line.split("\t")
                        except BaseException:
                            (x, y) = line.split()
                        x = float(x.strip())
                        y = float(y.strip())
                        scan_data.append((x, y))
                        f.write("%f,%f\r\n" % (x, y))
                f.close()
            except IOError:
                self.storeEnergyScan()
                self.emit("energyScanFailed", ())
                return

        shutil.copy2(raw_scan_file, raw_arch_file)
        self.energy_scan_parameters["scanFileFullPath"] = raw_arch_file

        result = PyChooch.calc(scan_data, elt, edge, efs_scan_file)
        # PyChooch occasionally returns an error and the result
        # the sleep command assures that we get the result
        time.sleep(1)
        print(result[0])
        pk = result[0] / 1000.0
        fppPeak = result[1]
        fpPeak = result[2]
        ip = result[3] / 1000.0
        fppInfl = result[4]
        fpInfl = result[5]
        chooch_graph_data = result[6]

        rm = pk + 0.03

        comm = ""
        th_edge = float(self.energy_scan_parameters["edgeEnergy"])

        logging.getLogger("HWR").info(
            "Chooch results: pk = %f, ip = %f, rm = %f, Theoretical edge: %f" %
            (pk, ip, rm, th_edge))

        # +- shift from the theoretical edge [eV]
        edge_shift = 10
        calc_shift = (th_edge - ip) * 1000
        if math.fabs(calc_shift) > edge_shift:
            rm = th_edge + 0.03
            comm = "%s" % "below" if (calc_shift) > edge_shift else "above"
            comm = (
                "Calculated peak (%f) is more than %d eV %s the theoretical value (%f)."
                % (pk, edge_shift, comm, th_edge))

            logging.getLogger("user_level_log").warning(
                "EnergyScan: %s Check your scan and choose the energies manually"
                % comm)
            pk = 0
            ip = 0

        efs_arch_file = raw_arch_file.replace(".raw", ".efs")
        if os.path.isfile(efs_scan_file):
            shutil.copy2(efs_scan_file, efs_arch_file)
        else:
            self.storeEnergyScan()
            self.emit("energyScanFailed", ())
            return

        self.energy_scan_parameters["filename"] = raw_arch_file.split("/")[-1]
        self.energy_scan_parameters["peakEnergy"] = pk
        self.energy_scan_parameters["inflectionEnergy"] = ip
        self.energy_scan_parameters["remoteEnergy"] = rm
        self.energy_scan_parameters["peakFPrime"] = fpPeak
        self.energy_scan_parameters["peakFDoublePrime"] = fppPeak
        self.energy_scan_parameters["inflectionFPrime"] = fpInfl
        self.energy_scan_parameters["inflectionFDoublePrime"] = fppInfl
        self.energy_scan_parameters["comments"] = comm

        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = zip(
            *chooch_graph_data)
        chooch_graph_x = list(chooch_graph_x)
        chooch_graph_x = [x / 1000.0 for x in chooch_graph_x]

        logging.getLogger("HWR").info("Saving png")
        # prepare to save png files
        title = "%10s  %6s  %6s\n%10s  %6.2f  %6.2f\n%10s  %6.2f  %6.2f" % (
            "energy",
            "f'",
            "f''",
            pk,
            fpPeak,
            fppPeak,
            ip,
            fpInfl,
            fppInfl,
        )
        fig = Figure(figsize=(15, 11))
        ax = fig.add_subplot(211)
        ax.set_title("%s\n%s" % (efs_scan_file, title))
        ax.grid(True)
        ax.plot(*(zip(*scan_data)), **{"color": "black"})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2 = fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color="blue"))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color="red"))
        canvas = FigureCanvasAgg(fig)

        png_scan_file = raw_scan_file.replace(".raw", ".png")
        png_arch_file = raw_arch_file.replace(".raw", ".png")
        self.energy_scan_parameters["jpegChoochFileFullPath"] = str(
            png_arch_file)
        try:
            logging.getLogger("HWR").info(
                "Rendering energy scan and Chooch graphs to PNG file : %s",
                png_scan_file,
            )
            canvas.print_figure(png_scan_file, dpi=80)
        except BaseException:
            logging.getLogger("HWR").exception("could not print figure")
        try:
            logging.getLogger("HWR").info(
                "Saving energy scan to archive directory for ISPyB : %s",
                png_arch_file)
            canvas.print_figure(png_arch_file, dpi=80)
        except BaseException:
            logging.getLogger("HWR").exception("could not save figure")

        self.storeEnergyScan()

        self.emit(
            "chooch_finished",
            (
                pk,
                fppPeak,
                fpPeak,
                ip,
                fppInfl,
                fpInfl,
                rm,
                chooch_graph_x,
                chooch_graph_y1,
                chooch_graph_y2,
                title,
            ),
        )
        return (
            pk,
            fppPeak,
            fpPeak,
            ip,
            fppInfl,
            fpInfl,
            rm,
            chooch_graph_x,
            chooch_graph_y1,
            chooch_graph_y2,
            title,
        )
コード例 #12
0
    def doChooch(self, elt, edge, directory, archive_directory, prefix):
        self.energy_scan_parameters["endTime"] = time.strftime("%Y-%m-%d %H:%M:%S")

        raw_data_file = os.path.join(directory, "data.raw")

        symbol = "_".join((elt, edge))
        archive_prefix = "_".join((prefix, symbol))
        raw_scan_file = os.path.join(directory, (archive_prefix + ".raw"))
        efs_scan_file = raw_scan_file.replace(".raw", ".efs")
        raw_arch_file = os.path.join(archive_directory, (archive_prefix + "1" + ".raw"))
        i = 0
        while os.path.isfile(raw_arch_file):
            i += 1
            raw_arch_file = os.path.join(
                archive_directory, (archive_prefix + str(i) + ".raw")
            )

        if not os.path.exists(archive_directory):
            os.makedirs(archive_directory)
        try:
            f = open(raw_scan_file, "w")
        except IOError:
            self.storeEnergyScan()
            self.emit("energyScanFailed", ())
            return
        else:
            scan_data = []
            try:
                with open(raw_data_file, "r") as raw_file:
                    for line in raw_file.readlines()[2:]:
                        try:
                            (x, y) = line.split("\t")
                        except BaseException:
                            (x, y) = line.split()
                        x = float(x.strip())
                        y = float(y.strip())
                        scan_data.append((x, y))
                        f.write("%f,%f\r\n" % (x, y))
                f.close()
            except IOError:
                self.storeEnergyScan()
                self.emit("energyScanFailed", ())
                return

        shutil.copy2(raw_scan_file, raw_arch_file)
        self.energy_scan_parameters["scanFileFullPath"] = raw_arch_file

        result = PyChooch.calc(scan_data, elt, edge, efs_scan_file)
        # PyChooch occasionally returns an error and the result
        # the sleep command assures that we get the result
        time.sleep(1)
        print result[0]
        pk = result[0] / 1000.0
        fppPeak = result[1]
        fpPeak = result[2]
        ip = result[3] / 1000.0
        fppInfl = result[4]
        fpInfl = result[5]
        chooch_graph_data = result[6]

        rm = pk + 0.03

        comm = ""
        th_edge = float(self.energy_scan_parameters["edgeEnergy"])

        logging.getLogger("HWR").info(
            "Chooch results: pk = %f, ip = %f, rm = %f, Theoretical edge: %f"
            % (pk, ip, rm, th_edge)
        )

        # +- shift from the theoretical edge [eV]
        edge_shift = 10
        calc_shift = (th_edge - ip) * 1000
        if math.fabs(calc_shift) > edge_shift:
            rm = th_edge + 0.03
            comm = "%s" % "below" if (calc_shift) > edge_shift else "above"
            comm = (
                "Calculated peak (%f) is more than %d eV %s the theoretical value (%f)."
                % (pk, edge_shift, comm, th_edge)
            )

            logging.getLogger("user_level_log").warning(
                "EnergyScan: %s Check your scan and choose the energies manually" % comm
            )
            pk = 0
            ip = 0

        efs_arch_file = raw_arch_file.replace(".raw", ".efs")
        if os.path.isfile(efs_scan_file):
            shutil.copy2(efs_scan_file, efs_arch_file)
        else:
            self.storeEnergyScan()
            self.emit("energyScanFailed", ())
            return

        self.energy_scan_parameters["filename"] = raw_arch_file.split("/")[-1]
        self.energy_scan_parameters["peakEnergy"] = pk
        self.energy_scan_parameters["inflectionEnergy"] = ip
        self.energy_scan_parameters["remoteEnergy"] = rm
        self.energy_scan_parameters["peakFPrime"] = fpPeak
        self.energy_scan_parameters["peakFDoublePrime"] = fppPeak
        self.energy_scan_parameters["inflectionFPrime"] = fpInfl
        self.energy_scan_parameters["inflectionFDoublePrime"] = fppInfl
        self.energy_scan_parameters["comments"] = comm

        chooch_graph_x, chooch_graph_y1, chooch_graph_y2 = zip(*chooch_graph_data)
        chooch_graph_x = list(chooch_graph_x)
        chooch_graph_x = [x / 1000.0 for x in chooch_graph_x]

        logging.getLogger("HWR").info("Saving png")
        # prepare to save png files
        title = "%10s  %6s  %6s\n%10s  %6.2f  %6.2f\n%10s  %6.2f  %6.2f" % (
            "energy",
            "f'",
            "f''",
            pk,
            fpPeak,
            fppPeak,
            ip,
            fpInfl,
            fppInfl,
        )
        fig = Figure(figsize=(15, 11))
        ax = fig.add_subplot(211)
        ax.set_title("%s\n%s" % (efs_scan_file, title))
        ax.grid(True)
        ax.plot(*(zip(*scan_data)), **{"color": "black"})
        ax.set_xlabel("Energy")
        ax.set_ylabel("MCA counts")
        ax2 = fig.add_subplot(212)
        ax2.grid(True)
        ax2.set_xlabel("Energy")
        ax2.set_ylabel("")
        handles = []
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y1, color="blue"))
        handles.append(ax2.plot(chooch_graph_x, chooch_graph_y2, color="red"))
        canvas = FigureCanvasAgg(fig)

        png_scan_file = raw_scan_file.replace(".raw", ".png")
        png_arch_file = raw_arch_file.replace(".raw", ".png")
        self.energy_scan_parameters["jpegChoochFileFullPath"] = str(png_arch_file)
        try:
            logging.getLogger("HWR").info(
                "Rendering energy scan and Chooch graphs to PNG file : %s",
                png_scan_file,
            )
            canvas.print_figure(png_scan_file, dpi=80)
        except BaseException:
            logging.getLogger("HWR").exception("could not print figure")
        try:
            logging.getLogger("HWR").info(
                "Saving energy scan to archive directory for ISPyB : %s", png_arch_file
            )
            canvas.print_figure(png_arch_file, dpi=80)
        except BaseException:
            logging.getLogger("HWR").exception("could not save figure")

        self.storeEnergyScan()

        self.emit(
            "chooch_finished",
            (
                pk,
                fppPeak,
                fpPeak,
                ip,
                fppInfl,
                fpInfl,
                rm,
                chooch_graph_x,
                chooch_graph_y1,
                chooch_graph_y2,
                title,
            ),
        )
        return (
            pk,
            fppPeak,
            fpPeak,
            ip,
            fppInfl,
            fpInfl,
            rm,
            chooch_graph_x,
            chooch_graph_y1,
            chooch_graph_y2,
            title,
        )