Package openmdao.util

This package contains a number of utilities that are used inside of openmdao. It does not depend on any other openmdao package.

decorators.py

Some useful decorators

openmdao.util.decorators.add_delegate(*delegates)[source]

A class decorator that takes delegate classes or (name,delegate) tuples as args. For each tuple, an instance with the given name will be created in the wrapped __init__ method of the class. If only the delegate class is provided, then the instance created in the wrapped __init__ method will be named using an underscore (_) followed by the lower case name of the class. All of the public methods from the delegate classes will be added to the class unless there is an attribute or method in the class with the same name. In that case the delegate method will be ignored.

openmdao.util.decorators.forwarder(cls, fnc, delegatename)[source]

Returns a method that forwards calls on the scoping object to calls on the delegate object. The signature of the delegate method is preserved in the forwarding method.

openmdao.util.decorators.on_condition(cond, dec, *args, **kwargs)[source]

This is actually a decorator of decorators. It will cause the wrapped decorator to be applied only if the supplied value is True.

distutils_fix.py

Importing this file will fix problems we’ve found in distutils.

Current fixes are:

Update the library_dir_option function in MSVCCompiler to add quotes around /LIBPATH entries.

doctools.py

A utility to extract Traits information from the code and get it into the Sphinx documentation.

openmdao.util.doctools.get_traits_info(app, what, name, obj, options, lines)[source]

Gets traits info.

openmdao.util.doctools.setup(app)[source]

Connect the doctools to the process-docstring hook

dumpdistmeta.py

If run as main, dumpdistmeta.py will print out either a pretty-printed dict full of the metadata found in the specified distribution or just the value of a single piece of metadata if metadata-item is specified on the command line. The distribution can be in the form of an installed egg, a zipped egg, or a gzipped tar file containing a distutils distribution.

usage: dumpdistmeta.py distribution [metadata-item]

Example output:

$ dumpdistmeta.py pyparsing-1.5.1-py2.5.egg
{'SOURCES': ['README',
             'pyparsing.py',
             'setup.py',
             'pyparsing.egg-info/PKG-INFO',
             'pyparsing.egg-info/SOURCES.txt',
             'pyparsing.egg-info/dependency_links.txt',
             'pyparsing.egg-info/top_level.txt'],
 'author': 'Paul McGuire',
 'author-email': 'ptmcg@users.sourceforge.net',
 'classifier': 'Programming Language :: Python',
 'dependency_links': [],
 'description': 'UNKNOWN',
 'download-url': 'http://sourceforge.net/project/showfiles.php?group_id=97203',
 'entry_points': {},
 'home-page': 'http://pyparsing.wikispaces.com/',
 'license': 'MIT License',
 'metadata-version': '1.0',
 'name': 'pyparsing',
 'platform': None,
 'py_version': '2.5',
 'summary': 'Python parsing module',
 'top_level': ['pyparsing'],
 'version': '1.5.1',
 'zip-safe': False}

Example output:

$ dumpdistmeta.py pyparsing-1.5.1-py2.5.egg license
MIT License
openmdao.util.dumpdistmeta.get_dist_metadata(dist, dirname='')[source]

Retrieve metadata from within a distribution. Returns a dict.

openmdao.util.dumpdistmeta.get_metadata(path)[source]

Retrieve metadata from the file or directory specified by path. path can be an installed egg, a zipped egg file, or a zipped or unzipped tar file of a python distutils or setuptools source distribution.

Returns a dict.

openmdao.util.dumpdistmeta.get_resource_files(dist, exList=None, incList=None, dirname='')[source]

A generator that retrieves resource file pathnames from within a distribution.

eggloader.py

Egg loading utilities.

openmdao.util.eggloader.load(instream, fmt=4, package=None, logger=None)[source]

Load object(s) from an input stream (or filename). If instream is a string that is not an existing filename or absolute path, then it is searched for using pkg_resources. Returns the root object.

instream: file or string
Stream or filename to load from.
fmt: int
Format of state data.
package: string
Name of package to use.
logger: Logger
Used for recording progress, etc.
openmdao.util.eggloader.load_from_eggfile(filename, entry_group, entry_name, logger=None, observer=None)[source]

Extracts files in egg to a subdirectory matching the saved object name. Then loads object graph state by invoking the given entry point. Returns the root object.

filename: string
Name of egg file.
entry_group: string
Name of group.
entry_name: string
Name of entry point in group.
logger: Logger
Used for recording progress, etc.
observer: callable
Called via an EggObserver.
openmdao.util.eggloader.load_from_eggpkg(package, entry_group, entry_name, instance_name=None, logger=None, observer=None)[source]

Load object graph state by invoking the given package entry point. Returns the root object.

package: string
Name of package to load from.
entry_group: string
Name of group.
entry_name: string
Name of entry point in group.
instance_name: string
Name for instance loaded.
logger: Logger
Used for recording progress, etc.
observer: callable
Called via an EggObserver.
openmdao.util.eggloader.check_requirements(required, logger=None, indent_level=0)[source]

Display requirements (if logger debug level enabled) and note conflicts. Returns a list of unavailable requirements.

required: list
List of package requirements.
logger: Logger
Used for recording progress, etc.
indent_level: int
Used to improve readability of log messages.

eggobserver.py

class openmdao.util.eggobserver.EggObserver(observer, logger)[source]

Bases: object

Provides a convenient API for calling an observer of egg operations. observer will be called with:

  • ('analyze', filename, -1, -1) during module analysis.
  • ('add', filename, file_fraction, byte_fraction) while writing files.
  • ('copy', filename, file_fraction, byte_fraction) while copying files.
  • ('extract', filename, file_fraction, byte_fraction) while extracting files.
  • ('complete', egg_name, 1, 1) when complete.
  • ('except', message, -1, -1) when an exception occurs.
add(path, file_fraction, byte_fraction)[source]

Observe add of file. If observer returns False, raises RuntimeError.

path: string
Name of file being added.
file_fraction: float
Fraction of total files processed.
byte_fraction: float
Fraction of total bytes processed.
analyze(path)[source]

Observe analysis of file. If observer returns False, raises RuntimeError.

path: string
Name of file being analyzed.
complete(path)[source]

Observe operation complete.

path: string
Name of file saved/loaded.
copy(path, file_fraction, byte_fraction)[source]

Observe copy of file. If observer returns False, raises RuntimeError.

path: string
Name of file being copied.
file_fraction: float
Fraction of total files processed.
byte_fraction: float
Fraction of total bytes processed.
exception(msg)[source]

Observe exception.

msg: string
Exception message.
extract(path, file_fraction, byte_fraction)[source]

Observe extraction of file. If observer returns False, raises RuntimeError.

path: string
Name of file being extracted.
file_fraction: float
Fraction of total files processed.
byte_fraction: float
Fraction of total bytes processed.

eggsaver.py

Egg save utilities.

Note that pickle can’t save references to functions that aren’t defined at the top level of a module, and there doesn’t appear to be a viable workaround. Normally pickle won’t handle instance methods either, but there is code in place to work around that.

When saving to an egg, the module named __main__ changes when reloading. This requires finding the real module name and munging references to __main__. References to old-style class types can’t be restored correctly.

Also note that YAML format doesn’t handle more than one layer of back-pointers, so it’s only suitable for very flat object networks.

openmdao.util.eggsaver.save(root, outstream, fmt=4, proto=-1, logger=None)[source]

Save the state of root and its children to an output stream (or filename). If outstream is a string, then it is used as a filename. The format can be supplied in case something other than cPickle is needed. For the pickle formats, a proto of -1 means use the highest protocol.

root: object
The root of the object tree to save
outstream: file or string
Stream or filename to save to.
fmt: int
What format to save the object state in.
proto: int
What protocol to use when pickling.
logger: Logger
Used for recording progress, etc.
openmdao.util.eggsaver.save_to_egg(entry_pts, version=None, py_dir=None, src_dir=None, src_files=None, dst_dir=None, fmt=4, proto=-1, logger=None, use_setuptools=False, observer=None)[source]

Save state and other files to an egg. Analyzes the objects saved for distribution dependencies. Modules not found in any distribution are recorded in an ‘egg-info/openmdao_orphans.txt’ file. Also creates and saves loader scripts for each entry point.

entry_pts: list
List of (obj, obj_name, obj_group) tuples. The first of these specifies the root object and package name.
version: string
Defaults to a timestamp of the form ‘YYYY.MM.DD.HH.mm’.
py_dir: string
The (root) directory for local Python files. It defaults to the current directory.
src_dir: string
The root of all (relative) src_files.
dst_dir: string
The directory to write the egg in.
fmt: int
Passed to save().
proto: int
Passed to save().
use_setuptools: bool
If True, then eggwriter.write_via_setuptools() is called rather than eggwriter.write().
observer: callable
Will be called via an EggObserver intermediary.

Returns (egg_filename, required_distributions, orphan_modules).

eggwriter.py

Write Python egg files, either directly or via setuptools. Supports what’s needed for saving and loading components/simulations.

Both write() and write_via_setuptools() have the following arguments:

name: string
Must be an alphanumeric string.
version: string
Must be an alphanumeric string.
doc: string
Used for the Summary and Description entries in the egg’s metadata.
entry_map: dict
A pkg_resources EntryPoint map: a dictionary mapping group names to dictionaries mapping entry point names to EntryPoint objects.
src_files: list
List of non-Python files to include.
distributions: list
List of Distributions this egg depends on. It is used for the Requires entry in the egg’s metadata.
modules: list
List of module names not found in a distribution that this egg depends on. It is used for the Requires entry in the egg’s metadata and is also recorded in the ‘openmdao_orphans.txt’ resource.
dst_dir: string
The directory to write the egg to.
logger: Logger
Used for recording progress, etc.
observer: callable
Will be called via an EggObserver intermediary.
openmdao.util.eggwriter.egg_filename(name, version)[source]

Returns name for egg file as generated by setuptools.

name: string
Must be alphanumeric.
version: string
Must be alphanumeric.
openmdao.util.eggwriter.write(name, version, doc, entry_map, src_files, distributions, modules, dst_dir, logger, observer=None, compress=True)[source]

Write egg in the manner of setuptools, with some differences:

  • Writes directly to the zip file, avoiding some intermediate copies.
  • Doesn’t compile any Python modules.

Returns the egg’s filename.

openmdao.util.eggwriter.write_via_setuptools(name, version, doc, entry_map, src_files, distributions, modules, dst_dir, logger, observer)[source]

Write an egg via setuptools. Returns the egg’s filename.

fileutil.py

Misc. file utility routines

openmdao.util.fileutil.copy(src, dest)[source]

Copy a file or directory.

openmdao.util.fileutil.find_bzr(path=None)[source]

Return bzr root directory path or None.

openmdao.util.fileutil.find_files(pat, startdir)[source]

Return a list of files (using a generator) that match the given glob pattern. Walks an entire directory structure.

openmdao.util.fileutil.makepath(path)[source]

Creates missing directories for the given path and returns a normalized absolute version of the path.

  • If the given path already exists in the filesystem, the filesystem is not modified.
  • Otherwise makepath creates directories along the given path using the dirname() of the path. You may append a ‘/’ to the path if you want it to be a directory path.

from holger@trillke.net 2002/03/18

openmdao.util.fileutil.rm(path)[source]

Delete a file or directory.

filewrap.py

Utilities for file wrapping.

Note: This is a work in progress.

class openmdao.util.filewrap.FileParser[source]

Bases: object

Utility to locate and read data from a file.

mark_anchor(anchor, occurrence=1)[source]

Marks the location of a landmark, which lets you describe data by relative position. Note that a forward search begins at the old anchor location. If you want to restart the search for the anchor at the file beginning, then call reset_anchor() before mark_anchor.

anchor: The text you want to search for.

occurence: find nth instance of text; default is 1 (first). Use -1 to find last occurence. Reverse searches always start at the end of the file no matter the state of any previous anchor.

reset_anchor()[source]

Resets anchor to the beginning of the file.

set_delimiters(delimiter)[source]

Lets you change the delimiter that is used to identify field boundaries.

set_file(filename)[source]

Set the name of the file that will be generated.

transfer_array(rowstart, fieldstart, rowend=None, fieldend=None)[source]

Grabs an array of variables relative to the current anchor.

transfer_keyvar(key, field, occurrence=1, rowoffset=0)[source]

Searches for a key relative to the current anchor and then grabs a field from that line.

field – Which field to transfer. Field 0 is the key.

occurrence – find nth instance of text; default is 1 (first value field). Use -1 to find last occurence. Position 0 is the key field, so it should not be used as a value for occurrence.

rowoffset – Optional row offset from the occurrence of key. This can also be negative.

You can do the same thing with a call to mark_anchor and transfer_var. This function just combines them for convenience.

transfer_line(row)[source]

Returns a whole line, relative to current anchor.

row - number of lines offset from anchor line (0 is anchor line). This can be negative.

transfer_var(row, field, fieldend=None)[source]

Grabs a single variable relative to the current anchor.

— If the delimiter is ” ” —

row - number of lines offset from anchor line (0 is anchor line). This can be negative.

field - which word in line to retrieve.

fieldend - IGNORED

— If the delimiter is “columns” —

row - number of lines offset from anchor line (0 is anchor line). This can be negative.

field - character position to start

fieldend - position of last character to return

class openmdao.util.filewrap.InputFileGenerator[source]

Bases: object

Utility to generate an input file from a template. Substitution of values is supported. Data is located with a simple API.

clearline(row)[source]

Replace the contents of a row with the newline character.

row - row number to clear, relative to current anchor.

generate()[source]

Use the template file to generate the input file.

mark_anchor(anchor, occurrence=1)[source]

Marks the location of a landmark, which lets you describe data by relative position.

anchor: text to search for

occurence: find nth instance of text; default is 1 (first). Use -1 to find last occurence.

reset_anchor()[source]

Resets anchor to the beginning of the file.

set_delimiters(delimiter)[source]

Lets you change the delimiter that is used to identify field boundaries.

set_generated_file(filename)[source]

Set the name of the file that will be generated.

set_template_file(filename)[source]

Set the name of the template file to be used.

transfer_2Darray(value, row_start, row_end, field_start, field_end, sep=', ')[source]

Changes the values of a 2D array in the template relative to the current anchor. This method is specialized for 2D arrays, where each row of the array is on its own line.

value - array of values to insert.

row_start - Starting row for inserting the array. This is relative to the anchor, and can be negative.

row_end - Final row for the array, relative to the anchor.

field_start - starting field in the given row_start as denoted by delimiter(s).

field_end - the final field the array uses in row_end. We need this to figure out if the template is too small or large

sep - Optional. Separator to use if we go beyond the template

transfer_array(value, row_start, field_start, field_end, row_end=None, sep=', ')[source]

Changes the values of an array in the template relative to the current anchor. This should generally be used for one-dimensional or free form arrays.

value - array of values to insert.

row_start - starting row for inserting the array. This is relative to the anchor, and can be negative.

field_start - starting field in the given row_start as denoted by delimiter(s).

field_end - the final field the array uses in row_end. We need this to figure out if the template is too small or large

row_end - Optional. Use if the array wraps to cover additional lines.

sep - Optional. Separator to use if we go beyond the template.

transfer_var(value, row, field)[source]

Changes a single variable in the template relative to the current anchor.

row - number of lines offset from anchor line (0 is anchor line). This can be negative.

field - which word in line to replace, as denoted by delimiter(s)

class openmdao.util.filewrap.ToFloat(expr, savelist=False)[source]

Bases: pyparsing.TokenConverter

Converter to make token into a float.

postParse(instring, loc, tokenlist)[source]
class openmdao.util.filewrap.ToInteger(expr, savelist=False)[source]

Bases: pyparsing.TokenConverter

Converter to make token into an integer.

postParse(instring, loc, tokenlist)[source]

filexfer.py

openmdao.util.filexfer.filexfer(src_server, src_path, dst_server, dst_path, mode='')[source]

Transfer a file from one place to another.

If src_server or dst_server is None, then the os module is used for the source or destination respectively. Otherwise the respective object must support open(), stat(), and chmod().

mode specifies any open() mode settings in addition to ‘r’ or ‘w’.

After the copy has completed, permission bits from stat() are set via chmod().

src_server: Proxy
Host to get file from.
src_path: string
Path to file on src_server.
dst_server: Proxy
Host to put file to.
dst_path: string
Path to file on dst_server.
mode: string
Mode settings for open, not including ‘r’ or ‘w’.
openmdao.util.filexfer.pack_zipfile(patterns, filename, logger=<class 'openmdao.util.log.NullLogger'>)[source]

Create ‘zip’ file filename of files in patterns. Returns (nfiles, nbytes).

patterns: list
List of glob style patterns.
filename: string
Name of zip file to create.
logger: Logger
Used for recording progress.
openmdao.util.filexfer.unpack_zipfile(filename, logger=<class 'openmdao.util.log.NullLogger'>)[source]

Unpack ‘zip’ file filename. Returns (nfiles, nbytes).

filename: string
Nmae of zip file to unpack.
logger: Logger
Used for recording progress.

grab_distrib.py

openmdao.util.grab_distrib.grab_distrib(req, index=None, dest='.', search_pypi=True)[source]

Downloads a distribution from the given package index(s) based on the given requirement string(s). Downloaded distributions are placed in the specified destination or the current directory if no destination is specified. If a distribution cannot be found in the given index(s), the Python Package Index will be searched as a last resort unless search_pypi is False. This does NOT install the distribution.

Requirements may be supplied as strings or as Requirement objects.

log.py

This is just a wrapper for the logging module. Messages can be routed to the console via enable_console(). If the file logger.cfg exists, it can be used to configure logging. See the Python documentation for logging.config for details. The example below is equivalent to calling enable_console():

[loggers]
keys=root

[handlers]
keys=consoleHandler

[formatters]
keys=consoleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=consoleFormatter
args=(sys.stderr,)

[formatter_consoleFormatter]
format=%(levelname)s %(name)s: %(message)s
class openmdao.util.log.Logger(name, level=None)[source]

Bases: object

Pickle-able logger. Mostly a pass-through to a real logger.

critical(msg, *args, **kwargs)[source]

Log a critical message.

debug(msg, *args, **kwargs)[source]

Log a debug message.

error(msg, *args, **kwargs)[source]

Log an error message.

info(msg, *args, **kwargs)[source]

Log an information message.

log(level, msg, *args, **kwargs)[source]

Log a message at a specified level.

rename(name)[source]

Change name reported in log.

warning(msg, *args, **kwargs)[source]

Log a warning message.

level

Logging message level.

class openmdao.util.log.NullLogger[source]

Bases: object

Can be useful when no logger has been supplied to a routine. It produces no output.

critical(msg, *args, **kwargs)[source]

Log a critical message.

debug(msg, *args, **kwargs)[source]

Log a debug message.

error(msg, *args, **kwargs)[source]

Log an error message.

info(msg, *args, **kwargs)[source]

Log an information message.

log(msg, *args, **kwargs)[source]

Log a message at a specified level.

warning(msg, *args, **kwargs)[source]

Log a warning message.

openmdao.util.log.getLogger(name)[source]

Return the named logger.

openmdao.util.log.enable_console()[source]

Configure logging to receive log messages at the console.

openmdao.util.log.disable_console()[source]

Stop receiving log messages at the console.

mdo.py

Math related utility functions used by OpenMDAO.

openmdao.util.mdo.is_latin_hypercube(lh)[source]

Returns True if the given array is a latin hypercube. The given array is assumed to be a numpy array.

openmdao.util.mdo.rand_latin_hypercube(n, k, edges=False)[source]

Calculates a random latin hypercube set of n points in k dimensions within [0,1]^k hypercube.

n: int
Desired number of points.
k: int
Number of design variables (dimensions).
edges: bool, optional
if Edges=True, the extreme bins will have their centres on the edges of the domain; otherwise the bins will be entirely contained within the domain (default setting).

Returns an n by k numpy array.

mod2dist.py

A script to package into a distribution a single module containing OpenMDAO plugin classes. The script imports the module in order to determine its contents, so all dependencies must be on sys.path.

exception openmdao.util.mod2dist.Mod2DistError(msg, parser=None)[source]

Bases: exceptions.RuntimeError

openmdao.util.mod2dist.mod2dist(argv=None, groups={'openmdao.variable': <class 'enthought.traits.trait_handlers.TraitType'>, 'openmdao.driver': <class 'openmdao.main.driver.Driver'>, 'openmdao.component': <class 'openmdao.main.component.Component'>})[source]

Utility to simplify the packaging of a single module containing OpenMDAO plugin classes into a source distribution.

Use mod2dist -h to see all of the options.

The only required options are the desired version of the distribution and the module to use to generate the distribution. For example:

mod2dist -v 1.0 simple_adder.py

namelist_util.py

Utilities for reading and writing Fortran namelists.

class openmdao.util.namelist_util.Card(name, value, is_comment=0)[source]

Bases: object

Data object that stores the value of a single card for a namelist.

class openmdao.util.namelist_util.Namelist(comp)[source]

Bases: object

Utility to ease the task of constructing a formatted output file.

add_comment(comment)[source]

Add a comment in the namelist.

add_container(varpath)[source]

Add every variable in an OpenMDAO container to the namelist.

add_group(name)[source]

Add a new group to the namelist. Any variables added after this are added to this new group.

add_newvar(name, value)[source]

Add a new private variable to the namelist.

add_var(varpath)[source]

Add an openmdao variable to the namelist. varpath is the dotted path (e.g., comp1.comp2.var1).

generate()[source]

Create the input file.

set_filename(filename)[source]

Set the name of the file that will be generated or parsed.

set_title(title)[source]

Sets the title for the namelist.

parse_phoenixwrapper.py

Parses the variable definition section of a Phoenix Integration ModelCenter component wrapper.

openmdao.util.parse_phoenixwrapper.parse_phoenixwrapper(infile, outfile, compname)[source]

Generates a dummy component given a Phoenix Integration Modelcenter script wrapper. The first section of this wrapper is parsed, and the appropriate variables and containers are placed in the new OpenMDAO component.

infile - ModelCenter scriptwrapper.

outfile - File containing new OpenMDAO component skeleton.

compname - Name for new component.

procutil.py

openmdao.util.procutil.run_command(cmd, sh=True)[source]

Run a command using Popen and return its output (stdout and stderr) and its return code as a tuple.

openmdao.util.procutil.traceit(frame, event, arg)[source]

A function useful for tracing Python execution. Wherever you want the tracing to start, insert a call to sys.settrace(traceit).

shellproc.py

exception openmdao.util.shellproc.CalledProcessError(returncode, cmd, errormsg)[source]

Bases: subprocess.CalledProcessError

subprocess.CalledProcessError plus errormsg attribute.

class openmdao.util.shellproc.ShellProc(args, stdin=None, stdout=None, stderr=None, env=None)[source]

Bases: subprocess.Popen

A slight modification to subprocess.Popen. Sets the shell argument True, updates a copy of os.environ with env, and opens files for any stream which is a basestring.

close_files()[source]

Closes files that were implicitly opened.

wait(poll_delay=0.0, timeout=0.0)[source]

Polls for command completion or timeout. Closes any files implicitly opened. Returns (return_code, error_msg).

poll_delay: float (seconds)
Time to delay between polling for command completion. A value of zero uses an internal default.
timeout: float (seconds)
Maximum time to wait for command completion. A value of zero implies an infinite maximum wait.
openmdao.util.shellproc.call(args, stdin=None, stdout=None, stderr=None, env=None, poll_delay=0.0, timeout=0.0)[source]

Run command with arguments. Returns (return_code, error_msg).

args: list
List of arguments for the command.
stdin, stdout, stderr: string, file, or int
Specify handling of corresponding stream. If a string, a file of that name is opened. Otherwise see the subprocess documentation.
env: dict
Environment variables for the command.
poll_delay: float (seconds)
Time to delay between polling for command completion. A value of zero uses an internal default.
timeout: float (seconds)
Maximum time to wait for command completion. A value of zero implies an infinite maximum wait.
openmdao.util.shellproc.check_call(args, stdin=None, stdout=None, stderr=None, env=None, poll_delay=0.0, timeout=0.0)[source]

Run command with arguments. If non-zero return_code, raises CalledProcessError.

args: list
List of arguments for the command.
stdin, stdout, stderr: string, file, or int
Specify handling of corresponding stream. If a string, a file of that name is opened. Otherwise see the subprocess documentation.
env: dict
Environment variables for the command.
poll_delay: float (seconds)
Time to delay between polling for command completion. A value of zero uses an internal default.
timeout: float (seconds)
Maximum time to wait for command completion. A value of zero implies an infinite maximum wait.

stream.py

class openmdao.util.stream.Stream(file_obj, binary=False, big_endian=False, single_precision=False, integer_8=False, unformatted=False, recordmark_8=False)[source]

Bases: object

Wrapper of standard Python file object. Supports reading/writing int and float arrays in various formats.

file_obj: file
File object opened for reading or writing.
binary: bool
If True, the data is in binary, not text, form.
big_endian: bool
If True, the data bytes are in ‘big-endian’ order. Only meaningful if binary.
single_precision: bool
If True, floating-point data is 32 bits, not 64. Only meaningful if binary.
integer_8: bool
If True, integer data is 64 bits, not 32. Only meaningful if binary.
unformatted: bool
If True, the data is surrounded by Fortran record length markers. Only meaningful if binary.
recordmark_8: bool
If True, the record length markers are 64 bits, not 32. Only meaningful if unformatted.
read_float(full_record=False)[source]

Returns next float.

full_record: bool
If True, then read surrounding recordmarks. Only meaningful if unformatted.
read_floats(shape, order='C', full_record=False)[source]

Returns floats as a numpy array of shape.

full_record: bool
If True, then read surrounding recordmarks. Only meaningful if unformatted.
read_int(full_record=False)[source]

Returns next integer.

full_record: bool
If True, then read surrounding recordmarks. Only meaningful if unformatted.
read_ints(shape, order='C', full_record=False)[source]

Returns integers as a numpy array of shape.

full_record: bool
If True, then read surrounding recordmarks. Only meaningful if unformatted.
read_recordmark()[source]

Returns value of next recordmark.

reclen_floats(count)[source]

Returns record length for count floats.

count: int
Number of floats in record.
reclen_ints(count)[source]

Returns record length for count ints.

count: int
Number of ints in record.
write_array(data, order='C', sep=' ', fmt='%s', linecount=0)[source]

Writes array as text.

data: numpy.ndarray
Data array.
order: string
If ‘C’, the data is written in row-major order. If ‘Fortran’, the data is written in column-major order.
sep: string
Separator between items.
fmt: string
Format specifier for each item.
linecount: int
If > zero, then at most linecount values are written per line.
write_float(value, sep=' ', fmt='%s', full_record=False)[source]

Writes a float.

full_record: bool
If True, then write surrounding recordmarks. Only meaningful if unformatted.
write_floats(data, order='C', sep=' ', fmt='%s', linecount=0, full_record=False)[source]

Writes a float array.

data: numpy.ndarray
Float data array.
order: string
If ‘C’, the data is written in row-major order. If ‘Fortran’, the data is written in column-major order.
sep: string
Separator between items.
fmt: string
Format specifier for each item.
linecount: int
If > zero, then at most linecount values are written per line.
full_record: bool
If True, then write surrounding recordmarks. Only meaningful if unformatted.
write_int(value, sep=' ', fmt='%s', full_record=False)[source]

Writes an integer.

If full_record, then write surrounding recordmarks. Only meaningful if unformatted.

write_ints(data, order='C', sep=' ', fmt='%s', linecount=0, full_record=False)[source]

Writes an integer array.

data: numpy.ndarray
Integer data array.
order: string
If ‘C’, the data is written in row-major order. If ‘Fortran’, the data is written in column-major order.
sep: string
Separator between items.
fmt: string
Format specifier for each item.
linecount: int
If > zero, then at most linecount values are written per line.
full_record: bool
If True, then write surrounding recordmarks. Only meaningful if unformatted.
write_recordmark(length)[source]

Writes recordmark.

length: int
Length of record (bytes).

testutil.py

Utilities for the OpenMDAO test process

openmdao.util.testutil.assertRaisesError(test_case_instance, code, err_type, err_msg)[source]

Determine that code raises err_type with err_msg.

openmdao.util.testutil.assert_raises(test_case, code, globals, locals, exception, msg, use_exec=False)[source]

Determine that code raises exception with msg.

test_case: unittest.TestCase
TestCase instance used for assertions.
code: string
Statement to be executed.
globals, locals: dict
Arguments for eval().
exception: Exception
Exception that should be raised.
msg: string
Expected message from exception.
use_exec: bool
If True, then evaluate code with exec rather than eval. This is necessary for testing statements that are not expressions.
openmdao.util.testutil.assert_rel_error(test_case, actual, desired, tolerance)[source]

Determine that the relative error between actual and desired is within tolerance.

test_case: unittest.TestCase
TestCase instance used for assertions.
actual: float
The value from the test.
desired: float
The value expected.
tolerance: float
Maximum relative error (actual - desired) / desired.
openmdao.util.testutil.find_python()[source]

Return path to the OpenMDAO python command

openmdao.util.testutil.make_protected_dir()[source]

Returns the the absolute path of an inaccessible directory. Files cannot be created in it, it can’t be os.chdir() to, etc. Not supported on Windows.

openmdao.util.testutil.print_timing(func)[source]

view_docs.py

openmdao.util.view_docs.view_docs(browser=None)[source]

A script (openmdao_docs) points to this. It just pops up a browser to view the openmdao Sphinx docs. If the docs are not already built, it builds them before viewing; but if the docs already exist, it’s not smart enough to rebuild them if they’ve changed since the last build.

If this is run from a non-developer install, i.e., there is no local copy of the docs, it just looks for the docs on the openmdao.org website.

wrkpool.py

class openmdao.util.wrkpool.WorkerPool[source]

Bases: object

Pool of worker threads; grows as necessary.

static cleanup()[source]

Cleanup resources (worker threads).

static get()[source]

Get a worker queue from the pool. Work requests should be of the form:

(callable, *args, **kwargs, reply_queue)

Work replies are of the form:

(queue, retval, exc, traceback)

static get_instance()[source]

Return singleton instance.

static release(queue)[source]

Release a worker queue back to the pool.

queue: Queue
Worker queue previously obtained from get().