Utilities
- class baseclasses.utils.CaseInsensitiveDict(*args, **kwargs)[source]
Python dictionary where the keys are case-insensitive. Note that this assumes the keys are strings, and indeed will fail if you try to create an instance where keys are not strings. All common Python dictionary operations are supported, and additional operations can be added easily. In order to preserve capitalization on key initialization, the implementation relies on storing a dictionary of mappings, which are used to check any new keys against existing keys and compare them in a case-insensitive fashion.
- Attributes:
- datadict
The equivalent case-sensitive dictionary. This stores the actual values.
- mapdict
Dictionary of mappings between the lowercase representation and the initial capitalization.
Warning
This container preserves the initial capitalization, such that any operation which operates on an existing entry will not modify it. This means that for example
__setitem__()
will NOT update the original capitalization.
- class baseclasses.utils.CaseInsensitiveSet(*args, **kwargs)[source]
Python set where the elements are case-insensitive. Note that this assumes the elements are strings, and indeed will fail if you try to create an instance where elements are not strings. All common Python set operations are supported, and additional operations can be added easily. In order to preserve capitalization on key initialization, the implementation relies on storing a dictionary of mappings which are used to check any new keys against existing keys and compare them in a case-insensitive fashion.
- Attributes:
- dataset
The equivalent case-sensitive set.
- mapdict
Dictionary of mappings between the lowercase representation and the initial capitalization.
- exception baseclasses.utils.Error(message)[source]
Format the error message in a box to make it clear this was a explicitly raised exception.
- class baseclasses.utils.SolverHistory(includeIter=True, includeTime=True)[source]
The SolverHistory class can be used to store and print various useful values during the execution of a solver.
NOTE: The implementation of this class contains no consideration of parallelism. If you are using a solverHistory object in your parallel solver, you will need to take care over which procs you make calls to the SolverHistory object on.
Create a solver history instance
- Parameters:
- includeIterbool, optional
Whether to include the history’s internal iteration variable in the history, by default True
- includeTimebool, optional
Whether to include the history’s internal timing variable in the history, by default True
- addMetadata(name, data)[source]
Add a piece of metadata to the history
The metadata attribute is simply a dictionary that can be used to store arbitrary information related to the solution being recorded, e.g solver options
- Parameters:
- namestr
Item name/key
- dataAny
Item to store
- addVariable(name, varType, printVar=False, valueFormat=None, overwrite=False)[source]
Define a new field to be stored in the history.
- Parameters:
- namestr
Variable name
- varTypeType
Variable type, i.e int, float, str etc
- printVarbool, optional
Whether to include the variable in the iteration printout, by default False
- valueFormatstr, optional
Format string valid for use with the str.format() method (e.g “{:17.11e}” for a float or “{:03d}” for an int), only important for variables that are to be printed. By default a predefined format for the given varType is used
- overwritebool, optional
Whether to overwrite any existing variables with the same name, by default False
- getIter()[source]
Get the current number of iterations recorded
- Returns:
- int
Number of iterations recorded
- printData(iters=None)[source]
Print a selection of lines from the history
Each line will look something like this:
| 0 | 1.000e-01 | -84 | 2.87098307489e-01 | ... |
- Parameters:
- itersint or Iterable of ints, optional
Iteration numbers to print, by default only the last iteration will be printed
- printHeader()[source]
Print the header of the iteration printout
The header will look something like this:
+--------------------------------------------------------------------...------+ | Iter | Time | Random Int | Random Float | ... | +--------------------------------------------------------------------...------+
- reset(clearMetadata=False)[source]
Reset the history to its initial state.
- Parameters:
- clearMetadatabool, optional
Whether to clear the metadata too, by default False
- save(fileName)[source]
Write the solution history to a pickle file
Only the data dictionary is saved
- Parameters:
- fileNamestr
File path to save the solution history to, file extension not required, will be ignored if supplied
- startTiming()[source]
Record the start time of the solver
This function only needs to be called explicitly if the start time of your solver is separate from the first time the write method is called.
- write(data)[source]
Record data for a single iteration
Note that each call to this method is treated as a new iteration. All data to be recorded for a single solver iteration must therefore be recorded in a single call to this method.
- Parameters:
- datadict
Dictionary of values to record, with variable names as keys
- writeFullVariableHistory(name, values)[source]
Write the entire history of a variable in one go
This function should be used in the case where your solver already handles the recording of variables during a solution (e.g ADflow) but you want to use a SolverHistory object to facilitate writing it to a file
- Parameters:
- namestr
Variable name
- valuesIterable
Values to record, will be converted to a list
- baseclasses.utils.getPy3SafeString(string)[source]
Accepts a string and makes sure it’s converted to unicode for python 3.6 and above
- baseclasses.utils.pp(obj, comm=None, flush=True)[source]
Parallel safe printing routine. This method prints
obj
(via pprint) on the root proc ofself.comm
if it exists. Otherwise it will just printobj
.- Parameters:
- objobject
Any Python object to be printed
- commMPI comm
The MPI comm object on this processor
- flushbool
If True, the stream will be flushed.
- baseclasses.utils.readJSON(fname, comm=None)[source]
Reads a JSON file and return the contents as a dictionary. This includes a custom NumPy reader to retrieve NumPy arrays, matching the
writeJSON()
function.- Parameters:
- file_namestr
The file name
- commmpi4py.MPI.Comm, optional
The communicator over which this function is called. If supplied, only the root proc will be used for file IO.
References
This is based on this stack overflow answer
- baseclasses.utils.readPickle(fname, comm=None)[source]
This is a parallel pickle.load function, which is performed on the root proc only. Error checking is necessary to provide py2 compatibility.
- Parameters:
- fnamestr
The pickle file name
- commmpi4py.MPI.Comm, optional
The communicator over which this function is called. If supplied, only the root proc will be used for file IO.
- Returns:
- objThe object stored in the pickle file
- baseclasses.utils.redirectIO(f_out, f_err=None)[source]
This function redirects stdout/stderr to the given file handle.
- Parameters:
- f_outfile
A file stream to redirect stdout to
- f_errfile
A file stream to redirect stderr to. If none is specified it is set to f_out
- baseclasses.utils.redirectingIO(f_out, f_err=None)[source]
A function that redirects stdout in a with block and returns to the stdout after the with block completes. The filestream passed to this function will be closed after exiting the with block.
Here is an example of usage where all adflow output is redirected to the file adflow_out.txt:
>>> from baseclasses.utils import redirectIO >>> print("Printing some information to terminal") >>> with redirectIO.redirectingIO(open("adflow_out.txt", "w")): ... CFDSolver = ADFLOW(options=options) ... CFDSolver(AeroProblem(**apOptions) >>> print("Printing some more information to terminal")
- Parameters:
- f_outfile
A file stream that stdout should be redirected to
- f_errfile
A file stream to redirect stderr to. If none is specified it is set to f_out
- baseclasses.utils.writeJSON(fname, obj, comm=None)[source]
Write an object to a JSON file. This includes a custom NumPy encoder to reliably write NumPy arrays to JSON, which can then be read back via
readJSON()
.- Parameters:
- fnamestr
The file name
- objdict or ndarray
The object to be written to JSON
- commmpi4py.MPI.Comm, optional
The communicator over which this function is called. If supplied, only the root proc will be used for file IO.
- baseclasses.utils.writePickle(fname, obj, comm=None)[source]
Parallel pickle writing function, only performs operations on the root proc
- Parameters:
- fnamestr
The pickle file name
- objany object which can be pickled by Python
The object to be pickled
- commmpi4py.MPI.Comm, optional
The communicator over which this function is called. If supplied, only the root proc will be used for file IO.