<commit_before>import base
import util
import header
import copy
import os

class File(object):
    ''' Base file object in laspy. Provides access to most laspy functionality,
    and holds references to the HeaderManager, Reader, and potentially Writer objects. 
    '''
    def __init__(self, filename,
                       header=None,
                       vlrs=False,
                       mode='r',
                       in_srs=None,
                       out_srs=None,
                       evlrs = False):
        '''Instantiate a file object to represent an LAS file.

        :arg filename: The filename to open
        :keyword header: A header open the file with. Not required in modes "r" and "rw"
        :type header: a :obj:`laspy.header.Header` instance
        :keyword mode: "r" for read, "rw" for modify/update, "w" for write, and "w+" for append (not implemented)
        :type mode: string
        :keyword in_srs: Input SRS to override the existing file's SRS with (not implemented)
        :type in_srs: a :obj:`laspy.SRS` instance
        :keyword out_srs: Output SRS to reproject points on-the-fly to as \
        they are read/written. (not implemented)
        :type out_srs: a :obj:`laspy.SRS` instance (not implemented)

        .. note::
            To open a file in write mode, you must provide a
            laspy.header.Header instance which will be immediately written to
            the file. If you provide a header instance in read mode, the
            values of that header will be used in place of those in the actual
            file.

        .. note::
            If a file is open for write, it cannot be opened for read and vice
            versa.

        >>> from laspy import file
        >>> f = file.File('file.las', mode='r')
        >>> for p in f:
        ...     print 'X,Y,Z: ', p.x, p.y, p.z

        >>> h = f.header
        >>> f2 = file.File('file2.las', mode = "w", header=h)
        >>> points = f.points
        >>> f2.points = points
        >>> f2.close()
        '''

        self.filename = os.path.abspath(filename)
        self._header = header
        self._vlrs = vlrs
        self._evlrs = evlrs
        self._mode = mode.lower()
        self.in_srs = in_srs
        self.out_srs = out_srs

        self.open()

    def open(self):
        '''Open the file for processing, called by __init__
        '''
       
        if self._mode == 'r':
            if not os.path.exists(self.filename):
                raise OSError("No such file or directory: '%s'" % self.filename)
            ## Make sure we have a header
            if self._header == None:
                self._reader = base.Reader(self.filename,mode= self._mode)            
                self._header = self._reader.get_header() 
            else: 
                raise util.LaspyException("Headers must currently be stored in the file, you provided: " + str(self._header))
                self._reader = base.Reader(self.filename, mode = self._mode, header=self._header)

            if self.in_srs:
                self._reader.SetInputSRS(self.in_srs)
            if self.out_srs:
                self._reader.SetOutputSRS(self.out_srs)
            ## Wire up API for extra dimensions
            if self._reader.extra_dimensions != []:
                for dimension in self._reader.extra_dimensions:
                    dimname = dimension.name.replace("\x00", "").replace(" ", "_").lower()
                    self.addProperty(dimname)


        if self._mode == 'rw':
            if self._header == None:
                self._writer = base.Writer(self.filename,mode = self._mode)
                self._reader = self._writer
                self._header = self._reader.get_header()
                ## Wire up API for any extra Dimensions
                if self._writer.extra_dimensions != []:
                    for dimension in self._writer.extra_dimensions:
                        dimname = dimension.name.replace("\x00", "").replace(" ", "_").lower()
                        self.addProperty(dimname) 
            else:
                raise util.LaspyException("Headers must currently be stored in the file, you provided: " + str(self._header))
    
        if self._mode == 'w': 
            if self._header == None:
                raise util.LaspyException("Creation of a file in write mode requires a header object.")  
            if isinstance(self._header,  header.HeaderManager):
                vlrs = self._header.vlrs
                evlrs = self._header.evlrs
                self._header = self._header.copy() 
                if self._vlrs != False:
                    self._vlrs.extend(vlrs)
                else:
                    self._vlrs = vlrs
                if self._evlrs != False:
                    self._evlrs.extend(evlrs)
                else:
                    self._evlrs = evlrs

            self._writer = base.Writer(self.filename, mode = "w",
                                      header = self._header, 
                                      vlrs = self._vlrs, evlrs = self._evlrs)
            self._reader = self._writer
            ## Wire up API for any extra Dimensions
            if self._writer.extra_dimensions != []:
                for dimension in self._writer.extra_dimensions:
                    dimname = dimension.name.replace("\x00", "").replace(" ", "_").lower()
                    self.addProperty(dimname) 

        if self._mode == 'w+':
            raise NotImplementedError

    def close(self, ignore_header_changes = False, minmax_mode="scaled"):
        '''Closes the LAS file
        '''
        if self._mode == "r":
            self._reader.close()
            self._reader = None
            self._header = None
        else: 
            self._writer.close(ignore_header_changes, minmax_mode)    
            self._reader = None
            self._writer = None
            self._header = None

    def visualize(self, mode = "default", dim = "intensity"):
        try:
            from laspy.glviewer import run_glviewer
            run_glviewer(self, mode= mode, dim = dim)
            return(0)
        except Exception, err:
            print("Something went wrong: ")
            print(err)
            return(1)

    def addProperty(self, name):
        def fget(self):
            return(self._reader.get_dimension(name))
        def fset(self, value):
            self.assertWriteMode()
            self._reader.set_dimension(name, value)
        setattr(self.__class__, name, property(fget, fset, None, None))

    def define_new_dimension(self, name, data_type, description):
        self.assertWriteMode()
        self._writer.define_new_dimension(name, data_type, description)
        self.addProperty(name)

    def assertWriteMode(self):<commit_msg>Continue import reforms in file.py<commit_after>import base
import util
import header
import copy
import os

class File(object):
    ''' Base file object in laspy. Provides access to most laspy functionality,
    and holds references to the HeaderManager, Reader, and potentially Writer objects. 
    '''
    def __init__(self, filename,
                       header=None,
                       vlrs=False,
                       mode='r',
                       in_srs=None,
                       out_srs=None,
                       evlrs = False):
        '''Instantiate a file object to represent an LAS file.

        :arg filename: The filename to open
        :keyword header: A header open the file with. Not required in modes "r" and "rw"
        :type header: a :obj:`laspy.header.Header` instance
        :keyword mode: "r" for read, "rw" for modify/update, "w" for write, and "w+" for append (not implemented)
        :type mode: string
        :keyword in_srs: Input SRS to override the existing file's SRS with (not implemented)
        :type in_srs: a :obj:`laspy.SRS` instance
        :keyword out_srs: Output SRS to reproject points on-the-fly to as \
        they are read/written. (not implemented)
        :type out_srs: a :obj:`laspy.SRS` instance (not implemented)

        .. note::
            To open a file in write mode, you must provide a
            laspy.header.Header instance which will be immediately written to
            the file. If you provide a header instance in read mode, the
            values of that header will be used in place of those in the actual
            file.

        .. note::
            If a file is open for write, it cannot be opened for read and vice
            versa.

        >>> import laspy 
        >>> f = laspy.file.File('file.las', mode='r')
        >>> for p in f:
        ...     print 'X,Y,Z: ', p.x, p.y, p.z

        >>> h = f.header
        >>> f2 = file.File('file2.las', mode = "w", header=h)
        >>> points = f.points
        >>> f2.points = points
        >>> f2.close()
        '''

        self.filename = os.path.abspath(filename)
        self._header = header
        self._vlrs = vlrs
        self._evlrs = evlrs
        self._mode = mode.lower()
        self.in_srs = in_srs
        self.out_srs = out_srs

        self.open()

    def open(self):
        '''Open the file for processing, called by __init__
        '''
       
        if self._mode == 'r':
            if not os.path.exists(self.filename):
                raise OSError("No such file or directory: '%s'" % self.filename)
            ## Make sure we have a header
            if self._header == None:
                self._reader = base.Reader(self.filename,mode= self._mode)            
                self._header = self._reader.get_header() 
            else: 
                raise util.LaspyException("Headers must currently be stored in the file, you provided: " + str(self._header))
                self._reader = base.Reader(self.filename, mode = self._mode, header=self._header)

            if self.in_srs:
                self._reader.SetInputSRS(self.in_srs)
            if self.out_srs:
                self._reader.SetOutputSRS(self.out_srs)
            ## Wire up API for extra dimensions
            if self._reader.extra_dimensions != []:
                for dimension in self._reader.extra_dimensions:
                    dimname = dimension.name.replace("\x00", "").replace(" ", "_").lower()
                    self.addProperty(dimname)


        if self._mode == 'rw':
            if self._header == None:
                self._writer = base.Writer(self.filename,mode = self._mode)
                self._reader = self._writer
                self._header = self._reader.get_header()
                ## Wire up API for any extra Dimensions
                if self._writer.extra_dimensions != []:
                    for dimension in self._writer.extra_dimensions:
                        dimname = dimension.name.replace("\x00", "").replace(" ", "_").lower()
                        self.addProperty(dimname) 
            else:
                raise util.LaspyException("Headers must currently be stored in the file, you provided: " + str(self._header))
    
        if self._mode == 'w': 
            if self._header == None:
                raise util.LaspyException("Creation of a file in write mode requires a header object.")  
            if isinstance(self._header,  header.HeaderManager):
                vlrs = self._header.vlrs
                evlrs = self._header.evlrs
                self._header = self._header.copy() 
                if self._vlrs != False:
                    self._vlrs.extend(vlrs)
                else:
                    self._vlrs = vlrs
                if self._evlrs != False:
                    self._evlrs.extend(evlrs)
                else:
                    self._evlrs = evlrs

            self._writer = base.Writer(self.filename, mode = "w",
                                      header = self._header, 
                                      vlrs = self._vlrs, evlrs = self._evlrs)
            self._reader = self._writer
            ## Wire up API for any extra Dimensions
            if self._writer.extra_dimensions != []:
                for dimension in self._writer.extra_dimensions:
                    dimname = dimension.name.replace("\x00", "").replace(" ", "_").lower()
                    self.addProperty(dimname) 

        if self._mode == 'w+':
            raise NotImplementedError

    def close(self, ignore_header_changes = False, minmax_mode="scaled"):
        '''Closes the LAS file
        '''
        if self._mode == "r":
            self._reader.close()
            self._reader = None
            self._header = None
        else: 
            self._writer.close(ignore_header_changes, minmax_mode)    
            self._reader = None
            self._writer = None
            self._header = None

    def visualize(self, mode = "default", dim = "intensity"):
        try:
            laspy.glviewer.run_glviewer(self, mode= mode, dim = dim)
            return(0)
        except Exception, err:
            print("Something went wrong: ")
            print(err)
            return(1)

    def addProperty(self, name):
        def fget(self):
            return(self._reader.get_dimension(name))
        def fset(self, value):
            self.assertWriteMode()
            self._reader.set_dimension(name, value)
        setattr(self.__class__, name, property(fget, fset, None, None))

    def define_new_dimension(self, name, data_type, description):
        self.assertWriteMode()
        self._writer.define_new_dimension(name, data_type, description)
        self.addProperty(name)

    def assertWriteMode(self):
{'fraction_non_alphanumeric': 0.0998158379373849, 'fraction_numerical': 0.0017679558011049724, 'mean_word_length': 1.6427876192330153, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 51, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '564867', 'n_tokens_mistral': 3739, 'n_tokens_neox': 3575, 'n_words': 1051}