예제 #1
0
파일: progressbar.py 프로젝트: kanzy/emzed2
def ProgressBar(n_steps, label="", allow_cancel=False, parent=None):
    """
    Progressbar context manager for showing progress of workflow to user. Example::

        with emzed.gui.ProgressBar(n_steps=100, allow_cancel=True) as handler:
            for i in range(100):

                # we simulate work of step i

                # we update progressbar
                handler.update(i, "step %03d" % i)

                # we can check if user pressed "Cancel" button and stop our "workflow":
                if handler.is_canceled():
                    break
    """

    app = guidata.qapplication()
    dlg = QProgressDialog(parent)
    dlg.setLabelText(label)
    dlg.setAutoClose(False)
    dlg.setAutoReset(False)
    if allow_cancel:
        dlg.setCancelButtonText("Cancel")
    dlg.setMaximum(n_steps)

    class ProgressBarHandler(object):
        def __init__(self, n_steps, dlg):
            self._dlg = dlg
            self._n_steps = n_steps
            self._n = 0
            self._canceled = False
            dlg.canceled.connect(self._set_canceled)
            dlg.setValue(0)

        def _set_canceled(self):
            self._canceled = True
            dlg.close()

        def update(self, n, message=None):
            app.processEvents()
            self._n = n
            dlg.setValue(n + 1)
            if message is not None:
                dlg.setLabelText(message)
            dlg.update()
            app.processEvents()

        def is_canceled(self):
            return self._canceled

    dlg.activateWindow()
    dlg.show()
    dlg.raise_()
    app.processEvents()

    handler = ProgressBarHandler(n_steps, dlg)
    yield handler

    dlg.close()
 def setup_workspace(self):
   umdimage  = os.path.join(self.iso_dir, UMDIMAGE_DAT)
   umdimage2 = os.path.join(self.iso_dir, UMDIMAGE2_DAT)
   voice     = os.path.join(self.iso_dir, VOICE_PAK)
   
   self.generate_directories()
   
   progress = QProgressDialog("", QtCore.QString(), 0, 11000, self)
   progress.setWindowTitle("Setting up workspace...")
   progress.setWindowModality(Qt.Qt.WindowModal)
   progress.setMinimumDuration(0)
   progress.setValue(0)
   progress.setAutoClose(False)
   progress.setAutoReset(False)
   
   progress.setLabelText("Creating directories...")
   
   # Do the easy stuff first.
   if not os.path.isdir(self.changes_dir):
     os.makedirs(self.changes_dir)
   progress.setValue(progress.value() + 1)
   
   if not os.path.isdir(self.backup_dir):
     os.makedirs(self.backup_dir)
   progress.setValue(progress.value() + 1)
   
   if not os.path.isdir(self.editor_data_dir):
     os.makedirs(self.editor_data_dir)
   progress.setValue(progress.value() + 1)
   
   thread_fns = [
     {"target": extract_umdimage, "kwargs": {"filename": umdimage,  "out_dir": self.umdimage_dir,  "eboot": self.eboot_path, "umdimage": UMDIMAGES.umdimage}},
     {"target": extract_umdimage, "kwargs": {"filename": umdimage2, "out_dir": self.umdimage2_dir, "eboot": self.eboot_path, "umdimage": UMDIMAGES.umdimage2}},
     {"target": extract_pak,      "kwargs": {"filename": voice,     "out_dir": self.voice_dir}},
   ]
   
   # Going to capture stdout because I don't feel like
   # rewriting the extract functions to play nice with GUI.
   stdout      = sys.stdout
   sys.stdout  = cStringIO.StringIO()
   
   for thread_fn in thread_fns:
     thread = threading.Thread(**thread_fn)
     thread.start()
     
     while thread.isAlive():
       thread.join(THREAD_TIMEOUT)
       
       output = [line for line in sys.stdout.getvalue().split('\n') if len(line) > 0]
       progress.setValue(progress.value() + len(output))
       if len(output) > 0:
         progress.setLabelText("Extracting %s..." % output[-1])
       
       sys.stdout = cStringIO.StringIO()
   
   sys.stdout = stdout
   
   # Give us an ISO directory for the editor to place modified files in.
   progress.setLabelText("Copying ISO files...")
   
   # ISO directory needs to not exist for copytree.
   if os.path.isdir(self.edited_iso_dir):
     shutil.rmtree(self.edited_iso_dir)
   
   # One more thing we want threaded so it doesn't lock up the GUI.
   thread = threading.Thread(target = shutil.copytree, kwargs = {"src": self.iso_dir, "dst": self.edited_iso_dir})
   thread.start()
   
   while thread.isAlive():
     thread.join(THREAD_TIMEOUT)
     progress.setLabelText("Copying ISO files...")
     # It has to increase by some amount or it won't update and the UI will lock up.
     progress.setValue(progress.value() + 1)
     
   # shutil.copytree(self.iso_dir, self.edited_iso_dir)
   progress.setValue(progress.value() + 1)
   
   # Files we want to make blank, because they're unnecessary.
   blank_files = [
     os.path.join(self.edited_iso_dir, "PSP_GAME", "INSDIR", "UMDIMAGE.DAT"),
     os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "DATA.BIN"),
     os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "EBOOT.BIN"),
     os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "PARAM.SFO"),
   ]
   
   for blank in blank_files:
     with open(blank, "wb") as f:
       pass
   
   # Copy the decrypted EBOOT into the ISO folder and apply our hacks to it.
   progress.setLabelText("Hacking EBOOT...")
   progress.setValue(progress.value() + 1)
   
   hacked_eboot = BitStream(filename = self.eboot_path)
   hacked_eboot, offset = apply_eboot_patches(hacked_eboot)
   with open(os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"), "wb") as f:
     hacked_eboot.tofile(f)
   # shutil.copy(self.eboot_path, os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"))
   
   progress.setLabelText("Extracting editor data...")
   progress.setValue(progress.value() + 1)
   
   # Extract the editor data.
   editor_data = zipfile.ZipFile("data/editor_data.zip", "r")
   editor_data.extractall(self.editor_data_dir)
   editor_data.close()
   
   progress.setValue(progress.maximum())
   progress.close()
   
   self.ui.grpStep4.setEnabled(False)
   self.ui.grpStep5.setEnabled(True)
예제 #3
0
class specread:
    def __init__(self, specfile, startLineNum=0, beamline='APS-15IDC',det='CCD',data={},par={}):
        self.Data=data
        self.Par=par
        self.specfile=specfile
        if beamline=='APS-15IDC':
            self.APS_15IDC(startLineNum=startLineNum,det=det)
        if beamline=='APS-9IDC':
            self.APS_9IDC(startLineNum=startLineNum,det=det)
        
    def updateProgress(self):
        self.progressDialog.setValue(self.progressDialog.value()+1)

    
    
    def APS_15IDC(self,startLineNum=0, det='CCD'):
        """
        Function to read a complete spec File collected at APS 15IDC 
        """
        self.progressDialog=QProgressDialog('Reading scans form SPEC File:','Abort',0,100)
        self.progressDialog.setWindowModality(Qt.WindowModal)
        self.progressDialog.setWindowTitle('Wait')
        self.progressDialog.setAutoClose(True)
        self.progressDialog.setAutoReset(True)
        self.progressDialog.setMinimum(1)
        self.Data['YCol']='Apex2'
        self.Data['NCol']='Monc'
        fid=open(self.specfile)
        fdata=fid.readlines()
        self.SpecFileFull=fdata
        fid.close()
        if fdata[0][:2]!='#F':
            self.Data['NumOfScans']=0
            self.Data['Message']='The file is not a valid specfile!!'
            print 'Error:: The file is not a valid specfile!!'
        else:
            startScanLineNums=[i for i in range(startLineNum,len(fdata)) if fdata[i][:2]=='#S']
            self.progressDialog.setMaximum(len(startScanLineNums))
            self.progressDialog.show()
            self.endLineNum=startScanLineNums[-1]
            if startLineNum>0:
                startScanLineNums=sorted(startScanLineNums)
            numOfScans=len(startScanLineNums)
            scanLines=[fdata[i] for i in startScanLineNums]
            if startLineNum==0:
                tmp=0
                self.Data['NumOfScans']=0#numOfScans
                self.Data['ScanLines']=[]#scanLines
                self.Data['StartScanLineNums']=[]#startScanLineNums
            else:
                tmp=self.Data['NumOfScans']-1
                self.Data['NumOfScans']=self.Data['NumOfScans']-1#+numOfScans
                self.Data['ScanLines']=self.Data['ScanLines'][:-1]#+scanLines[1:]
                self.Data['StartScanLineNums']=self.Data['StartScanLineNums'][:-1]#+startScanLineNums

            for i in range(numOfScans):
                start=startScanLineNums[i]+1
                line=fdata[start]
                i=i+tmp
                self.Data[i]={}
                self.Par[i]={}
                if fdata[start-1].split()[2]=='getandsave_mca' or fdata[start-1].split()[2]=='MCAscanpt':
                    self.Par[i]['Mca']=1
                    self.Data[i]['ScanVar']='Empty'
                else:
                    self.Par[i]['Mca']=0
                tmpdata=[]
                self.Par[i]['CCD']=0
                while line[:2]!='\n' and line[:2]!='#C':
                    if line[:2]=='#P':
                        parName=line[3:].split()
                        start=start+1
                        parValue=map(eval,fdata[start][1:].split())
                        for j in range(len(parName)):
                            self.Par[i][parName[j]]=parValue[j]
                    if line[:2]=='#W':
                        tmppar=line[2:].split()
                        self.Par[i]['Wavelength']=eval(tmppar[1])
                    if line[:3]=='#G0':
                        self.Par[i]['g_l1']=float(line[4:].split()[5])
                        self.Par[i]['g_l2']=float(line[4:].split()[6])
                        self.Par[i]['g_l3']=float(line[4:].split()[7])
                    if line[:2]=='#A':
                        tmppar=line[2:].split()
                        self.Par[i]['Absorber']=eval(tmppar[1])
                    if line[:2]=='#Q':
                        tmppar=line[2:].split()
                        self.Par[i]['Q']=map(eval, tmppar)
                    if line[:3]=='#B0':
                        tmppar=line[3:].split()
                        self.Par[i]['CCD']=1
                    if line[:3]=='#B2':
                        tmppar=map(eval, line[3:].split())
                        self.Par[i]['DBPos']=tmppar[:2]
                        self.Par[i]['S2D_Dist']=tmppar[2]
                        self.Par[i]['S7D_Dist']=tmppar[3]
                    if line[:2]=='#L':
                        scanVar=line[3:-1].split()
                        self.Data[i]['ScanVar']=scanVar
                    if line[0]!='#':
                        tmpdata.append(map(eval, line.split(  )))
                    start=start+1
                    try:
                        line=fdata[start]
                    except:
                        break
                for j in range(len(scanVar)):
                    try:
                        self.Data[i][scanVar[j]]=np.array(tmpdata)[:,j]
                    except:
                        self.Data[i][scanVar[j]]=None
                if len(self.Par[i])==1:
                    self.Par[i]['Message']='No parameters!!'
                self.progressDialog.setLabelText('Reading scans form SPEC File: '+str(i+1))         
                self.updateProgress()
                self.Data['NumOfScans']=i
                self.Data['ScanLines']=self.Data['ScanLines']+[scanLines[i-tmp]]
                self.Data['StartScanLineNums']=self.Data['StartScanLineNums']+[startScanLineNums[i-tmp]]
                self.endLineNum=startScanLineNums[i-tmp]
                if self.progressDialog.wasCanceled()==True:
                    break
        self.progressDialog.hide()
            
                  
    
    def APS_9IDC(self,startLineNum=0, det='CCD'):
        """
        Function to read a complete spec File collected at APS 15IDC 
        """
        self.progressDialog=QProgressDialog('Reading scans form SPEC File:','Abort',0,100)
        self.progressDialog.setWindowModality(Qt.WindowModal)
        self.progressDialog.setWindowTitle('Wait')
        self.progressDialog.setAutoClose(True)
        self.progressDialog.setAutoReset(True)
        self.progressDialog.setMinimum(1)
        self.Data['YCol']='Bicron1'
        self.Data['NCol']='i2'
        fid=open(self.specfile)
        fdata=fid.readlines()
        self.SpecFileFull=fdata
        fid.close()
        if fdata[0][:2]!='#F':
            self.Data['NumOfScans']=0
            self.Data['Message']='The file is not a valid specfile!!'
            print 'Error:: The file is not a valid specfile!!'
        else:
            startScanLineNums=[i for i in range(startLineNum, len(fdata)) if fdata[i][:2]=='#S']
            self.progressDialog.setMaximum(len(startScanLineNums))
            self.progressDialog.show()
            self.endLineNum=startScanLineNums[-1]
            if startLineNum>0:
                startScanLineNums=sorted(startScanLineNums)
            self.Data['StartScanLineNums']=startScanLineNums
            numOfScans=len(self.Data['StartScanLineNums'])
            scanLines=[fdata[i] for i in startScanLineNums]
            if startLineNum==0:
                tmp=0
                self.Data['NumOfScans']=0#numOfScans
                self.Data['ScanLines']=[]#scanLines
                self.Data['StartScanLineNums']=[]#startScanLineNums
                self.Par['ParName']=[]
                for i in range(startScanLineNums[0]):
                    line=fdata[i].split()
                    if fdata[i][:2]=='#O':
                        self.Par['ParName']=self.Par['ParName']+line[1:]
            else:
                tmp=self.Data['NumOfScans']
                self.Data['NumOfScans']=self.Data['NumOfScans']-1#+numOfScans
                self.Data['ScanLines']=self.Data['ScanLines'][:-1]#+scanLines[1:]
                self.Data['StartScanLineNums']=self.Data['StartScanLineNums'][:-1]#+startScanLineNums
            for i in range(numOfScans):
                start=startScanLineNums[i]+1
                line=fdata[start]
                i=i+tmp
                self.Data[i]={}
                self.Par[i]={}
                if fdata[start-1].split()[2]=='getandsave_mca' or fdata[start-1].split()[2]=='MCAscanpt':
                    self.Par[i]['Mca']=1
                    self.Data[i]['ScanVar']='Empty'
                else:
                    self.Par[i]['Mca']=0
                self.Par[i]['CCD']=0
                tmpdata=[]
                pstart=0
                while line[:2]!='\n' and line[:2]!='#C':
                    if line[:2]=='#P':
                        parValue=map(eval,fdata[start].split()[1:])
                        for j in range(len(parValue)):
                            self.Par[i][self.Par['ParName'][pstart]]=parValue[j]
                            pstart=pstart+1
                    if line[:2]=='#Q':
                        tmppar=line[2:].split()
                        self.Par[i]['Q']=map(eval, tmppar)
                    if line[:2]=='#L':
                        scanVar=line[3:-1].split()
                        self.Data[i]['ScanVar']=scanVar
                    if line[0]!='#':
                        tmpdata.append(map(eval, line.split(  )))
                    start=start+1
                    line=fdata[start]
                for j in range(len(scanVar)):
                    try:
                        self.Data[i][scanVar[j]]=np.array(tmpdata)[:,j]
                    except:
                        self.Data[i][scanVar[j]]=None
                if len(self.Par[i])==1:
                    self.Par[i]['Message']='No parameters!!'
                self.progressDialog.setLabelText('Reading scans form SPEC File: '+str(i+1)) 
                self.updateProgress()
                self.Data['NumOfScans']=i
                self.Data['ScanLines']=self.Data['ScanLines']+[scanLines[i-tmp]]
                self.Data['StartScanLineNums']=self.Data['StartScanLineNums']+[startScanLineNums[i-tmp]]
                self.endLineNum=startScanLineNums[i-tmp]
                if self.progressDialog.wasCanceled()==True:
                    break
        self.progressDialog.hide()
    def setup_workspace(self):
        data0 = os.path.join(self.iso_dir, DATA0_CPK)

        self.generate_directories()

        progress = QProgressDialog("", QtCore.QString(), 0, 11000, self)
        progress.setWindowTitle("Setting up workspace...")
        progress.setWindowModality(Qt.Qt.WindowModal)
        progress.setMinimumDuration(0)
        progress.setValue(0)
        progress.setAutoClose(False)
        progress.setAutoReset(False)

        progress.setLabelText("Creating directories...")

        # Do the easy stuff first.
        if not os.path.isdir(self.changes_dir):
            os.makedirs(self.changes_dir)
        progress.setValue(progress.value() + 1)

        if not os.path.isdir(self.backup_dir):
            os.makedirs(self.backup_dir)
        progress.setValue(progress.value() + 1)

        thread_fns = [{"target": extract_cpk, "kwargs": {"filename": data0, "out_dir": self.data0_dir}}]

        # Going to capture stdout because I don't feel like
        # rewriting the extract functions to play nice with GUI.
        stdout = sys.stdout
        sys.stdout = cStringIO.StringIO()

        for thread_fn in thread_fns:
            thread = threading.Thread(**thread_fn)
            thread.start()

            while thread.isAlive():
                thread.join(THREAD_TIMEOUT)

                output = [line for line in sys.stdout.getvalue().split("\n") if len(line) > 0]
                progress.setValue(progress.value() + len(output))
                if len(output) > 0:
                    progress.setLabelText("Extracting %s..." % output[-1])

                sys.stdout = cStringIO.StringIO()

        sys.stdout = stdout

        # Give us an ISO directory for the editor to place modified files in.
        progress.setLabelText("Copying ISO files...")

        # ISO directory needs to not exist for copytree.
        if os.path.isdir(self.edited_iso_dir):
            shutil.rmtree(self.edited_iso_dir)

        # One more thing we want threaded so it doesn't lock up the GUI.
        thread = threading.Thread(target=shutil.copytree, kwargs={"src": self.iso_dir, "dst": self.edited_iso_dir})
        thread.start()

        while thread.isAlive():
            thread.join(THREAD_TIMEOUT)
            progress.setLabelText("Copying ISO files...")
            # It has to increase by some amount or it won't update and the UI will lock up.
            progress.setValue(progress.value() + 1)

        # shutil.copytree(self.iso_dir, self.edited_iso_dir)
        progress.setValue(progress.value() + 1)

        # Files we want to make blank, because they're unnecessary.
        blank_files = [
            os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "DATA.BIN"),
            os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "EBOOT.BIN"),
            os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "UPDATE", "PARAM.SFO"),
        ]

        for blank in blank_files:
            with open(blank, "wb") as f:
                pass

        # Copy the decrypted EBOOT into the ISO folder and apply our hacks to it.
        progress.setLabelText("Hacking EBOOT...")
        progress.setValue(progress.value() + 1)

        hacked_eboot = BitStream(filename=self.eboot_path)
        hacked_eboot = apply_eboot_patches(hacked_eboot)
        with open(os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"), "wb") as f:
            hacked_eboot.tofile(f)
        # shutil.copy(self.eboot_path, os.path.join(self.edited_iso_dir, "PSP_GAME", "SYSDIR", "EBOOT.BIN"))

        progress.setLabelText("Extracting editor data...")
        progress.setValue(progress.value() + 1)

        # Extract the editor data.
        editor_data = zipfile.ZipFile("data/editor_data.zip", "r")
        editor_data.extractall(self.editor_data_dir)
        editor_data.close()

        progress.setValue(progress.maximum())
        progress.close()

        self.ui.grpStep4.setEnabled(False)
        self.ui.grpStep5.setEnabled(True)
class specread:
    def __init__(self,
                 specfile,
                 startLineNum=0,
                 endScanNum=0,
                 beamline='APS-15IDC',
                 det='CCD',
                 data={},
                 par={}):
        self.Data = data
        self.Par = par
        self.specfile = specfile
        if beamline == 'APS-15IDC':
            self.APS_15IDC(startLineNum=startLineNum,
                           endScanNum=endScanNum,
                           det=det)
        if beamline == 'APS-9IDC':
            self.APS_9IDC(startLineNum=startLineNum,
                          endScanNum=endScanNum,
                          det=det)

    def updateProgress(self):
        self.progressDialog.setValue(self.progressDialog.value() + 1)

    def APS_15IDC(self, startLineNum=0, endScanNum=0, det='CCD'):
        """
        Function to read a complete spec File collected at APS 15IDC 
        """
        self.progressDialog = QProgressDialog('Reading scans form SPEC File:',
                                              'Abort', 0, 100)
        self.progressDialog.setWindowModality(Qt.WindowModal)
        self.progressDialog.setWindowTitle('Wait')
        self.progressDialog.setAutoClose(True)
        self.progressDialog.setAutoReset(True)
        self.progressDialog.setMinimum(1)
        self.Data['YCol'] = 'Apex2'
        self.Data['NCol'] = 'Monc'
        fid = open(self.specfile)
        fdata = fid.readlines()
        self.SpecFileFull = fdata
        fid.close()
        if fdata[0][:2] != '#F':
            self.Data['NumOfScans'] = 0
            self.Data['Message'] = 'The file is not a valid specfile!!'
            print 'Error:: The file is not a valid specfile!!'
        else:
            startScanLineNums = [
                i for i in range(startLineNum, len(fdata))
                if fdata[i][:2] == '#S'
            ]
            self.progressDialog.setMaximum(len(startScanLineNums))
            self.progressDialog.show()
            if startLineNum > 0:
                startScanLineNums = sorted(startScanLineNums)
            numOfScans = len(startScanLineNums)
            scanLines = [fdata[i] for i in startScanLineNums]
            if startLineNum == 0:
                tmp = 0
                self.Data['NumOfScans'] = 0  #numOfScans
                self.Data['ScanNums'] = []
                offset = 0
#                self.Data['ScanLines']=[]#scanLines
#                self.Data['StartScanLineNums']=[]#startScanLineNums
            else:
                tmp = self.Data['NumOfScans']
                self.Data[
                    'NumOfScans'] = self.Data['NumOfScans'] - 1  #+numOfScans
                offset = 1
#                self.Data['ScanLines']=self.Data['ScanLines'][:-1]#+scanLines[1:]
#                self.Data['StartScanLineNums']=self.Data['StartScanLineNums'][:-1]#+startScanLineNums
            if int(scanLines[-1].split()
                   [1]) != len(startScanLineNums) + endScanNum - offset:
                print len(
                    startScanLineNums), scanLines[-1].split()[1], endScanNum
                self.Data['Error'] = True
                self.Data['Message'] = 'There are identical scans in the file'
            else:
                self.Data['Error'] = False
            for i in range(numOfScans):
                start = startScanLineNums[i] + 1
                line = fdata[start]
                num = int(fdata[startScanLineNums[i]].split()[1])
                i = i + tmp
                self.Data[num] = {}
                self.Par[num] = {}
                if fdata[start - 1].split()[2] == 'getandsave_mca':
                    self.Par[num]['Detector'] = 'Vortex'
                    self.Data[num]['ScanVar'] = 'Empty'
                else:
                    self.Par[num]['Detector'] = 'Monitor'
                tmpdata = []
                while line[:2] != '\n' and line[:2] != '#C':
                    if line[:2] == '#P':
                        parName = line[4:].split()
                        start = start + 1
                        parValue = map(eval, fdata[start][1:].split())
                        for j in range(len(parName)):
                            self.Par[num][parName[j]] = parValue[j]
                    if line[:2] == '#W':
                        tmppar = line[2:].split()
                        self.Par[num]['Wavelength'] = eval(tmppar[1])
                    if line[:3] == '#G0':
                        self.Par[num]['g_l1'] = float(line[4:].split()[5])
                        self.Par[num]['g_l2'] = float(line[4:].split()[6])
                        self.Par[num]['g_l3'] = float(line[4:].split()[7])
                    if line[:2] == '#A':
                        tmppar = line[2:].split()
                        self.Par[num]['Absorber'] = eval(tmppar[1])
                    if line[:2] == '#Q':
                        tmppar = line[2:].split()
                        self.Par[num]['Q'] = map(eval, tmppar)
                    if line[:2] == '#V':
                        self.Par[num]['Detector'] = 'Vortex'
                    if line[:3] == '#B0':
                        tmppar = line[3:].split('.')
                        self.Par[num]['ImageNumber'] = len(
                            line[3:].split('_')[-1].split('.')[0])
                        if tmppar[1] == 'tif\n':
                            self.Par[num]['Detector'] = 'Pilatus'
                        elif tmppar[1] == 'sfrm\n':
                            self.Par[num]['Detector'] = 'Bruker'
                    if line[:3] == '#B1':
                        try:
                            tmppar = map(eval, line[3:].split())
                        except:
                            tmppar = map(eval, line[3:].split()[:-1])
                        self.Par[num]['DBPos'] = tmppar[:2]
                        self.Par[num]['S2D_Dist'] = tmppar[2]
                        self.Par[num]['S7D_Dist'] = tmppar[3]
                    if line[:3] == '#B2':
                        tmppar = map(eval, line[3:].split())
                        self.Par[num]['DBPos'] = tmppar[:2]
                        self.Par[num]['S2D_Dist'] = tmppar[2]
                        self.Par[num]['S7D_Dist'] = tmppar[3]
                    if line[:2] == '#L':
                        scanVar = line[3:-1].split()
                        self.Data[num]['ScanVar'] = scanVar
                    if line[0] != '#':
                        try:
                            tmpdata.append(map(eval, line.split()))
                        except:
                            self.Data[num][
                                'Message'] = 'Something wrong with Scan Number %d', num, '.Please check the the scan in the specfile.'
                            print 'Something wrong with Scan Number %d', num
                    start = start + 1
                    try:
                        line = fdata[start]
                    except:
                        break
                if self.Data[num]['ScanVar'] != 'Empty':
                    for j in range(len(scanVar)):
                        try:
                            self.Data[num][scanVar[j]] = np.array(
                                tmpdata, dtype='float')[:, j]
                        except:
                            self.Data[num][scanVar[j]] = None
                if len(self.Par[num]) == 1:
                    self.Par[num]['Message'] = 'No parameters!!'
                self.progressDialog.setLabelText('Reading Scan #' + str(num))
                self.updateProgress()
                self.Data['NumOfScans'] = num
                #                self.Data['ScanLines']=self.Data['ScanLines']+[scanLines[num-tmp]]
                self.Data[num]['ScanLine'] = fdata[startScanLineNums[i - tmp]]
                self.Data[num]['StartScanLineNum'] = startScanLineNums[i - tmp]
                self.endLineNum = startScanLineNums[i - tmp]
                self.Data['ScanNums'].append(num)
                if self.progressDialog.wasCanceled() == True:
                    break
        self.progressDialog.hide()

    def APS_9IDC(self, startLineNum=0, endScanNum=0, det='CCD'):
        """
        Function to read a complete spec File collected at APS 9IDC 
        """
        self.progressDialog = QProgressDialog('Reading scans form SPEC File:',
                                              'Abort', 0, 100)
        self.progressDialog.setWindowModality(Qt.WindowModal)
        self.progressDialog.setWindowTitle('Wait')
        self.progressDialog.setAutoClose(True)
        self.progressDialog.setAutoReset(True)
        self.progressDialog.setMinimum(1)
        self.Data['YCol'] = 'Bicron1'
        self.Data['NCol'] = 'i2'
        fid = open(self.specfile)
        fdata = fid.readlines()
        self.SpecFileFull = fdata
        fid.close()
        if fdata[0][:2] != '#F':
            self.Data['NumOfScans'] = 0
            self.Data['Message'] = 'The file is not a valid specfile!!'
            print 'Error:: The file is not a valid specfile!!'
        else:
            startScanLineNums = [
                i for i in range(startLineNum, len(fdata))
                if fdata[i][:2] == '#S'
            ]
            self.progressDialog.setMaximum(len(startScanLineNums))
            self.progressDialog.show()
            self.endLineNum = startScanLineNums[-1]
            if startLineNum > 0:
                startScanLineNums = sorted(startScanLineNums)
            self.Data['StartScanLineNums'] = startScanLineNums
            numOfScans = len(self.Data['StartScanLineNums'])
            scanLines = [fdata[i] for i in startScanLineNums]
            if startLineNum == 0:
                tmp = 0
                self.Data['NumOfScans'] = 0  #numOfScans
                self.Data['ScanLines'] = []  #scanLines
                self.Data['StartScanLineNums'] = []  #startScanLineNums
                self.Par['ParName'] = []
                for i in range(startScanLineNums[0]):
                    line = fdata[i].split()
                    if fdata[i][:2] == '#O':
                        self.Par['ParName'] = self.Par['ParName'] + line[1:]
            else:
                tmp = self.Data['NumOfScans']
                self.Data[
                    'NumOfScans'] = self.Data['NumOfScans'] - 1  #+numOfScans
                self.Data['ScanLines'] = self.Data[
                    'ScanLines'][:-1]  #+scanLines[1:]
                self.Data['StartScanLineNums'] = self.Data[
                    'StartScanLineNums'][:-1]  #+startScanLineNums
            for i in range(numOfScans):
                start = startScanLineNums[i] + 1
                line = fdata[start]
                i = i + tmp
                self.Data[i] = {}
                self.Par[i] = {}
                if fdata[start - 1].split()[2] == 'getandsave_mca' or fdata[
                        start - 1].split()[2] == 'MCAscanpt':
                    self.Par[i]['Mca'] = 1
                    self.Data[i]['ScanVar'] = 'Empty'
                else:
                    self.Par[i]['Mca'] = 0
                self.Par[i]['CCD'] = 0
                tmpdata = []
                pstart = 0
                while line[:2] != '\n' and line[:2] != '#C':
                    if line[:2] == '#P':
                        parValue = map(eval, fdata[start].split()[1:])
                        for j in range(len(parValue)):
                            self.Par[i][self.Par['ParName']
                                        [pstart]] = parValue[j]
                            pstart = pstart + 1
                    if line[:2] == '#Q':
                        tmppar = line[2:].split()
                        self.Par[i]['Q'] = map(eval, tmppar)
                    if line[:2] == '#L':
                        scanVar = line[3:-1].split()
                        self.Data[i]['ScanVar'] = scanVar
                    if line[0] != '#':
                        tmpdata.append(map(eval, line.split()))
                    start = start + 1
                    line = fdata[start]
                for j in range(len(scanVar)):
                    try:
                        self.Data[i][scanVar[j]] = np.array(tmpdata)[:, j]
                    except:
                        self.Data[i][scanVar[j]] = None
                if len(self.Par[i]) == 1:
                    self.Par[i]['Message'] = 'No parameters!!'
                self.progressDialog.setLabelText(
                    'Reading scans form SPEC File: ' + str(i + 1))
                self.updateProgress()
                self.Data['NumOfScans'] = i
                self.Data['ScanLines'] = self.Data['ScanLines'] + [
                    scanLines[i - tmp]
                ]
                self.Data['StartScanLineNums'] = self.Data[
                    'StartScanLineNums'] + [startScanLineNums[i - tmp]]
                self.endLineNum = startScanLineNums[i - tmp]
                if self.progressDialog.wasCanceled() == True:
                    break
        self.progressDialog.hide()
예제 #6
0
def ProgressBar(n_steps, label="", allow_cancel=False, parent=None):
    """
    Progressbar context manager for showing progress of workflow to user. Example::

        with emzed.gui.ProgressBar(n_steps=100, allow_cancel=True) as handler:
            for i in range(100):

                # we simulate work of step i

                # we update progressbar
                handler.update(i, "step %03d" % i)

                # we can check if user pressed "Cancel" button and stop our "workflow":
                if handler.is_canceled():
                    break
    """

    app = guidata.qapplication()
    dlg = QProgressDialog(parent)
    dlg.setLabelText(label)
    dlg.setAutoClose(False)
    dlg.setAutoReset(False)
    if allow_cancel:
        dlg.setCancelButtonText("Cancel")
    dlg.setMaximum(n_steps)

    class ProgressBarHandler(object):

        def __init__(self, n_steps, dlg):
            self._dlg = dlg
            self._n_steps = n_steps
            self._n = 0
            self._canceled = False
            dlg.canceled.connect(self._set_canceled)
            dlg.setValue(0)

        def _set_canceled(self):
            self._canceled = True
            dlg.close()

        def update(self, n, message=None):
            app.processEvents()
            self._n = n
            dlg.setValue(n + 1)
            if message is not None:
                dlg.setLabelText(message)
            dlg.update()
            app.processEvents()

        def is_canceled(self):
            return self._canceled

    dlg.activateWindow()
    dlg.show()
    dlg.raise_()
    app.processEvents()

    handler = ProgressBarHandler(n_steps, dlg)
    yield handler

    dlg.close()