Beispiel #1
0
    def saveData(self, plus_subfiles=False):
        """Save the current state of the data contained by this instance.
        
        Unless plus_subfiles == False all subfile data will be saved as well.
        
        Args:
            plus_subfiles=False (bool): if True all associated subfile will be
            saved to their current state as well.
        
        Raises:
            IOError: if there is a problem writing to file.

        """
        try:
            contents = self._getPrintableContents()
            filetools.writeFile(contents, self.path_holder.absolutePath())
        except IOError:
            logger.error(
                'Could not write contents for %s file to %s' %
                (self.path_holder.extension, self.path_holder.absolutePath()))
            raise IOError('Unable to write file to disc')

        if self.subfiles and plus_subfiles:
            for subfile in self.subfiles:
                try:
                    contents = subfile._getPrintableContents()
                    filetools.writeFile(contents,
                                        subfile.path_holder.absolutePath())
                except IOError:
                    logger.error('Could not write contents for %s file to %s' %
                                 (subfile.path_holder.absolutePath()))
                    raise
Beispiel #2
0
    def write(self, filepath=None, overwrite=False):
        """Write the contents of this file to disk.

        Writes out to file in the format required for reading by ISIS/FMP.

        Note:
            If a filepath is not provided and the settings in this objects
            PathHolder class have not been updated you will write over the
            file that was loaded.

        Args:
            filepath=None(str): if a filename is provided it the file will be
                written to that location. If not, the current settings in this
                object path_holder object will be used.
            overwrite=False(bool): if the file already exists it will raise
                an IOError.

        Raises:
            IOError - If unable to write to file.
        """
        if filepath is None:
            filepath = self.path_holder.absolutePath()

        if not overwrite and os.path.exists(filepath):
            raise IOError(
                'filepath %s already exists. Set overwrite=True to ignore this warning.'
                % filepath)

        contents = self.getPrintableContents()
        ft.writeFile(contents, filepath)
Beispiel #3
0
    def write(self, overwrite=False, **kwargs):
        """Write the control files to disk.

        Calls the getPrintableContents function and then writes the returned
        contents to file.

        **kwargs:
            active_only=True(bool): if True only the parts with 'active' status
                set to True will be included.
            parents(list): a list of parents (tuflow control files) to return.
                if not given all the parents in self.control_files will be
                returned.

        Args:
            overwrite=False(bool): if set to True it will overwrite an existing
                file without warning. If False it will raise an error if the
                file already exists.
        """
        contents = self.getPrintableContents(**kwargs)
        for ckey in contents.keys():
            if os.path.exists(ckey) and not overwrite:
                raise IOError(
                    'File %s already exists. Use overwrite=True to ignore this warning'
                    % ckey)

        for ckey, cval in contents.items():
            i = 0
            filetools.writeFile(cval, ckey)
Beispiel #4
0
    def write(self, filepath=None, overwrite=False):
        """Write the contents of this file to disk.
        
        Writes out to file in the format required for reading by ISIS/FMP.
        
        Note:
            If a filepath is not provided and the settings in this objects
            PathHolder class have not been updated you will write over the
            file that was loaded.
        
        Args:
            filepath=None(str): if a filename is provided it the file will be
                written to that location. If not, the current settings in this
                object path_holder object will be used.
            overwrite=False(bool): if the file already exists it will raise
                an IOError.
        
        Raises:
            IOError - If unable to write to file.
        """
        if filepath is None:
            filepath = self.path_holder.absolutePath()

        if not overwrite and os.path.exists(filepath):
            raise IOError('filepath %s already exists. Set overwrite=True to ignore this warning.' % filepath)
            
        contents = self.getPrintableContents()
        ft.writeFile(contents, filepath)


        
Beispiel #5
0
    def saveData(self, plus_subfiles=False):
        """Save the current state of the data contained by this instance.
        
        Unless plus_subfiles == False all subfile data will be saved as well.
        
        Args:
            plus_subfiles=False (bool): if True all associated subfile will be
            saved to their current state as well.
        
        Raises:
            IOError: if there is a problem writing to file.

        """
        try:
            contents = self._getPrintableContents()
            filetools.writeFile(contents, self.path_holder.absolutePath())
        except IOError:
            logger.error('Could not write contents for %s file to %s' %
                (self.path_holder.extension, self.path_holder.absolutePath()))
            raise IOError ('Unable to write file to disc')  
        
        if self.subfiles and plus_subfiles:
            for subfile in self.subfiles:
                try:
                    contents = subfile._getPrintableContents()
                    filetools.writeFile(contents, subfile.path_holder.absolutePath())
                except IOError:
                    logger.error('Could not write contents for %s file to %s' %
                        (subfile.path_holder.absolutePath()))
                    raise 
Beispiel #6
0
    def test_writeTuflowModel(self):
        """Note this will write the outputs of the tuflow model to disk.
        
        No comparisons of the data are done here. It's just a convenience so
        that you can check the output files and make sure that they look like
        they should.
        Outputs will be written to SHIP/integration_tests/test_output/asread/
        """
        print('Test writing tuflow model...')
        cwd = os.path.join(os.getcwd(), 'integration_tests', 'test_output')
        need_dirs = [
            cwd,
            os.path.join(cwd, 'asread'),
            os.path.join(cwd, 'asread/model1'),
            os.path.join(cwd, 'asread/model1/tuflow'),
            os.path.join(cwd, 'asread/model1/tuflow/runs'),
            os.path.join(cwd, 'asread/model1/tuflow/model')
        ]
        try:
            for n in need_dirs:
                if not os.path.isdir(n):
                    os.mkdir(n)
        except IOError:
            print('\t Could not make test directeries - aborting test')
            print('\nFail!\n')

        tuflow = copy.deepcopy(self.tuflow)
        new_root = os.path.normpath(need_dirs[4])  # ending 'runs'
        root_compare = os.path.normpath(need_dirs[3])  # ending 'tuflow'
        tuflow.root = new_root
        contents = {}
        for ckey, cval in tuflow.control_files.items():
            if not ckey in contents.keys():
                contents[ckey] = {}
            temp = cval.getPrintableContents()
            for tkey, tval in temp.items():
                #                 print ('root compare: ' + root_compare)
                #                 print ('tkey:         ' + tkey)
                utils.softAssertionIn(root_compare, tkey)
                contents[ckey][tkey] = tval

        for ctype, c in contents.items():
            for pkey, val in c.items():
                ft.writeFile(val, pkey)

        del tuflow
        print('Done')
Beispiel #7
0
    def test_writeTuflowModel(self):
        """Note this will write the outputs of the tuflow model to disk.
        
        No comparisons of the data are done here. It's just a convenience so
        that you can check the output files and make sure that they look like
        they should.
        Outputs will be written to SHIP/integration_tests/test_output/asread/
        """
        print ('Test writing tuflow model...')
        cwd = os.path.join(os.getcwd(), 'integration_tests', 'test_output')
        need_dirs = [cwd,
                     os.path.join(cwd, 'asread'), 
                     os.path.join(cwd, 'asread/model1'),
                     os.path.join(cwd, 'asread/model1/tuflow'),
                     os.path.join(cwd, 'asread/model1/tuflow/runs'),
                     os.path.join(cwd, 'asread/model1/tuflow/model')
                    ]
        try:
            for n in need_dirs:
                if not os.path.isdir(n):
                    os.mkdir(n)
        except IOError:
            print ('\t Could not make test directeries - aborting test')
            print ('\nFail!\n')
        tuflow = copy.deepcopy(self.tuflow)
        new_root = os.path.normpath(need_dirs[4])       # ending 'runs'
        root_compare = os.path.normpath(need_dirs[3])   # ending 'tuflow'
        tuflow.root = new_root
        contents = {}
        for ckey, cval in tuflow.control_files.items():
            if not ckey in contents.keys():
                contents[ckey] = {}
            temp = cval.getPrintableContents()
            for tkey, tval in temp.items():
#                 print ('root compare: ' + root_compare)
#                 print ('tkey:         ' + tkey)
                assert(root_compare in tkey)
                contents[ckey][tkey] = tval
        
        for ctype, c in contents.items():
            for pkey, val in c.items():
                ft.writeFile(val, pkey)

        del tuflow
        print ('pass')
Beispiel #8
0
def trimRiverSections():
    """Deactivates all parts of isis/fmp river sections outside bankmarkers.
    
    Searches through all of the river sections in an isis/fmp model and sets
    deactivation markers at the location of all bankmarkers. I.e. where a 
    bankmarker was marked as left it will now have a deactivation marker there
    as well.
    
    Saves the updated file to disk with _Updated appended to the filename.
    """
    # Load the dat file into a new DatCollection object (isis_model)
    dat_file = r'C:\path\to\an\isis-fmp\datfile.dat'
    loader = fl.FileLoader()
    isis_model = loader.loadFile(dat_file)

    # Get the river sections from the model and loop through them
    rivers = isis_model.getUnitsByCategory('River')
    for river in rivers:

        # Get the bankmarker locations as a list for this river section
        bvals = river.getRowDataAsList(rdt.BANKMARKER)

        # Get the DataObject for deactivation because we want to update it
        deactivation_data = river.getRowDataObject(rdt.DEACTIVATION)

        # Loop through the bankmarker values and each time we find one that's
        # set (not False) we set the deactivation value at that index equal to
        # the LEFT or RIGHT status of the bankmarker
        for i, b in enumerate(bvals):
            if b == 'LEFT':
                deactivation_data.setValue('LEFT', i)
            elif b == 'RIGHT':
                deactivation_data.setValue('RIGHT', i)

    # Update and get the filename of the isis_model
    fname = isis_model.path_holder.file_name
    isis_model.path_holder.setFileName(fname + '_Updated')
    dat_path = isis_model.path_holder.getAbsolutePath()

    # Get the contents of the updated isis model
    contents = isis_model.getPrintableContents()

    # Write the new isis model to file
    filetools.writeFile(contents, dat_path)
Beispiel #9
0
def iefExample():
    """update some key file paths in an ief file.
    
    Updates the .dat file, .tcf file, and results file paths referenced by
    the ief file and save it under a new ief file name. 
    """
    # Load the tuflow model with a tcf file
    ief_file = r'C:\path\to\an\isis\ieffile.ief'
    loader = fl.FileLoader()
    ief = loader.loadFile(ief_file)
    
    # Get the referenced fmp .dat and .tcf files
    dat_path = ief.getValue('Datafile')
    tcf_path = ief.getValue('2DFile')
    results_path = ief.getValue('Results')
    
    # Update the dat, results and tcf file names
    root, ext = os.path.splitext(dat_path)
    new_dat = root + '_Updated' + ext
    root, ext = os.path.splitext(results_path)
    new_results = root + '_Updated' + ext
    root, ext = os.path.splitext(tcf_path)
    new_tcf = root + '_Updated' + ext
    ief.setValue('Datafile', new_dat)
    ief.setValue('Results', new_results)
    ief.setValue('2DFile', new_tcf)
    
    # Update and get the filename of the ief
    fname = ief.path_holder.file_name
    ief.path_holder.setFileName(fname + '_Updated')
    ief_path = ief.path_holder.getAbsolutePath()

    # Get the contents of the updated ief
    contents = ief.getPrintableContents()
    
    # Write the new ief to file
    filetools.writeFile(contents, ief_path)