def write(self, sile, *args, **kwargs): """ Writes a density matrix to the `Sile` as implemented in the :code:`Sile.write_density_matrix` method """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): sile.write_density_matrix(self, *args, **kwargs) else: get_sile(sile, 'w').write_density_matrix(self, *args, **kwargs)
def write(self, sile, *args, **kwargs): """ Writes a tight-binding model to the `Sile` as implemented in the :code:`Sile.write_hamiltonian` method """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): sile.write_hamiltonian(self, *args, **kwargs) else: get_sile(sile, 'w').write_hamiltonian(self, *args, **kwargs)
def write(self, sile, *args, **kwargs): """ Writes a tight-binding model to the `Sile` as implemented in the :code:`Sile.write_es` method """ self.finalize() # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): sile.write_es(self, *args, **kwargs) else: get_sile(sile, 'w').write_es(self, *args, **kwargs)
def __call__(self, parser, ns, value, option_string=None): out = value[0] from sisl.io import get_sile, TableSile try: # We figure out if the user wants to write # to a geometry obj = get_sile(out, mode='w') if hasattr(obj, 'write_geom'): obj.write_geom(ns._geometry) return raise NotImplementedError except: pass if len(ns._data) == 0: # do nothing if data has not been collected return TableSile(out, mode='w').write(np.array(ns._data), comment=ns._data_description, header=ns._data_header) # Clean all data ns._data_description = [] ns._data_header = [] ns._data = [] # These are expert options ns._Ovalue = '' ns._Orng = None ns._Oscale = 1. / len(ns._tbt.pivot) ns._Erng = None ns._krng = None
def write(self, sile, *args, **kwargs): """ Writes the Overlap to the `Sile` as implemented in the :code:`Sile.write_overlap` method """ from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): sile.write_overlap(self, *args, **kwargs) else: with get_sile(sile, 'w') as fh: fh.write_overlap(self, *args, **kwargs)
def write(self, sile): """ Writes grid to the `Sile` using `write_grid` Parameters ---------- sile : Sile, str a `Sile` object which will be used to write the grid if it is a string it will create a new sile using `get_sile` """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): sile.write_grid(self) else: get_sile(sile, 'w').write_grid(self)
def write(self, sile, *args, **kwargs): """ Writes a Hessian to the `Sile` as implemented in the :code:`Sile.write_hessian` method """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): sile.write_hessian(self, *args, **kwargs) else: with get_sile(sile, 'w') as fh: fh.write_hessian(self, *args, **kwargs)
def metric(self, variables): """ Read the force from the `self.file` in `path` """ try: force = self.force(get_sile(self.file).read_force()) metric = self.failure(force, False) _log.debug(f"metric.force [{self.file}] success {metric}") except: metric = self.failure(0., True) _log.debug(f"metric.force [{self.file}] fail {metric}") return metric
def __call__(self, parser, ns, values, option_string=None): routine = values.pop(0) # Default input file input_file = getattr(ns, '_input_file', None) # Figure out which of the segments are a file for i, val in enumerate(values): if osp.isfile(str_spec(val)[0]): input_file = values.pop(i) break # Quick return if there is no input-file... if input_file is None: return # Try and read the vector from sisl.io import get_sile input_sile = get_sile(input_file, mode='r') vector = None if hasattr(input_sile, f'read_{routine}'): vector = getattr(input_sile, f'read_{routine}')(*values) if vector is None: # Try the read_data function d = {routine: True} vector = input_sile.read_data(*values, **d) if vector is None and len(values) > 1: # try and see if the first argument is a str, if # so use that as a keyword if isinstance(values[0], str): d = {values[0]: True} vector = input_sile.read_data(*values[1:], **d) # Clean the sile del input_sile if vector is None: # Use title to capitalize raise ValueError( '{} could not be read from file: {}.'.format( routine.title(), input_file)) if len(vector) != len(ns._geometry): raise ValueError( f'read_{routine} could read from file: {input_file}, sizes does not conform to geometry.' ) setattr(ns, '_vector', vector)
def read(sile, *args, **kwargs): """ Reads SuperCell from the `Sile` using `Sile.read_sc` Parameters ---------- sile : `Sile`, str a `Sile` object which will be used to read the supercell if it is a string it will create a new sile using `get_sile`. """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): return sile.read_sc(*args, **kwargs) else: return get_sile(sile).read_sc(*args, **kwargs)
def read(sile, *args, **kwargs): """ Reads grid from the `Sile` using `read_grid` Parameters ---------- sile : Sile, str a `Sile` object which will be used to read the grid if it is a string it will create a new sile using `get_sile`. * : args passed directly to ``read_grid(,**)`` """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): return sile.read_grid(*args, **kwargs) else: return get_sile(sile).read_grid(*args, **kwargs)
def read(sile, *args, **kwargs): """ Reads Overlap from `Sile` using `read_overlap`. Parameters ---------- sile : Sile, str or pathlib.Path a `Sile` object which will be used to read the Overlap and the overlap matrix (if any) if it is a string it will create a new sile using `get_sile`. * : args passed directly to ``read_overlap(,**)`` """ from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): return sile.read_overlap(*args, **kwargs) else: with get_sile(sile) as fh: return fh.read_overlap(*args, **kwargs)
def read(sile, *args, **kwargs): """ Reads the supercell from the `Sile` using ``Sile.read_supercell`` Parameters ---------- sile : Sile, str or pathlib.Path a `Sile` object which will be used to read the supercell if it is a string it will create a new sile using `sisl.io.get_sile`. """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): return sile.read_supercell(*args, **kwargs) else: with get_sile(sile) as fh: return fh.read_supercell(*args, **kwargs)
def read(sile, *args, **kwargs): """ Reads Hamiltonian from `Sile` using `read_H`. Parameters ---------- sile : `Sile`, str a `Sile` object which will be used to read the Hamiltonian and the overlap matrix (if any) if it is a string it will create a new sile using `get_sile`. * : args passed directly to ``read_es(,**)`` """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): return sile.read_es(*args, **kwargs) else: return get_sile(sile).read_es(*args, **kwargs)
def read(sile, *args, **kwargs): """ Reads dynamical matrix from `Sile` using `read_dynamical_matrix`. Parameters ---------- sile : Sile, str or pathlib.Path a `Sile` object which will be used to read the dynamical matrix. If it is a string it will create a new sile using `get_sile`. * : args passed directly to ``read_dynamical_matrix(,**)`` """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): return sile.read_dynamical_matrix(*args, **kwargs) else: with get_sile(sile) as fh: return fh.read_dynamical_matrix(*args, **kwargs)
def __call__(self, parser, ns, values, option_string=None): routine = values.pop(0) # Default input file input_file = getattr(ns, '_input_file', None) # Figure out which of the segments are a file for i, val in enumerate(values): if osp.isfile(val): input_file = values.pop(i) break # Quick return if there is no input-file... if input_file is None: return # Try and read the vector from sisl.io import get_sile input_sile = get_sile(input_file, mode='r') vector = None if hasattr(input_sile, 'read_{}'.format(routine)): vector = getattr(input_sile, 'read_{}'.format(routine))(*values) if vector is None: # Try the read_data function d = {routine: True} vector = input_sile.read_data(*values, **d) # Clean the sile del input_sile if vector is None: # Use title to capitalize raise ValueError( '{} could not be read from file: {}.'.format( routine.title(), input_file)) if len(vector) != len(ns._geometry): raise ValueError( '{} could read from file: {}, does not conform to read geometry.' .format(routine.title(), input_file)) setattr(ns, '_vector', vector)
def read(sile, *args, **kwargs): """ Reads density matrix from `Sile` using `read_energy_density_matrix`. Parameters ---------- sile : `Sile`, str a `Sile` object which will be used to read the density matrix and the overlap matrix (if any) if it is a string it will create a new sile using `get_sile`. * : args passed directly to ``read_energy_density_matrix(,**)`` """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): return sile.read_energy_density_matrix(*args, **kwargs) else: with get_sile(sile) as fh: return fh.read_energy_density_matrix(*args, **kwargs)
def __call__(self, parser, ns, values, option_string=None): routine = values.pop(0) # Default input file input_file = getattr(ns, '_input_file', None) # Figure out which of the segments are a file for i, val in enumerate(values): if osp.isfile(val): input_file = values.pop(i) break # Quick return if there is no input-file... if input_file is None: return # Try and read the vector from sisl.io import get_sile input_sile = get_sile(input_file, mode='r') vector = None if hasattr(input_sile, 'read_{}'.format(routine)): vector = getattr(input_sile, 'read_{}'.format(routine))() if vector is None: # Try the read_data function d = dict() d[routine] = True vector = input_sile.read_data(*values, **d) # Clean the sile del input_sile if vector is None: # Use title to capitalize raise ValueError('{} could not be read from file: {}.'.format(routine.title(), input_file)) if len(vector) != len(ns._geometry): raise ValueError('{} could read from file: {}, does not conform to read geometry.'.format(routine.title(), input_file)) setattr(ns, '_vector', vector)
def read(sile, *args, **kwargs): """ Reads grid from the `Sile` using `read_grid` Parameters ---------- sile : Sile, str a `Sile` object which will be used to read the grid if it is a string it will create a new sile using `get_sile`. * : args passed directly to ``read_grid(,**)`` """ # This only works because, they *must* # have been imported previously from sisl.io import get_sile, BaseSile if isinstance(sile, BaseSile): return sile.read_grid(*args, **kwargs) else: sile, spec = str_spec(sile) if spec is not None: if ',' in spec: kwargs['spin'] = list(map(float, spec.split(','))) else: kwargs['spin'] = int(spec) with get_sile(sile) as fh: return fh.read_grid(*args, **kwargs)
def sgrid(grid=None, argv=None, ret_grid=False): """ Main script for sgrid script. This routine may be called with `argv` and/or a `Sile` which is the grid at hand. Parameters ---------- grid : `Grid`/`BaseSile` this may either be the grid, as-is, or a `Sile` which contains the grid. argv : `list of str` the arguments passed to sgeom ret_grid : `bool` (`False`) whether the function should return the grid """ import sys import os.path as osp import argparse from sisl.io import get_sile, BaseSile # The file *MUST* be the first argument # (except --help|-h) # We cannot create a separate ArgumentParser to retrieve a positional arguments # as that will grab the first argument for an option! # Start creating the command-line utilities that are the actual ones. description = """ This manipulation utility is highly advanced and one should note that the ORDER of options is determining the final structure. For instance: {0} ElectrostaticPotential.grid.nc --diff Other.grid.nc --sub z 0.:0.2f is NOT equivalent to: {0} ElectrostaticPotential.grid.nc --sub z 0.:0.2f --diff Other.grid.nc This may be unexpected but enables one to do advanced manipulations. """.format(osp.basename(sys.argv[0])) if argv is not None: if len(argv) == 0: argv = ['--help'] elif len(sys.argv) == 1: # no arguments # fake a help argv = ['--help'] else: argv = sys.argv[1:] # Ensure that the arguments have pre-pended spaces argv = cmd.argv_negative_fix(argv) p = argparse.ArgumentParser('Manipulates real-space grids in commonly encounterd files.', formatter_class=argparse.RawDescriptionHelpFormatter, description=description) # First read the input "Sile" if grid is None: argv, input_file = cmd.collect_input(argv) try: grid = get_sile(input_file).read_grid() except: grid = Grid([10, 10, 10]) elif isinstance(grid, Grid): # Do nothing, the geometry is already created argv = ['fake.grid.nc'] + argv pass elif isinstance(grid, BaseSile): try: grid = sile.read_grid() # Store the input file... input_file = grid.file except Exception as E: grid = Grid([10, 10, 10]) argv = ['fake.grid.nc'] + argv # Do the argument parser p, ns = grid.ArgumentParser(p, **grid._ArgumentParser_args_single()) # Now the arguments should have been populated # and we will sort out if the input options # is only a help option. try: if not hasattr(ns, '_input_file'): setattr(ns, '_input_file', input_file) except: pass # Now try and figure out the actual arguments p, ns, argv = cmd.collect_arguments(argv, input=False, argumentparser=p, namespace=ns) # We are good to go!!! args = p.parse_args(argv, namespace=ns) g = args._grid if not args._stored_grid: # We should write out the information to the stdout # This is merely for testing purposes and may not be used for anything. print(g) if ret_grid: return g return 0
def sgrid(grid=None, argv=None, ret_grid=False): """ Main script for sgrid script. This routine may be called with `argv` and/or a `Sile` which is the grid at hand. Parameters ---------- grid : `Grid`/`BaseSile` this may either be the grid, as-is, or a `Sile` which contains the grid. argv : `list of str` the arguments passed to sgeom ret_grid : `bool` (`False`) whether the function should return the grid """ import sys import os.path as osp import argparse from sisl.io import get_sile, BaseSile # The file *MUST* be the first argument # (except --help|-h) # We cannot create a separate ArgumentParser to retrieve a positional arguments # as that will grab the first argument for an option! # Start creating the command-line utilities that are the actual ones. description = """ This manipulation utility is highly advanced and one should note that the ORDER of options is determining the final structure. For instance: {0} ElectrostaticPotential.grid.nc --diff Other.grid.nc --sub z 0.:0.2f is NOT equivalent to: {0} ElectrostaticPotential.grid.nc --sub z 0.:0.2f --diff Other.grid.nc This may be unexpected but enables one to do advanced manipulations. """.format(osp.basename(sys.argv[0])) if argv is not None: if len(argv) == 0: argv = ['--help'] elif len(sys.argv) == 1: # no arguments # fake a help argv = ['--help'] else: argv = sys.argv[1:] # Ensure that the arguments have pre-pended spaces argv = cmd.argv_negative_fix(argv) p = argparse.ArgumentParser('Manipulates real-space grids in commonly encounterd files.', formatter_class=argparse.RawDescriptionHelpFormatter, description=description) # First read the input "Sile" if grid is None: argv, input_file = cmd.collect_input(argv) try: grid = get_sile(input_file).read_grid() except: grid = Grid([10,10,10]) elif isinstance(grid, Grid): # Do nothing, the geometry is already created argv = ['fake.grid.nc'] + argv pass elif isinstance(grid, BaseSile): try: grid = sile.read_grid() # Store the input file... input_file = grid.file except Exception as E: grid = Grid([10,10,10]) argv = ['fake.grid.nc'] + argv # Do the argument parser p, ns = grid.ArgumentParser(p, **grid._ArgumentParser_args_single()) # Now the arguments should have been populated # and we will sort out if the input options # is only a help option. try: if not hasattr(ns, '_input_file'): setattr(ns, '_input_file', input_file) except: pass # Now try and figure out the actual arguments p, ns, argv = cmd.collect_arguments(argv, input=False, argumentparser=p, namespace=ns) # We are good to go!!! args = p.parse_args(argv, namespace=ns) g = args._grid if not args._stored_grid: # We should write out the information to the stdout # This is merely for testing purposes and may not be used for anything. print(g) if ret_grid: return g return 0
def sgrid(grid=None, argv=None, ret_grid=False): """ Main script for sgrid. This routine may be called with `argv` and/or a `Sile` which is the grid at hand. Parameters ---------- grid : Grid or BaseSile this may either be the grid, as-is, or a `Sile` which contains the grid. argv : list of str the arguments passed to sgrid ret_grid : bool, optional whether the function should return the grid """ import sys import os.path as osp import argparse from sisl.io import get_sile, BaseSile # The file *MUST* be the first argument # (except --help|-h) # We cannot create a separate ArgumentParser to retrieve a positional arguments # as that will grab the first argument for an option! # Start creating the command-line utilities that are the actual ones. description = """ This manipulation utility is highly advanced and one should note that the ORDER of options is determining the final structure. For instance: {0} ElectrostaticPotential.grid.nc --diff Other.grid.nc --sub z 0.:0.2f is NOT equivalent to: {0} ElectrostaticPotential.grid.nc --sub z 0.:0.2f --diff Other.grid.nc This may be unexpected but enables one to do advanced manipulations. """.format(osp.basename(sys.argv[0])) if argv is not None: if len(argv) == 0: argv = ['--help'] elif len(sys.argv) == 1: # no arguments # fake a help argv = ['--help'] else: argv = sys.argv[1:] # Ensure that the arguments have pre-pended spaces argv = cmd.argv_negative_fix(argv) p = argparse.ArgumentParser('Manipulates real-space grids.', formatter_class=argparse.RawDescriptionHelpFormatter, description=description) # Add default sisl version stuff cmd.add_sisl_version_cite_arg(p) # First read the input "Sile" stdout_grid = True if grid is None: from os.path import isfile argv, input_file = cmd.collect_input(argv) kwargs = {} if input_file is None: stdout_grid = False grid = Grid(0.1, geometry=Geometry([0] * 3, sc=1)) else: # Extract specification of the input file input_file, spec = str_spec(input_file) if spec is not None: if ',' in spec: kwargs['spin'] = list(map(float, spec.split(','))) else: kwargs['spin'] = int(spec) if isfile(input_file): grid = get_sile(input_file).read_grid(**kwargs) elif not isfile(input_file): from .messages import info info("Cannot find file '{}'!".format(input_file)) elif isinstance(grid, BaseSile): # Store the input file... input_file = grid.file grid = grid.read_grid() # Do the argument parser p, ns = grid.ArgumentParser(p, **grid._ArgumentParser_args_single()) # Now the arguments should have been populated # and we will sort out if the input options # is only a help option. try: if not hasattr(ns, '_input_file'): setattr(ns, '_input_file', input_file) except: pass # Now try and figure out the actual arguments p, ns, argv = cmd.collect_arguments(argv, input=False, argumentparser=p, namespace=ns) # We are good to go!!! args = p.parse_args(argv, namespace=ns) g = args._grid if stdout_grid and not args._stored_grid: # We should write out the information to the stdout # This is merely for testing purposes and may not be used for anything. print(g) if ret_grid: return g return 0
def collect_arguments(argv, input=False, argumentparser=None, namespace=None): """ Function for returning the actual arguments depending on the input options. This function will create a fake `argparse.ArgumentParser` which then will pass through the input figuring out which options that should be given to the final `argparse.ArgumentParser`. Parameters ---------- argv : list of str the argument list that comprise the arguments input : bool, optional whether or not the arguments should also gather from the input file. argumentparser : argparse.ArgumentParser, optional the argument parser that should add the options that we find from the output and input files. namespace : argparse.Namespace, optional the namespace for the argument parser. """ # First we figure out the input file, and the output file from sisl.io import get_sile # Create the default namespace in case there is none if namespace is None: namespace = default_namespace() if input: argv, input_file = collect_input(argv) else: input_file = None # Grap output-file p = argparse.ArgumentParser('Parser for output file', add_help=False) p.add_argument('--out', '-o', nargs=1, default=None) # Parse the passed args to sort out the input file and # the output file args, _ = p.parse_known_args(argv) if input_file is not None: try: obj = get_sile(input_file) argumentparser, namespace = obj.ArgumentParser( argumentparser, namespace=namespace, **obj._ArgumentParser_args_single()) # Be sure to add the input file setattr(namespace, '_input_file', input_file) except Exception as e: print(e) raise ValueError( f"File: '{input_file}' cannot be found. Please supply a readable file!" ) if args.out is not None: try: obj = get_sile(args.out[0], mode='r') obj.ArgumentParser_out(argumentparser, namespace=namespace) except Exception: # Allowed pass due to pythonic reading pass return argumentparser, namespace, argv