Changeset 1234


Ignore:
Timestamp:
Mar 1, 2013 3:46:05 PM (9 years ago)
Author:
jemian
Message:

contribute user requests to save all MDA files in a chosen directory
make more robust against exceptions
suppress most unnecessary output
note: mda.py support has many print statements!

Location:
mda2idd_report/src
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • mda2idd_report/src/mda2idd_gui.py

    r1233 r1234  
    1515Browse to a directory containing MDA files.
    1616Select one.  A summary will be shown.
    17 Choose   File --> Save  (or ^S)
    18 to write an ASCII text file.
     17Choose:
     18* File --> Save  (or ^S)  to convert selected MDA file to an ASCII text file.
     19* File --> Convert entire Directory (^D) to convert all MDA files
    1920
    2021For now, only `*.mda` files may be browsed.
    2122ASCII text files will be written to directory: ../ASCII/
    2223(relative to the MDA file directory)
     24
     25Features
     26-----------
     27
     28* presents file system list
     29* adds directory picker dialog and text entry box
     30* preview brief header or full summary of MDA file
     31* convert one selected MDA file to ASCII
     32* convert entire directory of MDA files to ASCII
    2333'''
    2434
     
    3545import optparse
    3646import datetime
     47import glob
    3748import platform
    3849import os
     
    6576        self.startup_complete = False
    6677        self.selectedMdaFile = None
    67         self.dirty = False
    6878        self.preferences_file = self.GetDefaultPreferencesFileName()
    6979        self.mrud = []      # most-recently-used directories
     
    7888        self.SetPosition(wx.Point(self.prefs['pos_h'], self.prefs['pos_v']))
    7989        self.splitter1.SetSashPosition(self.prefs['sash_pos'], True)
    80         summary = self.prefs['short_summary']
    8190        self.menu_file.Check(self.id_menu_report, self.prefs['short_summary'])
     91
    8292        self.update_mrud_menus()
    83        
    8493        self.setStatusText('preferences file: ' + self.preferences_file)
    8594        self.setSummaryText('')
     
    93102        self.id_menu_report  = 1 + id_menu_save
    94103        id_menu_mrud  = 1 + self.id_menu_report
     104        id_menu_convert_all  = 1 + id_menu_mrud
    95105
    96106        self.menu_file = wx.Menu(title='')
     
    98108                              help=u'Save MDA data to ASCII text file')
    99109        self.Bind(wx.EVT_MENU, self.OnMenuFileItemSave, id=id_menu_save)
     110
     111        self.menu_file.Append(text=u'Convert entire &Directory\tCtrl+D', id=id_menu_convert_all,
     112                              help=u'Convert all MDA files in current directory to ASCII text files')
     113        self.Bind(wx.EVT_MENU, self.OnConvertAll, id=id_menu_convert_all)
     114       
    100115        self.menu_file.AppendSeparator()
    101116        self.menu_file.AppendCheckItem(text=u'Brief &Report\tCtrl+R', id=self.id_menu_report,
     
    116131                              help=u'Most Recently Used Directories')
    117132        self.menu_file.Enable(id_menu_mrud, False)
    118        
     133        self.mrud_insertion_pos = self.menu_file.GetMenuItemCount()
    119134        self.menu_file.AppendSeparator()
     135       
    120136        self.menu_file.Append(text=u'E&xit', id=id_menu_exit,
    121137                              help=u'Quit this application')
     
    170186        tree = self.dir.GetTreeCtrl()
    171187
    172         wx.EVT_TREE_SEL_CHANGED(self, tree.GetId(), self.OnSelect)
     188        wx.EVT_TREE_SEL_CHANGED(self, tree.GetId(), self.OnSelectTreeCtrlItem)
    173189        wx.EVT_SPLITTER_SASH_POS_CHANGED(self, self.splitter1.GetId(), self.OnSashMoved)
    174190        #self.Bind(wx.EVT_SIZE, self.OnWindowGeometryChanged)
     
    203219        self.writePreferences()
    204220       
    205     def OnSelect(self, event):
    206         '''user selected something in the directory list'''
     221    def OnSelectTreeCtrlItem(self, event):
     222        '''user selected something in the directory list tree control'''
    207223        if not isinstance(event, wx.Event):
    208224            self.setStatusText( "Not an event: %s" % str(event) )
     
    224240                    self.dirPicker.SetPath( path )
    225241            if os.path.isdir(selectedItem):
    226                 self.prefs['start_dir'] = selectedItem
    227                 self.update_mrud(selectedItem)
     242                # must select a valid MDA file to join the MRUD list!
     243                #self.prefs['start_dir'] = selectedItem
     244                #self.update_mrud(selectedItem)
    228245                self.dirPicker.SetPath( selectedItem )
    229246            self.writePreferences()
     
    277294        #self.textCtrl1.Clear()
    278295        #self.textCtrl1.AppendText(str(text))
    279         #self.textCtrl1.SetSelection(0,0)       # SetSelection() not working on Linux!
     296        #self.textCtrl1.SetSelection(0,0)    # SetSelection() not working on Linux!
    280297        self.textCtrl1.ChangeValue(str(text))
     298   
     299    def appendSummaryText(self, text):
     300        '''post new text to the summary TextCtrl, appending to any existing text'''
     301        self.textCtrl1.AppendText(str(text))
    281302   
    282303    def setStatusText(self, text):
     
    332353                self.prefs['short_summary'] = node is None or 'true' == node.text.strip().lower()
    333354                self.prefs['start_dir'] = root.find('starting_directory').text.strip()
    334                    
    335355
    336356    def writePreferences(self):
     
    388408                    f.write(xmlText)
    389409                    f.close()
    390        
    391410   
    392411    def update_mrud(self, newdir):
    393         '''list of most-recently-used directories'''
     412        '''MRUD: list of most-recently-used directories'''
    394413        if newdir in self.mrud:
    395414            if self.mrud[0] == newdir:
     
    401420       
    402421        self.update_mrud_menus()
    403        
    404422   
    405423    def update_mrud_menus(self):
    406424        '''manage the MRUD menu items'''
    407         # TODO: this is too complicated -- save the MRUD menu details to avoid the search
    408         mrud_pos = None     # need to know the insertion point in the menu
     425       
    409426        if len(self.mrud) > 0:
     427       
    410428            # remove old MRUD items
    411             # look for items just after "MRUD list"
    412             signal = False
    413             for counter, item in enumerate(self.menu_file.GetMenuItems()):
    414                 if item.GetKind() == wx.ITEM_NORMAL:
    415                     if signal:
    416                         self.menu_file.Delete(item.GetId())     # remove any old MRUD items
    417                     if item.GetItemLabel() == 'MRUD list':
    418                         signal = True   # trigger next item(s) for removal
    419                         mrud_pos = counter
    420                 else:
    421                     if signal:
    422                         signal = False
    423                         break
    424                     signal = False      # no more items
     429            # look for items just after "MRUD list" until the separator
     430            item = self.menu_file.FindItemByPosition(self.mrud_insertion_pos)
     431            while item.GetKind() != wx.ITEM_SEPARATOR:
     432                #label = item.GetLabel()
     433                self.menu_file.Delete(item.GetId())
     434                item = self.menu_file.FindItemByPosition(self.mrud_insertion_pos)
     435
    425436            # add new MRUD items
    426             if mrud_pos is not None:
    427                 for counter, dir in enumerate(self.mrud):
    428                     if os.path.exists(dir):
    429                         text = '%s\tCtrl+%d' % (dir, counter+1)
    430                         self.menu_file.Insert(mrud_pos+counter+1, wx.ID_ANY, text=text)
    431                         id = self.menu_file.FindItem(text)
    432                         self.Bind(wx.EVT_MENU, self.OnMrudItem, id=id)
     437            counter = 0
     438            for path in self.mrud:
     439                if os.path.exists(path):
     440                    text = '%s\tCtrl+%d' % (path, counter+1)
     441                    position = self.mrud_insertion_pos + counter
     442                    self.menu_file.Insert(position, wx.ID_ANY, text=text)
     443                    item_id = self.menu_file.FindItem(text)
     444                    self.Bind(wx.EVT_MENU, self.OnMrudItem, id=item_id)
     445                    counter += 1
    433446       
    434447    def OnMrudItem(self, event):
    435448        '''handle MRUD menu items'''
    436         id = event.GetId()
    437449        label = self.menu_file.GetLabelText(event.GetId())
    438450        self.setCurrentDirectory(label)
     
    446458        info.Name = sys.argv[0]
    447459        info.Version = __version__
    448         #info.Copyright = version.__copyright__
    449         #info.Copyright = __svnid__
    450460        info.Description = __doc__
    451461        URL = __url__
    452462        info.WebSite = (URL, __svnid__)
    453463        author = __author__ +  " <" + __author_email__ + ">"
    454         others = [ "author: ", author ]
     464        info.Developers = ['main author: ' + author,
     465                           'MDA support: Time Mooney <mooney@aps.anl.gov>']
    455466        # Then we call wx.AboutBox giving it the info object
    456467        wx.AboutBox(info)
     468       
     469    def OnConvertAll(self, event):
     470        '''selected the "ConvertAll" menu item'''
     471        # use path from self.dirPicker widget
     472        #path = self.prefs['start_dir']
     473        path = self.dirPicker.GetPath()
     474        self.setStatusText('Converting all MDA files to ASCII in directory: ' + path)
     475        self.convertMdaDir(path)
     476       
     477    def convertMdaDir(self, path):
     478        '''convert all MDA files in a given directory'''
     479        if not os.path.exists(path):
     480            self.setSummaryText('non-existent path: ' + path)
     481            return
     482        fileList = glob.glob(os.path.join(path, '*.mda'))
     483        if len(fileList) == 0:
     484            self.setSummaryText('No MDA files to convert in directory: ' + path)
     485            return
     486        self.setSummaryText('Converting these files:\n')
     487        for mdaFile in fileList:
     488            try:
     489                answer = mda2idd_report.report(mdaFile, allowException=True)
     490                msg = ''
     491                for k, v in answer.items():
     492                    msg += '\n* ' + k + ' --> ' + str(v)
     493            except (mda2idd_report.ReadMdaException, mda2idd_report.RankException) as answer:
     494                msg = '\n* ' + mdaFile + ': ' + str(answer)
     495            self.appendSummaryText(msg)
    457496
    458497
     
    466505    # , version=__svnid__
    467506    # also: -h gets a help / usage message
    468     options, args = parser.parse_args()
     507    options = parser.parse_args()[0]  # ignore any args
    469508    fresh_start = options.start_fresh
    470509
  • mda2idd_report/src/mda2idd_report.py

    r1231 r1234  
    1414text file format produced by ``yca scanSee_report`` (a
    1515Yorick-based support).
     16
    1617
    1718Main Methods
     
    150151
    151152
    152 def report(mdaFileName):
     153class ReadMdaException(Exception):
     154    '''MDA files are all version 1.3 (+/- 0.01)'''
     155    pass
     156
     157
     158class RankException(Exception):
     159    '''this report can only handle ranks 1 and 2'''
     160    pass
     161
     162
     163def report(mdaFileName, allowException=False):
    153164    '''
    154165    converts MDA file to 1 or more ASCII text files, based on the rank
     
    158169    '''
    159170    converted = {}
    160     if os.path.exists(mdaFileName):
    161         asciiPath = getAsciiPath(mdaFileName)
    162    
    163         data = mda.readMDA(mdaFileName)
    164         rank = data[0]['rank']
    165    
    166         if rank in (1, 2):
    167             if len(data[0]['acquired_dimensions']) == rank:
    168                 method = {1: report_1d, 2: report_2d}[rank]
    169                 for key, value in method(data).items():
    170                     writeOutput(asciiPath, key, value)
    171                     if mdaFileName not in converted:
    172                         converted[mdaFileName] = []
    173                     converted[mdaFileName].append( os.path.join(asciiPath, key) )
     171    if not os.path.exists(mdaFileName):
     172        return converted
     173
     174    asciiPath = getAsciiPath(mdaFileName)
     175
     176    data = mda.readMDA(mdaFileName)
     177    if data is None:
     178        msg = "could not read data from MDA file: " + mdaFileName
     179        if allowException:
     180            raise ReadMdaException, msg
    174181        else:
    175             print '%d-D data: not handled by this code' % rank
     182            print msg
     183        return converted
     184       
     185    rank = data[0]['rank']
     186
     187    if rank in (1, 2):
     188        if len(data[0]['acquired_dimensions']) == rank:
     189            method = {1: report_1d, 2: report_2d}[rank]
     190            for key, value in method(data).items():
     191                writeOutput(asciiPath, key, value)
     192                if mdaFileName not in converted:
     193                    converted[mdaFileName] = []
     194                converted[mdaFileName].append( os.path.join(asciiPath, key) )
     195    else:
     196        msg = '%d-D data: not handled by this code' % rank
     197        if allowException:
     198            raise RankException, msg
     199        else:
     200            print msg
     201               
    176202    return converted
    177203
Note: See TracChangeset for help on using the changeset viewer.