Reads in the TEMP#/ener_box#.output file and parses it, returning an array of energies

    ARGUMENTS
        filename (string) - the path to the folder of the simulation
	colnum (integer) column the energy is found in
336044
def read_total_energies(pathname,colnum):
    

    print("--Reading total energies from %s/..." % pathname)

    # Initialize Return variables
    E_kn = numpy.zeros([NumTemps, NumIterations], numpy.float64)
    
    #Read files
    for k in range(NumTemps):
        #Construct each TEMP#/ener_box#.output name and read in the file
        filename = os.path.join(pathname,'TEMP' + str(k), 'ener_box'+ str(k) + '.output')
        infile = open(filename, 'r')
        lines = infile.readlines()
        infile.close()
        numLines = len(lines)

        #Initialize arrays for E
        E_from_file = numpy.zeros(NumIterations, numpy.float64)

        #Parse lines in each file
        for n in range(NumIterations):
            m = numLines - 2 - n #Count down (the 2 is for index purposes(1) and to not use the double-counted last line (1))
            elements = lines[m].split()
            E_from_file[n] = float(elements[colnum])

        #Add in the E's for each timestep (n) at this temperature (k)
        E_kn[k] = E_from_file;
    return E_kn
742606
def read_energies(self, root):
        self.key_value_pairs_reaction = None

        slab_structures = collect_structures(root)

        if len(slab_structures) == 0:
            self.raise_warning('No structure files in {root}: Skipping this folder'
                               .format(root=root))
            return

        # Remove old species from ase_ids
        all_reaction_species = list(self.reaction.values())[0] \
            + list(self.reaction.values())[1]
        all_reaction_species = [clear_prefactor(rs) for rs in
                                all_reaction_species]

        for ase_id in list(self.ase_ids.keys()):
            if ase_id == 'star' or 'bulk' in ase_id:
                continue
            if not ase_id in all_reaction_species:
                del self.ase_ids[ase_id]

        if 'TS' in self.structures:  # Delete old TS
            del self.structures['TS']
            del self.structures['TSempty']
            del self.prefactors['TS']

        for k in list(self.structures.keys()):
            if 'neb' in k:
                del self.structures[k]


        neb_indices = [i for i, slab in enumerate(slab_structures) if 'neb' in
                       slab[-1].info['filename']]
        neb_names = {}

        if len(neb_indices) == 1:
            index = neb_indices[0]
            slab = slab_structures[index]
            f = slab[-1].info['filename']
            del slab_structures[index]
            neb_indices = []
            for i, s in enumerate(slab):
                s.info['filename'] = f
                slab_structures.append(s)
                index = len(slab_structures) - 1
                neb_indices += [index]
                neb_names.update({str(i): 'neb' + str(i)})

        elif len(neb_indices) > 1:
            for i in neb_indices:
                f = slab_structures[i][-1].info['filename']
                neb_names.update({str(i): os.path.basename(f).split('.')[0]})

        for i, slab in enumerate(slab_structures):
            if isinstance(slab, list):
                slab_structures[i] = slab[-1]

        empty = self.empty

        reactant_entries = self.reaction['reactants'] + \
            self.reaction['products']
        if not empty:
            if 'star' in reactant_entries and len(neb_indices) == 0:
                message = 'Empty slab needed for reaction!'
                self.raise_error(message)
                return
            else:
                empty0 = slab_structures[0]
                chemical_composition = ase_tools.get_chemical_formula(empty0)
                self.raise_warning("Using '{}' as a reference instead of empty slab"
                                   .format(empty0.info['filename']))
                empty_atn = list(empty0.get_atomic_numbers())
        else:
            chemical_composition = ase_tools.get_chemical_formula(empty)
            empty_atn = list(empty.get_atomic_numbers())

        prefactor_scale = copy.deepcopy(self.prefactors)
        for key1, values in prefactor_scale.items():
            prefactor_scale[key1] = [1 for v in values]

        key_value_pairs = {}

        key_value_pairs.update({'name':
                                chemical_composition,
                                'facet': self.ase_facet,
                                'state': 'star'})

        
        for i, slab in enumerate(slab_structures):
            f = slab.info['filename']
            atns = list(slab.get_atomic_numbers())
            if not (np.array(atns) > 8).any() and \
               (np.array(empty_atn) > 8).any():
                self.raise_warning("Only molecular species for structure: {}"
                                   .format(f))
                continue

            """Get supercell size relative to empty slab"""
            supercell_factor = 1
            if len(atns) > len(empty_atn) * 2:  # different supercells
                supercell_factor = len(res_slab_atn) // len(empty_atn)

            """Atomic numbers of adsorbate"""
            ads_atn = []
            if 'star' in reactant_entries and len(neb_indices) == 0:
                ads_atn = copy.copy(atns)
                for atn in empty_atn * supercell_factor:
                    try:
                        ads_atn.remove(atn)
                    except ValueError as e:
                        self.raise_error(
                            'Empty slab: {} contains species not in: {}' \
                                .format(empty.info['filename'], f))
                ads_atn = sorted(ads_atn)
                if ads_atn == []:
                    self.raise_warning("No adsorbates for structure: {}"
                                   .format(f))
                    continue

            ase_id = None
            id, ase_id = ase_tools.check_in_ase(slab, self.cathub_db)
            key_value_pairs.update({'epot': ase_tools.get_energies([slab])})

            if 'empty' in f and 'TS' in f:  # empty slab for transition state
                self.structures.update({'TSempty': [slab]})
                self.prefactors.update({'TSempty': [1]})
                prefactor_scale.update({'TSempty': [1]})
                key_value_pairs.update({'species': ''})
                if ase_id is None:
                    ase_id = ase_tools.write_ase(slab, self.cathub_db,
                                                 self.stdout,
                                                 self.user,
                                                 **key_value_pairs)
                elif self.update:
                    ase_tools.update_ase(self.cathub_db, id, self.stdout,
                                         **key_value_pairs)
                self.ase_ids.update({'TSemptystar': ase_id})
                continue

            elif 'TS' in f:  # transition state
                self.structures.update({'TS': [slab]})
                self.prefactors.update({'TS': [1]})
                prefactor_scale.update({'TS': [1]})
                key_value_pairs.update({'species': 'TS'})
                if ase_id is None:
                    ase_id = ase_tools.write_ase(slab, self.cathub_db,
                                                 self.stdout,
                                                 self.user,
                                                 **key_value_pairs)
                elif self.update:
                    ase_tools.update_ase(self.cathub_db, id, self.stdout,
                                         **key_value_pairs)
                self.ase_ids.update({'TSstar': ase_id})
                continue

            if i in neb_indices:
                self.structures.update({neb_names[str(i)]: [slab]})
                key_value_pairs.update({'species': 'neb'})
                if ase_id is None:
                    ase_id = ase_tools.write_ase(slab,
                                                 self.cathub_db,
                                                 self.stdout,
                                                 self.user,
                                                 **key_value_pairs)
                elif self.update:
                    ase_tools.update_ase(self.cathub_db, id, self.stdout,
                                         **key_value_pairs)
                self.ase_ids.update({neb_names[str(i)]: ase_id})
                continue
            

            found = False
            for key, mollist in self.reaction.items():
                if found:
                    break
                for n, molecule in enumerate(mollist):
                    if found:
                        break
                    if not self.states[key][n] == 'star':  # only slab stuff
                        continue
                    if not self.structures[key][n] == '':  # allready found
                        continue
                    molecule = clear_state(clear_prefactor(molecule))
                    if molecule == '':
                        continue
                    molecule_atn = sorted(
                        ase_tools.get_numbers_from_formula(molecule))
                    if slab.info['filename'] == molecule:
                        if ads_atn == molecule_atn:
                            found = True
                            match_key = key
                            match_n = n
                            break
                        else:
                            raise_warning('Name of file does not match chemimcal formula: {}'
                                          .format(slab.info['filename']))

                    for n_ads in range(1, 5):
                        mol_atn = sorted(molecule_atn * n_ads)
                        if (ads_atn == mol_atn or len(ads_atn) == 0):
                            match_n_ads = n_ads
                            found = True
                            match_key = key
                            match_n = n
                            break

            if found:
                key = match_key
                n = match_n
                n_ads = match_n_ads
                self.structures[key][n] = slab
                species = clear_prefactor(
                    self.reaction[key][n])
                id, ase_id = ase_tools.check_in_ase(
                    slab, self.cathub_db)
                key_value_pairs.update(
                    {'species':
                     clear_state(
                         species),
                     'n': n_ads,
                     'site': str(self.sites.get(species, ''))})
                if ase_id is None:
                    ase_id = ase_tools.write_ase(
                        slab, self.cathub_db, self.stdout,
                        self.user,
                        **key_value_pairs)
                elif self.update:
                    ase_tools.update_ase(
                        self.cathub_db, id, self.stdout,
                        **key_value_pairs)
                self.ase_ids.update({species: ase_id})

            if n_ads > 1:
                for key1, values in prefactor_scale.items():
                    for mol_i in range(len(values)):
                        if self.states[key1][mol_i] == 'gas':
                            prefactor_scale[key1][mol_i] = n_ads

            if supercell_factor > 1:
                for key2, values in prefactor_scale.items():
                    for mol_i in range(len(values)):
                        if self.reaction[key2][mol_i] == 'star':
                            prefactor_scale[key2][mol_i] *= supercell_factor


        # Check that all structures have been found
        structurenames = [s for s in list(self.structures.keys())
                          if s not in ['reactants', 'products']]
        for k in ['reactants', 'products']:
            structurenames += [s for s in self.structures[k] if s != ''
                               and s is not None]
        only_neb = np.all(['neb' in s for s in structurenames])
        surface_composition = self.metal

        if only_neb:
            if not self.empty:
                for ads in self.reaction_atoms['reactants']:
                    ads_atn = ase_tools.get_numbers_from_formula(ads)
                    for atn in ads_atn:
                        empty_atn.remove(atn)
                chemical_composition = \
                    ase_tools.get_formula_from_numbers(empty_atn, mode='metal')
            neb_numbers = []
            neb_energies = []
            for key, structure in self.structures.items():
                if key in ['reactants', 'products']:
                    continue

                neb_no = int(key.split('.')[0].replace('neb', ''))
                neb_numbers += [neb_no]
                neb_energies += [structure[0].get_potential_energy()]

            initial = neb_energies[np.argmin(neb_numbers)]
            final = neb_energies[np.argmax(neb_numbers)]
            TS = np.max(neb_energies)

            reaction_energy = final - initial
            activation_energy = TS - initial

            if activation_energy == 0 or activation_energy == reaction_energy:
                activation_energy = None
        else:
            for key, structurelist in self.structures.items():
                if '' in structurelist:
                    index = structurelist.index('')
                    molecule = clear_state(
                        clear_prefactor(self.reaction[key][index]))
                    if self.states[key][index] == 'star':
                        message = "Adsorbate '{}' not found for any structure files in '{}'."\
                            .format(molecule, root) + \
                            " Please check your adsorbate structures and the empty slab."
                    if self.states[key][index] == 'gas':
                        message = "Gas phase molecule '{}' not found for any structure files in '{}'."\
                            .format(molecule, self.gas_folder) + \
                            " Please check your gas phase references."
                    self.raise_error(message)
                    return

            prefactors_final = copy.deepcopy(self.prefactors)
            for key in self.prefactors:
                for i, v in enumerate(self.prefactors[key]):
                    prefactors_final[key][i] = self.prefactors[key][i] * \
                        prefactor_scale[key][i]

            reaction_energy = None
            activation_energy = None
            try:
                reaction_energy, activation_energy = \
                    ase_tools.get_reaction_energy(
                        self.structures, self.reaction,
                        self.reaction_atoms,
                        self.states, prefactors_final,
                        self.prefactors_TS,
                        self.energy_corrections)
            except BaseException as e:
                message = "reaction energy failed for files in '{}'"\
                    .format(root)
                self.raise_error(message + '\n' + str(e))

        if not -self.energy_limit < reaction_energy < self.energy_limit:
            self.raise_error('reaction energy is very large: {} eV \n  '
                             .format(reaction_energy) +
                             'Folder: {}. \n  '.format(root) +
                             'If the value is correct, you can reset the limit with cathub folder2db --energy-limit <value>. Default is --energy-limit=5 (eV)'
                             )
        if activation_energy is not None:
            if activation_energy < reaction_energy:
                self.raise_warning('activation energy is smaller than reaction energy: {} vs {} eV \n  Folder: {}'.format(
                    activation_energy, reaction_energy, root))
            if not activation_energy < self.energy_limit:
                self.raise_error(' Very large activation energy: {} eV \n  Folder: {}'
                                 .format(activation_energy, root))

        reaction_info = {'reactants': {},
                         'products': {}}

        for key in ['reactants', 'products']:
            for i, r in enumerate(self.reaction[key]):
                r = clear_prefactor(r)
                reaction_info[key].update({r: self.prefactors[key][i]})

        self.key_value_pairs_reaction = {
            'chemical_composition': chemical_composition,
            'surface_composition': surface_composition,
            'facet': self.facet,
            'sites': self.sites,
            'coverages': self.coverages,
            'reactants': reaction_info['reactants'],
            'products': reaction_info['products'],
            'reaction_energy': float(reaction_energy),
            'activation_energy': activation_energy,
            'dft_code': self.DFT_code,
            'dft_functional': self.DFT_functional,
            'pub_id': self.pub_id,
            'doi': self.doi,
            'year': int(self.year),
            'ase_ids': self.ase_ids,
            'energy_corrections': self.energy_corrections,
            'username': self.user}
1236873
def readehf(filename):
    
    f = open(filename, 'r')
    edf = {}
    if not f.readline().strip().startswith('{'):
        raise ValueError('Invalid file format.')
    for l in f:
        l = l.strip()
        if not l:
            continue
        if l.endswith('}'):
            break  # last line of header
        try:
            left, right = l.split('=', 1)
        except ValueError:
            raise ValueError('Invalid line: ' + l)
        left = left.strip()
        right = right.strip()
        if not right.endswith(';'):
            raise ValueError(
                'Invalid line (does not end with a semicolon): ' + l)
        right = right[:-1].strip()
        m = re.match('^(?P<left>.*)~(?P<continuation>\d+)$', left)
        if m is not None:
            edf[m.group('left')] = edf[m.group('left')] + right
        else:
            edf[left] = _readedf_extractline(left, right)
    f.close()
    edf['FileName'] = filename
    edf['__Origin__'] = 'EDF ID02'
    edf['__particle__'] = 'photon'
    return edf
43028
def save_volt(elecs, volt, filename):
    
    # bring data in shape
    content = np.column_stack((elecs, volt, np.zeros(len(volt))))

    # save datapoints
    with open(filename, 'w') as fid:
        fid.write('{0}\n'.format(content.shape[0]))
    with open(filename, 'ab') as fid:
        np.savetxt(fid, np.array(content), fmt='%i %i %f %f')
1014684
def read_envfile(path=None, **overrides):
        
        if path is None:
            frame = inspect.currentframe().f_back
            caller_dir = os.path.dirname(frame.f_code.co_filename)
            path = os.path.join(os.path.abspath(caller_dir), '.env')

        try:
            with open(path, 'r') as f:
                content = f.read()
        except getattr(__builtins__, 'FileNotFoundError', IOError):
            logger.debug('envfile not found at %s, looking in parent dir.',
                         path)
            filedir, filename = os.path.split(path)
            pardir = os.path.abspath(os.path.join(filedir, os.pardir))
            path = os.path.join(pardir, filename)
            if filedir != pardir:
                Env.read_envfile(path, **overrides)
            else:
                # Reached top level directory.
                warnings.warn('Could not any envfile.')
            return

        logger.debug('Reading environment variables from: %s', path)
        for line in content.splitlines():
            tokens = list(shlex.shlex(line, posix=True))
            # parses the assignment statement
            if len(tokens) < 3:
                continue
            name, op = tokens[:2]
            value = ''.join(tokens[2:])
            if op != '=':
                continue
            if not re.match(r'[A-Za-z_][A-Za-z_0-9]*', name):
                continue
            value = value.replace(r'\n', '\n').replace(r'\t', '\t')
            os.environ.setdefault(name, value)

        for name, value in overrides.items():
            os.environ.setdefault(name, value)
29677
def energy_value(h: List[Union[int, float]],
                 J: Dict[Tuple[int, int], Union[int, float]],
                 sol: List[int]) -> Union[int, float]:
    
    ener_ising = 0
    for elm in J.keys():
        if elm[0] == elm[1]:
            raise TypeError("""Interaction term must connect two different variables""")
        else:
            ener_ising += J[elm] * int(sol[elm[0]]) * int(sol[elm[1]])
    for i in range(len(h)):
        ener_ising += h[i] * int(sol[i])
    return ener_ising
1062124
def _assembled_out_file_name(self):
        """"""
        if self.Parameters['-s'].isOn():
            assembled_reads = self._absolute(str(self.Parameters['-s'].Value))
        else:
            raise ValueError(
                "No assembled-reads (flag -s) output path specified")
        return assembled_reads
1258282
def _read_tempfile(self, filename):
        '''

        '''
        with open(os.path.join(self._tempdir, filename)) as f:
            return f.read()
419033
def get_sf_values(self, filename='shlp_hour_factors.csv'):
        
        file = os.path.join(self.datapath, filename)
        hour_factors = pd.read_csv(file, index_col=0)
        hour_factors = hour_factors.query(
            'building_class=={0} and shlp_type=="{1}"'.format(
                self.building_class, self.shlp_type))

        # Join the two DataFrames on the columns 'hour' and 'hour_of_the_day'
        # or ['hour' 'weekday'] and ['hour_of_the_day', 'weekday'] if it is
        # not a residential slp.
        residential = self.building_class > 0
        left_cols = ['hour_of_day'] + (['weekday'] if not residential else [])
        right_cols = ['hour'] + (['weekday'] if not residential else [])
        sf_mat = pd.DataFrame.merge(
            hour_factors, self.df, left_on=left_cols, right_on=right_cols,
            how='outer', left_index=True).sort_index()

        # drop unnecessary columns
        drop_cols = (
            ['hour_of_day', 'hour', 'building_class', 'shlp_type',
             'date', 'temperature'] + (['weekday_x'] if residential else []) +
            (['weekday_y'] if residential else []) +
            (['weekday'] if not residential else []))
        sf_mat = sf_mat.drop(drop_cols, 1)

        # Determine the h values
        length = len(self.temperature)
        sf = (np.array(sf_mat)[np.array(list(range(0, length)))[:],
                               (self.get_temperature_interval() - 1)[:]])
        return np.array(list(map(float, sf[:])))
1032971
def _read(self, directory, filename, session, path, name, extension,
              spatial=False, spatialReferenceID=4236, replaceParamFile=None,
              readIndexMaps=True):
        
        # Set file extension property
        self.fileExtension = extension

        # Dictionary of keywords/cards and parse function names
        KEYWORDS = {'INDEX_MAP': mtc.indexMapChunk,
                    'ROUGHNESS': mtc.mapTableChunk,
                    'INTERCEPTION': mtc.mapTableChunk,
                    'RETENTION': mtc.mapTableChunk,
                    'GREEN_AMPT_INFILTRATION': mtc.mapTableChunk,
                    'GREEN_AMPT_INITIAL_SOIL_MOISTURE': mtc.mapTableChunk,
                    'RICHARDS_EQN_INFILTRATION_BROOKS': mtc.mapTableChunk,
                    'RICHARDS_EQN_INFILTRATION_HAVERCAMP': mtc.mapTableChunk,
                    'EVAPOTRANSPIRATION': mtc.mapTableChunk,
                    'WELL_TABLE': mtc.mapTableChunk,
                    'OVERLAND_BOUNDARY': mtc.mapTableChunk,
                    'TIME_SERIES_INDEX': mtc.mapTableChunk,
                    'GROUNDWATER': mtc.mapTableChunk,
                    'GROUNDWATER_BOUNDARY': mtc.mapTableChunk,
                    'AREA_REDUCTION': mtc.mapTableChunk,
                    'WETLAND_PROPERTIES': mtc.mapTableChunk,
                    'MULTI_LAYER_SOIL': mtc.mapTableChunk,
                    'SOIL_EROSION_PROPS': mtc.mapTableChunk,
                    'CONTAMINANT_TRANSPORT': mtc.contamChunk,
                    'SEDIMENTS': mtc.sedimentChunk}

        indexMaps = dict()
        mapTables = []

        # Parse file into chunks associated with keywords/cards
        with io_open(path, 'r') as f:
            chunks = pt.chunk(KEYWORDS, f)

        # Parse chunks associated with each key
        for key, chunkList in iteritems(chunks):
            # Parse each chunk in the chunk list
            for chunk in chunkList:
                # Call chunk specific parsers for each chunk
                result = KEYWORDS[key](key, chunk)

                # Index Map handler
                if key == 'INDEX_MAP':

                    # Create GSSHAPY IndexMap object from result object
                    indexMap = IndexMap(name=result['idxName'])

                    # Dictionary used to map index maps to mapping tables
                    indexMaps[result['idxName']] = indexMap

                    # Associate IndexMap with MapTableFile
                    indexMap.mapTableFile = self

                    if readIndexMaps:
                        # Invoke IndexMap read method
                        indexMap.read(directory=directory, filename=result['filename'], session=session,
                                      spatial=spatial, spatialReferenceID=spatialReferenceID)
                    else:
                        # add path to file
                        indexMap.filename = result['filename']

                # Map Table handler
                else:
                    # Create a list of all the map tables in the file
                    if result:
                        mapTables.append(result)

        # Create GSSHAPY ORM objects with the resulting objects that are
        # returned from the parser functions
        self._createGsshaPyObjects(mapTables, indexMaps, replaceParamFile, directory, session, spatial, spatialReferenceID)
890655
def readResources(self, elem):
        
        try:
            iterator = getattr(elem, 'iter')
        except AttributeError:
            iterator = getattr(elem, 'getiterator')

        for include in iterator("include"):
            loc = include.attrib.get("location")

            # Apply the convention for naming the Python files generated by
            # pyrcc5.
            if loc and loc.endswith('.qrc'):
                mname = os.path.basename(loc[:-4] + self._resource_suffix)
                if mname not in self.resources:
                    self.resources.append(mname)
230844
def load_params(filepath):
    
    # Read the file
    with open(filepath) as file:
        content = file.read()

    # Detect all environment variables referenced (using %EXAMPLE%, use windows style since it is easier to match)
    q = [m.start() for m in re.finditer("%", content)]
    env_vars = []
    for i in range(0, len(q), 2):
        env_var = content[q[i]+1:q[i+1]]
        if env_var not in env_vars:
            if env_var in os.environ:
                env_vars.append(env_var)
            else:
                print("WARNING: Detected an environment variable which is not set.")
    
    # Fill in environment variables
    for env_var in env_vars:
        s = "%" + env_var + "%"
        # Use unix style path linebreaks, since windows style might break stuff (and linux is more common anyways.)
        content = content.replace(s, os.environ[env_var].replace("\\", "/"))

    # Try to match linux path style with anything that matches
    for env_var in list(os.environ.keys()):
        s = "$" + env_var
        content = content.replace(s, os.environ[env_var].replace("\\", "/"))

    # Finally load hyperparams
    return HyperParams(json.loads(jsmin(content)))
657929
def load_data_and_build(self, filename, delimiter=","):
        
        data = np.genfromtxt(
            filename, dtype=float, delimiter=delimiter, names=True
        )
        data = data.view(np.float64).reshape(data.shape + (-1,))

        X = data[:, 0:-1]
        Y = data[:, -1]

        self.build(X=X, Y=Y)
1266747
def load_env_from_file(filename):
    
    if not os.path.exists(filename):
        raise FileNotFoundError("Environment file {} does not exist.".format(filename))

    with open(filename) as f:
        for lineno, line in enumerate(f):
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            if "=" not in line:
                raise SyntaxError("Invalid environment file syntax in {} at line {}.".format(filename, lineno + 1))

            name, value = parse_var(line)

            yield name, value
1301031
def uifile(self):
        
        output = ''

        # build from a zip file
        if zipfile.is_zipfile(self.source()):
            zfile = zipfile.ZipFile(self.source(), 'r')
            if 'properties.ui' in zfile.namelist():
                tempdir = tempfile.gettempdir()
                output = os.path.join(tempdir,
                                      '{0}_properties.ui'.format(self.name()))

                f = open(output, 'w')
                f.write(zfile.read('properties.ui'))
                f.close()
            zfile.close()

        else:
            uifile = os.path.join(os.path.dirname(self.source()),
                                  'properties.ui')
            if os.path.exists(uifile):
                output = uifile

        return output
34480
def _read(self, directory, filename, session, path, name, extension, spatial, spatialReferenceID, replaceParamFile):
        
        # Set file extension property
        self.fileExtension = extension

        # Open file and read plain text into text field
        with open(path, 'r') as f:
            self.rasterText = f.read()

        # Retrieve metadata from header
        lines = self.rasterText.split('\n')
        for line in lines[0:6]:
            spline = line.split()

            if 'north' in spline[0].lower():
                self.north = float(spline[1])
            elif 'south' in spline[0].lower():
                self.south = float(spline[1])
            elif 'east' in spline[0].lower():
                self.east = float(spline[1])
            elif 'west' in spline[0].lower():
                self.west = float(spline[1])
            elif 'rows' in spline[0].lower():
                self.rows = int(spline[1])
            elif 'cols' in spline[0].lower():
                self.columns = int(spline[1])

        if spatial:
            # Get well known binary from the raster file using the MapKit RasterLoader
            wkbRaster = RasterLoader.grassAsciiRasterToWKB(session=session,
                                                           grassRasterPath=path,
                                                           srid=str(spatialReferenceID),
                                                           noData='-1')
            self.raster = wkbRaster
            self.srid = spatialReferenceID

        # Assign other properties
        self.filename = filename
308590
def _generate_to_tempfile(self, generator):
    """"""
    with temporary_file(cleanup=False, binary_mode=False) as output:
      generator.write(output)
      return output.name