InputFile#
- class nextnanopy.InputFile(fullpath=None, configpath=None, parse=False, text=None)#
Bases:
InputFileTemplateLoad a nextnano input file as the product-specific class that fits it.
InputFile(fullpath)detects the product from the file’s text and returns an instance of that product’s class (nextnanopy.nnp.inputs.InputFile,nextnanopy.nn3.inputs.InputFile, and so on), or a bareInputFileTemplateif the text matches no known product.Pass
textto build from a string instead of from disk:InputFile(text=...)detects the product from that text and never opens a file.fullpathis then just the name to give the result —InputFile(fullpath, text=...)reads nothing, butsave()writes there. With neither, there is nothing to detect and nothing to load, so an emptyInputFileTemplatecomes back.See also
InputFileTemplateParameters, attributes and methods of the object returned.
Notes
Build from a string at construction time, not by assignment afterwards.
InputFile(text=...)works;InputFile()followed by.text = ...does not. The latter cannot work:InputFile()has no text to detect from, so it returns a product-agnosticInputFileTemplatewhoseload_variables()is a no-op, and assigningtextafterwards cannot re-class the object it is called on. The text round-trips, butvariablesstays empty andproductstays'not valid', silently. Dispatch happens in__new__or not at all, so the contents must be supplied at construction. (Assigningtextto a file loaded from a path is fine — that object is already a product class.)Two limitations follow from dispatching in
__new__, both deliberate:The result is not an InputFile. The product classes are siblings of this class, not subclasses, so
isinstance(InputFile(fullpath), InputFile)isFalse. Check against, annotate with, and subclassInputFileTemplate— the base every product class shares.This class cannot be subclassed.
__new__picks the class from the file’s contents and ignorescls, so a subclass would be silently discarded; it raisesTypeErrorinstead. To extend one product, subclass that product’s class; to extend all of them, subclassInputFileTemplate.
- execute(show_log=True, convergenceCheck=False, convergence_check_mode='pause', overwrite=False, create_subdirectory=True, **kwargs)#
Execute the input file located at
fullpath.Individual kwargs can be passed like
licenseordatabase; anything not given comes fromconfig.- Parameters:
- show_logbool, default=True
If False, do not print the simulation log to the console. The log file is written either way.
- convergenceCheckbool, default=False
If True, check the log for convergence once the simulation has finished. Ignored when the file is executed in parallel, as a sweep or an execution queue does.
- convergence_check_mode{‘pause’, ‘terminate’, ‘continue’}
What to do when the simulation did not converge. Only used when
convergenceCheckis True.‘pause’: ask the user how to proceed. If no interactive terminal is attached (e.g. CI, cluster jobs), behaves like ‘terminate’ instead of blocking on input.
‘terminate’: terminate the script.
‘continue’: notify the user but continue the script. This is also the only mode that tolerates a missing log file.
- overwritebool, default=False
If False, the output directory is created under an unused name: an index is appended (
example_0,example_1, …) when the name is already taken, so a run never writes into an earlier run’s output. If True, an existing directory is used as it is - which means writing next to whatever the earlier run left there; nothing is deleted. Has no effect whencreate_subdirectoryis False.- create_subdirectorybool, default=True
If True, the simulation writes into
<outputdirectory>/<input file name>/. If False, it writes into theoutputdirectoryitself.- **kwargsdict
The nextnano product’s own command line arguments, passed on as they are. Anything not given here comes from
config.kwargsmay contain:- exestr, optional
Path to the executable.
- licensestr, optional
Path to the license file.
- databasestr, optional
Path to the database file.
- outputdirectorystr, optional
Path where to save the simulated data.
and other parameters depending on the nextnano product. For example, ‘threads’ is accepted by nextnano++. See the documentation of the command line arguments of each nextnano product on the online Manual (https://www.nextnano.com/docu/).
- Returns:
- dict
Information about the started simulation, also stored in
execute_info. Keys: ‘process’, ‘outputdirectory’, ‘filename’, ‘logfile’, ‘cmd’, ‘wdir’, ‘queue’, ‘tout’, ‘terr’.
- Raises:
- ValueError
If
fullpathis empty or is not an existing file, or ifconvergence_check_modeis not one of the values listed above.- FileNotFoundError
If the executable path in
configis empty or invalid.- RuntimeError
If
convergenceCheckis True and the simulation was terminated or did not converge, unlessconvergence_check_modeis ‘continue’.- NotImplementedError
If
convergenceCheckis True and the product is nextnano.MSB.
Notes
The simulation is launched through the system shell, so
execute_info['process']is the shell process, not the simulator itself. On Windows, callingkill()/terminate()on it stops only the shell wrapper; the running simulation is NOT stopped.Where the output goes is decided by
overwrite/create_subdirectory, which are parameters rather than members of**kwargs: they steer nextnanopy, not the simulator, so they are also not config options.folder_outputholds the directory that was chosen once the run has started.
- property folder_output#
Folder where the simulated data is stored. Read-only.
- Returns:
- pathlib.Path
Output directory of the last execution, as chosen by
execute()fromoverwriteandcreate_subdirectory.
- Raises:
- KeyError
If the input file has not been executed yet.
- get_variable(name)#
Return the input variable called
name.Equivalent to
variables[name], except that only lookup by name is supported:variablesalso accepts an integer index, this method does not.- Parameters:
- namestr
Name of the input variable.
- Returns:
- InputVariable
The input variable stored under
name.
- Raises:
- KeyError
If
nameis not a key ofvariables.
- load(fullpath, text=None)#
Load the input file.
The steps are the following:
Clear the
raw_lines,variablesandfullpathattributes.Load the raw text (updates the
fullpathandraw_linesattributes).Find the nextnano product (updates
product).Validate the input file.
Load the input variables (updates
variables).Load the content, when applicable.
- Parameters:
- fullpathstr or pathlib.Path
Path to the file to be loaded.
- textstr, default=None
Contents of
fullpath, if the caller has already read them. Saves re-reading the file from disk. If omitted, the file is read here.
- Raises:
- FileNotFoundError
If
fullpathdoes not exist andtextis not given.
- preview(nums=True)#
Print the text of the file.
- Parameters:
- numsbool, default=True
If True, prefix each line with its index, starting at 0.
- save(fullpath=None, overwrite=False, automkdir=True, temp=False, content=False)#
Save the current information into a file.
The
fullpathattribute is updated to the path that was written.- Parameters:
- fullpathstr or pathlib.Path, default=None
Path including the file name where it will be saved. If None, the
fullpathattribute is used.- overwritebool, default=False
If False, an index is appended to the file name when it is already taken (
example.nnp, thenexample_0.nnp,example_1.nnp, …), so an existing file is never overwritten. If True, the file is written even if it exists and no index is appended.- automkdirbool, default=True
If True, create the parent folder if it does not exist.
- tempbool, default=False
If True, save into a temporary folder that is removed when the process exits, keeping the current
filename. Ignored with a warning whenfullpathis given.- contentbool, default=False
Experimental feature, refrain from using it. If True, save the parsed
contentattribute instead oftext. Comments are not preserved. It requires the file to be loaded withparse=True.
- Returns:
- str
Path of the file that was written. Not necessarily
fullpath: withoverwrite=Falsean index may have been appended.
- Raises:
- ValueError
If neither the
fullpathargument nor thefullpathattribute is set, or ifcontentis True and the file was not loaded withparse=True.- FileNotFoundError
If
automkdiris False and the parent folder does not exist.
- set_variable(name, value=None, comment=None, unit=None)#
Change the value, the comment and/or the unit of an input variable.
- Parameters:
- namestr
Name of the input variable.
- valueint, float or str, default=None
New value of the variable. If None, the value is left unchanged.
- commentstr, default=None
New comment of the variable. If None, the comment is left unchanged.
- unitstr, default=None
New unit of the variable. If None, the unit is left unchanged. The unit is not part of the input file text: it only feeds the
unitandlabelattributes of the variable.
- Returns:
- InputVariable
The input variable that was changed.
- Raises:
- KeyError
If
nameis not a key ofvariables.