Ignore:
Timestamp:
Apr 17, 2017 2:39:50 PM (7 years ago)
Author:
krzywon
Branches:
master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.2.2, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
8ffafd1
Parents:
beba407
git-author:
Jeff Krzywon <krzywon@…> (04/17/17 14:39:50)
git-committer:
krzywon <krzywon@…> (04/17/17 14:39:50)
Message:

Refactor ASCII reader to use FileReader? class.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • src/sas/sascalc/dataloader/file_reader_base_class.py

    rbeba407 rb09095a  
    11""" 
    2 This is the base file reader class all file readers should inherit from. 
     2This is the base file reader class most file readers should inherit from. 
    33All generic functionality required for a file loader/reader is built into this 
    44class 
     
    77import os 
    88import logging 
     9import numpy as np 
    910from abc import abstractmethod 
    1011from loader_exceptions import NoKnownLoaderException, FileContentsException,\ 
     
    1920    # List of Data1D and Data2D objects to be sent back to data_loader 
    2021    output = [] 
    21     # Current plottable1D/2D object being loaded in 
     22    # Current plottable_(1D/2D) object being loaded in 
    2223    current_dataset = None 
    23     # Current DataInfo objecct being loaded in 
     24    # Current DataInfo object being loaded in 
    2425    current_datainfo = None 
    25     # Wildcards 
    26     type = ["Text files (*.txt)"] 
     26    # String to describe the type of data this reader can load 
     27    type_name = "ASCII" 
     28    # Wildcards to display 
     29    type = ["Text files (*.txt|*.TXT)"] 
    2730    # List of allowed extensions 
    2831    ext = ['.txt'] 
    2932    # Bypass extension check and try to load anyway 
    3033    allow_all = False 
     34    # Able to import the unit converter 
     35    has_converter = True 
     36    # Open file handle 
     37    f_open = None 
     38    # Default value of zero 
     39    _ZERO = 1e-16 
    3140 
    3241    def read(self, filepath): 
     
    4251                # Try to load the file, but raise an error if unable to. 
    4352                try: 
    44                     input_f = open(filepath, 'rb') 
    45                     self.get_file_contents(input_f) 
     53                    self.unit_converter() 
     54                    self.f_open = open(filepath, 'rb') 
     55                    self.get_file_contents() 
     56                    self.sort_one_d_data() 
    4657                except RuntimeError: 
     58                    # Reader specific errors 
     59                    # TODO: Give a specific error. 
    4760                    pass 
    4861                except OSError as e: 
     62                    # If the file cannot be opened 
    4963                    msg = "Unable to open file: {}\n".format(filepath) 
    5064                    msg += e.message 
    5165                    self.handle_error_message(msg) 
    5266                except Exception as e: 
    53                     self.handle_error_message(e.message) 
     67                    # Handle any other generic error 
     68                    # TODO: raise or log? 
     69                    raise 
     70                finally: 
     71                    if not self.f_open.closed: 
     72                        self.f_open.close() 
    5473        else: 
    5574            msg = "Unable to find file at: {}\n".format(filepath) 
    5675            msg += "Please check your file path and try again." 
    5776            self.handle_error_message(msg) 
    58         # Return a list of parsed entries that dataloader can manage 
     77        # Return a list of parsed entries that data_loader can manage 
    5978        return self.output 
    6079 
     
    7998        self.output.append(data_obj) 
    8099 
     100    def unit_converter(self): 
     101        """ 
     102        Generic unit conversion import  
     103        """ 
     104        # Check whether we have a converter available 
     105        self.has_converter = True 
     106        try: 
     107            from sas.sascalc.data_util.nxsunit import Converter 
     108        except: 
     109            self.has_converter = False 
     110 
     111    def sort_one_d_data(self): 
     112        """ 
     113        Sort 1D data along the X axis for consistency 
     114        """ 
     115        final_list = [] 
     116        for data in self.output: 
     117            if isinstance(data, Data1D): 
     118                ind = np.lexsort((data.y, data.x)) 
     119                data.x = np.asarray([data.x[i] for i in ind]) 
     120                data.y = np.asarray([data.y[i] for i in ind]) 
     121                if data.dx is not None: 
     122                    data.dx = np.asarray([data.dx[i] for i in ind]) 
     123                if data.dxl is not None: 
     124                    data.dxl = np.asarray([data.dxl[i] for i in ind]) 
     125                if data.dxw is not None: 
     126                    data.dxw = np.asarray([data.dxw[i] for i in ind]) 
     127                if data.dy is not None: 
     128                    data.dy = np.asarray([data.dy[i] for i in ind]) 
     129                if data.lam is not None: 
     130                    data.lam = np.asarray([data.lam[i] for i in ind]) 
     131                if data.dlam is not None: 
     132                    data.dlam = np.asarray([data.dlam[i] for i in ind]) 
     133            final_list.append(data) 
     134        self.output = final_list 
     135 
     136    @staticmethod 
     137    def splitline(line): 
     138        """ 
     139        Splits a line into pieces based on common delimeters 
     140        :param line: A single line of text 
     141        :return: list of values 
     142        """ 
     143        # Initial try for CSV (split on ,) 
     144        toks = line.split(',') 
     145        # Now try SCSV (split on ;) 
     146        if len(toks) < 2: 
     147            toks = line.split(';') 
     148        # Now go for whitespace 
     149        if len(toks) < 2: 
     150            toks = line.split() 
     151        return toks 
     152 
    81153    @abstractmethod 
    82     def get_file_contents(self, contents): 
     154    def get_file_contents(self): 
    83155        """ 
    84         All reader classes that inherit from here should implement 
    85         :param contents:  
     156        All reader classes that inherit from FileReader must implement 
    86157        """ 
    87158        pass 
Note: See TracChangeset for help on using the changeset viewer.