inputoutput

Class summary

GenericInputFileArgParser(obj[, …]) Pass input files to a class/function, then call methods on the object
InputFileLoaderCheckerSaver([reader, …]) A class for accepting an input file, running checks, saveing data/plots.
PrefixNumpyArrayString([prefix]) When printing a numpy array string prefix ‘array’
SimpleTimer() Simple timer to display start, end, and elapsed wall clock time of code execution.
SyntaxChecker([allow]) Check if a string contains only allowabel python syntax
print_all_nodes Simple ast.NodeVisitor sub class that prints each node when visited

Function summary

check_attribute_PolyLines_have_same_x_limits(obj) Check if attributes of object that are PolyLine have the same x values
check_attribute_combinations(obj[, …]) Check for incomplete combinations of attributes
check_attribute_is_list(obj[, attributes, …]) Check if attributes of an object are lists
check_attribute_pairs_have_equal_length(obj) Check if attribute pairs have the same length
code_for_explicit_attribute_initialization([…]) Generate code to initialize an objects attributes
copy_attributes_between_objects(from_object, …) Copy attributes from one object to another
copy_attributes_from_text_to_object(reader, …) Wrapper for copy_attributes_between_objects where from_object is fileobject, StringIO, text
fcode_one_large_expr(expr[, prepend]) Fortran friendly printing of sympy expression ignoring any loops/indexed
force_attribute_same_len_if_none(obj[, …]) Make list of None with len the same as an existing attribute
get_filepaths([wildcard]) dialog box to select files
hms_string(sec_elapsed) Convert seconds to human readable h:min:seconds
initialize_objects_attributes(obj[, …]) Initialize an objects attributes
make_array_into_dataframe(data[, …]) Make an array into a pandas dataframe
make_module_from_text(reader[, syntax_checker]) Make a module from file, StringIO, text etc.
modules_in_package(package_name[, exclude]) List of modules in a package
next_output_stem(prefix[, path, start, inc, …]) Find next unique prefix-number in sequence of numbered files/folders
object_members(obj[, info, join]) Get a list of object members.
save_grid_data_to_file(data_dicts[, …]) Save grid data to files using a common filename stem
string_of_object_attributes(obj[, …]) Put repr of objects attributes into one string
working_directory(path) Change working directory for duration of with statement

Module listing

Input/output operations,attribute checking, proccess input files that have python syntax.

class geotecha.inputoutput.inputoutput.GenericInputFileArgParser(obj, pass_open_file=True, methods=[], prog=None, description='Process some input files', epilog='If no options are specifyied then the user will be prompted to select files.')[source]

Bases: object

Pass input files to a class/function, then call methods on the object

see self.main for use in scripts.

The working directory will be changed to the location of each input file

Basically the path of each input file is passed to the method self.process.

Parameters:
obj : object/callable

Object to call with input file as argument.

methods : sequence of 3 element tuples, optional

Each element of methods is a 3 element tuple (method_name, args, kwargs). After obj has been initialized the obj’s method called ‘method_name’ will be called with unpacked args and kwargs. i.e. obj(filename).method_name(*args, **kwargs). Default methods=[] i.e. no methods called.

pass_open_file : True/False, optional

If True then input files will be passed to obj as open file objects. If False then paths of the input files will be passed to obj. Default pass_open_file=True

prog : string, optional

Part of usage method for argparse, the name of the program. Default prog=None which uses sys.argv[0] i.e. the first command line paramter.

description : string, optional

Part of usage method for argparse. Default description=”Process some input files”.

epilog : string, optional

Part of usage method for argparse. Default epilog=’If no options are specifyied then the user will be prompted to select files.’

See also

argparse
better description of some of the variables.

Notes

For basic usage, in a file to be used as a script put:

if __name__=='__main__':
    a = GenericInputFileArgParser(obj_to_call)
    a.main()

Methods

main([argv]) Accept command line arguments and pass files/paths to self.obj
process(path) Process the input file path
main(argv=None)[source]

Accept command line arguments and pass files/paths to self.obj

Allows users to specify files via the command line in various ways:

1. If no options are specifyied a dialog box will open for the user to select files. 2. A list of file paths can be specified with the –filename option 3. The –directory and –pattern options can be used together to search a particular directory for files matching a certain pattern. If no actual directory is specified then the current working directory will be used. The default pattern to look for is “*.py”. The script file itself will not be processed if it matches the pattern itself.

Parameters:
argv : list of str, optional

List of command line arguments. Default argv=None which will grab arguments from sys.argv. Used mainly for testing or bypassing script based command line arguments.

process(path)[source]

Process the input file path

The default behaviour of self.process depends on self.pass_open_file. If True then path will be opened and then self.obj will be called with the opened file as the argument. If False then then self.obj will be called with the path itself as argument.

If you need more complicated behaviour to process your input file (e.g. initalize self.obj with a path and then call one of it’s methods) then over write this method.

Parameters:
path : string

Absolute path to input file.

class geotecha.inputoutput.inputoutput.InputFileLoaderCheckerSaver(reader=None, pkg_for_version='geotecha')[source]

Bases: object

A class for accepting an input file, running checks, saveing data/plots.

Options to:

  • Accept an inputfile with python syntax
  • Copy attribute value from a text file (i.e. text such as ‘b = 34’ in the input file will be result in self.b=34)
  • Run checks on the attributes.
  • Save data to file
  • Save figures to file.
  • Common attributes along with their defaults are available to all classes that sub-class InputFileLoaderCheckerSaver.
Parameters:
reader : file_like object

Object to get text from. file, StringIO, text etc.

pkg_for_version : string, optional

The version attribute will be determined by the version number of the pkg_for_version package. Default pkg_for_version=’geotecha’. If for some reason pkg_for_version has not been set, or the package cannot be found, then version will be ‘unknown’.

Notes

For the _attributes and _attribute_defaults attribute the common attributes and their defualts are:

Attributes:
_attributes : list of string

User defined list of attributes. Must be defined in the sub-class. A number of common attributes will be added to the user defined list. See the Notes section for the common attributes and their default values.

_attribute_defaults : dict, optional

User defined dict of attribute defaults. May be defined in the sub-class. Defaults for the common attributes will will be added to the user defined list. When no default value is given , None will be used. Default _attribute_defaults=dict() i.e. all user defaults are None. See the Notes section for the common attributes and their default values.

_attributes_that_should_be_lists : list of string, optional

list of attributes that should be of type list. Those attributes that are not None and not lists will be put in a list. May be defined in the sub-class.

_attributes_that_should_have_same_x_limits : list of list of str, optional

Each sublist is a list of attribute names to check. May be defined in the sub-class.

_attributes_that_should_have_same_len_pairs : list of list of two string

List of attribute names to check. Each sub-list should have two elements. May be defined in the sub-class.

_zero_or_all : list of list of string

Each element of zero_or_all is a list of attribute names that should either all be None or all be not None. May be defined in the sub-class.

_at_least_one : list of list of string

Each element of at_least_one is a list of attribute names of which at least one should not be None. May be defined in the sub-class.

_one_implies_others : list of list of string

Each element of one_implies_others is a list of attribute names. If the first attribute in the list is not None then all other members of the list should also not be None. May be defined in the sub-class.

_input_text : string

str of the input file. Will be None if no reader is passed to the __init__ method

_debug : True/False

For use with debugging. Default _debug=False

_figures : list of matplotlib figures

Define in sub-class. Each figure should have a label which will be used to save figures.

_grid_data_dicts : list of dict

Define in sub-class. For saving grid_data to file using save_grid_data_to_file.

_file_stem: string

path including file name prefix with number for all output files. default=’out_000’. If create_directory=True then files will be put in a folder named file_stem

Methods

check_input_attributes() Perform checks on attributes
check_input_attributes()[source]

Perform checks on attributes

class geotecha.inputoutput.inputoutput.PrefixNumpyArrayString(prefix='np.')[source]

Bases: object

When printing a numpy array string prefix ‘array’

If you use repr to print a numpy array it will print as ‘array([…])’. If you have imported numpy with ‘import numpy.array as array’ or some such import then you can paste the printed output straight back into Python. However, I use ‘import numpy as np’ so I have to manually put in the ‘np.’ before I can use the printed output in my code. Using PrefixNumpyArrayString can put in the ‘np.’ automatically when using the __str__ of the numpy array. i.e. __repr__ remains unchanged but __str__ will have the prefix

Examples

>>> print(np.arange(3))
[0 1 2]
>>> a=PrefixNumpyArrayString('numpy.')
>>> a.turn_on()
>>> print(np.arange(3))
numpy.array([0, 1, 2])
>>> a.turn_off()
>>> print(np.arange(3))
[0 1 2]
Attributes:
prefix : string, optional

string to prefix with. Default prefix=’np.’.

Methods

turn_off() Turn_on printing numpy array with prefix
turn_on() Turn_on printing numpy array with prefix
turn_off()[source]

Turn_on printing numpy array with prefix

turn_on()[source]

Turn_on printing numpy array with prefix

class geotecha.inputoutput.inputoutput.SimpleTimer[source]

Bases: object

Simple timer to display start, end, and elapsed wall clock time of code execution.

Messages displayed when start and finish methods called.

Attributes:
start_times : dict

Start times corresponding to each timing level.

messages : dict

Message/title corresponding to each timeing level.

end_times : dict

end times corresponding to each timing level.

Methods

finish(i) Print message saying timing level i has finished along with the elapsed time.
start(i[, msg]) Print message saying timing level i has started.
finish(i)[source]

Print message saying timing level i has finished along with the elapsed time.

i : int
index of timed process. Numerical value of i will detemine indent of printed message. If i==0 then row of astericks will be printed after finish message.
start(i, msg=None)[source]

Print message saying timing level i has started.

i : int
index of timed process. Numerical value of i will detemine indent of printed message. If i==0 then row of astericks will be printed before message.
msg : string, optional
title of timing process. printed message will be “Started ” + msg. Default msg=None which will make “Started Level i” appear.
class geotecha.inputoutput.inputoutput.SyntaxChecker(allow=[])[source]

Bases: ast.NodeVisitor

Check if a string contains only allowabel python syntax

SyntaxChecker provides functionality to check syntax of string using the ast module. Basically white-list allowable functions and attributes. A SyntaxError will be raised if any code is found that is not allowed.

Parameters:
allow : list of str

List of SyntaxChecker ‘allow’ methods to call. Default = []. e.g. allow=[‘ast’, ‘numpy’] will call SyntaxChecker.allow_ast(), SyntaxChecker.allow_numpy()

See also

ast.NodeVisitor
Parent class. Descriptions of python syntax grammar.
object_members
Easily print a string of an objects routines for use in a ‘allow_<some_name>’ method.

Notes

If subclassing new ‘allow_<some_name>’ methods can be written to bulk add allowable functions and attributes.

Examples

>>> syntax_checker = SyntaxChecker(allow=['ast', 'builtin', 'numpy'])
>>> tree = ast.parse('a=np.cos(0.5)', mode='exec')
>>> syntax_checker.visit(tree)
>>> syntax_checker = SyntaxChecker(allow=['ast', 'builtin', 'numpy'])
>>> tree = ast.parse('a=cos(0.5)', mode='exec')
>>> syntax_checker.visit(tree)
Traceback (most recent call last):
    ...
SyntaxError: cos is not an allowed function!
Attributes:
allowed_functions : dict

A dictionary of allowable functions. e.g. allowed_functions[‘cos’] = math.cos would permit the use of ‘cos’ from the math module. allowed_functions[‘math’] = math would allow use of the math module (note to allow things like ‘math.sin’ you would also have to add ‘sin’ to the allowable_attributes). Adding functions one by one can be cumbersome; see the ‘allow_<some_name>’ methods for bulk adding of common functionality.

allowed_node_types : dict

Dictionary of allowable ast node names. e.g. allowed_node_types[‘Name’] = ast.Name would allow ast.Name nodes. typically use SytaxChecker.allow_ast to allow a reasonable set of ast nodes

allowed_attributes : set of string

set of allowable attributes. e.g. you have already allowed the math module with allowed_functions[‘math’] = math. allowable_attributes.add(‘tan’) will allow use of math.tan(34) etc. Note that the attribute ‘tan’ could now be used as an attribute for any of the functions in allowed_functions even though this may not make any logical sense. i.e. it will pass the SyntaxChecker but would fail if the code was executed. Adding attributes one by one can be cumbersome; see the ‘allow_<some_name>’ methods for bulk adding of common functionality.

safe_names : dict

Dictionary of safe names. Default safe_names={‘True’: True, ‘False’: False, ‘None’: None}.

print_each_node : bool

Print out each node when they are visited. Default print_each_node=False. Note that nodes may be printed twice, once for a generic visit and once for a specific visit such as visit_Name, visit_Attribute etc.

Methods

allow_ast() Allow subset of ast node types
allow_builtin() Allow subset of __builtins__ functions
allow_numpy() Allow a subset of numpy functionality via np.attribute syntax
allow_PolyLine() Allow PolyLine class from geotecha.piecewise.piecewise_linear_1d
allow_PolyLine()[source]

Allow PolyLine class from geotecha.piecewise.piecewise_linear_1d

allow_ast()[source]

Allow subset of ast node types

allow_builtin()[source]

Allow subset of __builtins__ functions

allow_numpy()[source]

Allow a subset of numpy functionality via np.attribute syntax

generic_visit(node)[source]

Custom visit a generic node

visit_Attribute(node)[source]

Custom visit an ‘Attribute’ node

visit_Call(node)[source]

Custom visit a ‘Call’ node

visit_Name(node)[source]

Custom visit a ‘Name’ node

geotecha.inputoutput.inputoutput.check_attribute_PolyLines_have_same_x_limits(obj, attributes=[])[source]

Check if attributes of object that are PolyLine have the same x values

Each attribute can be a single instance of PolyLine or a list of PolyLines. An error is raised if x-values are different.

Parameters:
obj : object

Object with attributes to check.

attributes : list of list of strings

Each sublist is a list of attribute names to check.

geotecha.inputoutput.inputoutput.check_attribute_combinations(obj, zero_or_all=[], at_least_one=[], one_implies_others=[])[source]

Check for incomplete combinations of attributes

Raises ValueError if any combination fails.

Parameters:
zero_or_all : list of list of string

Each element of zero_or_all is a list of attribute names that should either all be None or all be not None.

at_least_one : list of list of string

Each element of at_least_one is a list of attribute names of which at least one should not be None.

one_implies_others : list of list of string

Each element of one_implies_others is a list of attribute names. If the first attribute in the list is not None then all other members of the list should also not be None.

Returns:
None
geotecha.inputoutput.inputoutput.check_attribute_is_list(obj, attributes=[], force_list=False)[source]

Check if attributes of an object are lists

If attribute is not a list and `force_list`=True then attribute will be placed in list. e.g. say obj.a = 6, 6 is not a list so obj.a will be changed to obj.a = [6]. An error is raised if attribute is not a list.

Parameters:
obj : object

Object with attributes to check.

attributes : list of strings

A list of attribute names to check.

force_list : bool, optional

If True not-list attributes will be put in a list. If False then non-list attributes will raise an error. Default force_list=False.

Returns:
None
geotecha.inputoutput.inputoutput.check_attribute_pairs_have_equal_length(obj, attributes=[])[source]

Check if attribute pairs have the same length

Compares pairs only if both pairs are not None. Raises error if pair items have unequal lenghth.

Parameters:
obj : object

Object with attributes to check.

attributes : list of list of two string

List of attribute names to check. Each sub-list should have two elements.

geotecha.inputoutput.inputoutput.code_for_explicit_attribute_initialization(attributes=[], defaults={}, defaults_name='_attribute_defaults', object_name='self', not_found_value=None)[source]

Generate code to initialize an objects attributes

Parameters:
object_name : string , optional

Name of object to set attributes. default=’self’.

attributes : list of strings

A list of attribute names to set.

defaults : dict of string-value pairs

Dictionary specifying the default value of each attribute.

defaults_name : string, optional

If None then the actual values in defaults will be used to set attributes. If not None then those attributes with defaults will be initialized by pointing to a dictionary called defaults_name. Default defaults_name=’_attribute_defaults’,

not_found_value : optional

Default value to set attribute to if not found in defaults. default not_found_value=``None``

Returns:
out : string

Code that can be pasted into an object (usually in the __init__ methos) to explicitly initialize attributes, so the attributes appear in autocomplete.

See also

initialize_objects_attributes
Similar functionality with no copy paste.
geotecha.inputoutput.inputoutput.copy_attributes_between_objects(from_object, to_object, attributes=[], defaults={}, not_found_value=None)[source]

Copy attributes from one object to another

Looks up attributes in from_obj and copies them to to_object. If not present in from_object the corresponding attribute in to_object will be set to defaults or not_found_value if not in defaults.

Parameters:
from_object : object or module

Object to copy attributes from.

to_object : object or module

Object to copy attributes to.

attributes : list of strings

A list of attribute names to copy from from_object to object_to.

defaults : dict of string-value pairs

Dictionary specifying the default value of each attribute that is not found in from_object.

not_found_value : optional

Default value to set attribute to if not found in from_object or in defaults. Default not_found_value=None.

Returns:
None
geotecha.inputoutput.inputoutput.copy_attributes_from_text_to_object(reader, *args, **kwargs)[source]

Wrapper for copy_attributes_between_objects where from_object is fileobject, StringIO, text

Parameters:
reader : fileobject, StringIO, text

text to turn into a module and pass as from_object

*args :

Positional arguments that will be passed to copy_attributes_between_objects.

**kwargs :

Keyword arguments that will be passed to copy_attributes_between_objects. You can use a SyntaxChecker object to interpret the reader by using the keyword argument ‘syntax_checker’=<some SyntaxChecker object>.

See also

copy_attributes_between_objects
See for args and kwargs input.
SyntaxChecker
Restrict the allowable syntax in the reader.

Notes

Put ‘syntax_checker= ‘ in the kwargs to add a SyntaxChecker

geotecha.inputoutput.inputoutput.fcode_one_large_expr(expr, prepend=None, **settings)[source]

Fortran friendly printing of sympy expression ignoring any loops/indexed

The normal FcodePrinter.doprint method will try to figure out what fortran loops you need by looking for indexed expressions. Sometimes you just want to change square brackets [] to parenteses () and wrap/indent the code for Fortran with appropriate line continuations. fcode_one_large_expr can do that for you. You will have to write your own fortran do loops.

Parameters:
expr : sympy expression

A single large sympy expression.

prepend : string, optional

A string to prepend to your fortran code. Assuming you are going to cut and paste into a fortran routine prepend should be correct fortran format. (note you do not need an initial indent for your prepend it will be put in for you). e.g. prepend = ‘a(i, i) = a(i, i) + ‘. Defualt prepend=None i.e. nothing prepended.

settings : keyword arguments

See sympy.printing.fcode docs, specifically FCodePrinter.__init__ . Note that ‘assign_to will not work’.

Returns:
out : str

Fortran ready code that can be copy and pasted into a Fortran routine.

See also

sympy.printing.fcode
contains all the functionality.
geotecha.inputoutput.inputoutput.force_attribute_same_len_if_none(obj, same_len_attributes=[], value=None)[source]

Make list of None with len the same as an existing attribute

If attributes after the first are None then make those attributes a list of len(first_attribute) filled with value. This is useful when you want to zip each member of two attributes. If the second attribute is None, then any zipping is impossible. However, if the second attribute is set to a list of None then zipping is possible.

Parameters:
obj : object

Object that has the attributes.

same_len_attributes : list of list of string

For each group of attribute names, if attributes after the first are None then those attributes will be made a list of len(first_attribute) filled with value.

value : obj, optional

Value to fill each list. Default value=None.

geotecha.inputoutput.inputoutput.get_filepaths(wildcard='')[source]

dialog box to select files

Opens a dialog box from which the user can select files

Parameters:
wildcard : string, optional

Only show file types of this kind. Default wildcard=”” which means no file type filtering. e.g. “BMP files (.bmp)|.bmp|GIF files (.gif)|.gif”

Returns:
filepaths: list of paths

List of user selected file paths. Will return None if the cancel button was selected.

geotecha.inputoutput.inputoutput.hms_string(sec_elapsed)[source]

Convert seconds to human readable h:min:seconds

Parameters:
sec_elapsed : float

Elapsed seconds

References

Copied verbatim from http://arcpy.wordpress.com/2012/04/20/146/

geotecha.inputoutput.inputoutput.initialize_objects_attributes(obj, attributes=[], defaults={}, not_found_value=None)[source]

Initialize an objects attributes

For each attribute, set it to the value found in defaults dictionary or, if the attribute is not found, set it to not_found_value.

Parameters:
obj : object

Object to set attributes in.

attributes : list of strings

A list of attribute names to set.

defaults : dict of string-value pairs, optional

Dictionary specifying the default value of each attribute. Default defautls=dict() i.e. no explicit default value.

not_found_value : optional

Default value to set attribute to if not found in defaults dict. Default not_found_value=None.

See also

code_for_explicit_attribute_initialization
Use for temporary explicit attribute initialization to facilitate auto-complete, then comment out when done.

Notes

If using this function to initialize attributes in a class then just be aware that the attributes will not be available for auto-complete until an instance of the class is created. This can be annoying when coding the class itself because typing ‘self.’ will not have any autocomplete options. To work around this use a temporary explicit assignment e.g. ‘self.a = 6’ and then later comment it out when coding of the class is finsihed.

geotecha.inputoutput.inputoutput.make_array_into_dataframe(data, column_labels=None, row_labels=None, row_labels_label='item')[source]

Make an array into a pandas dataframe

The data frame will have no index. Use df.set_index().

Parameters:
data : 2d array

Data to be put int

column_labels : list or 1d array, optional

Column lables for data. Default column_labels=None which will give column numbers 0,1,2, etc.

row_labels : list or 1d array, optional

Default row_labels=None which will use row numbers, 0,1,2,etc.

row_labels_label : string, optional

Column label for the row_labels column. Default row_labels_label=’item’.

Returns:
df : pandas dataframe

dDtaframe of data with column and row labels added

geotecha.inputoutput.inputoutput.make_module_from_text(reader, syntax_checker=None)[source]

Make a module from file, StringIO, text etc.

Parameters:
reader : file_like object

Object to get text from.

syntax_checker : SyntaxChecker object, optional

Specifies what syntax is allowed when executing the text within reader. Default = None, which means that text will be executed with the all powerful all dangerous exec function. Only use this option if you trust the input.

Returns:
m : module

text as module

See also

SyntaxChecker
allow certain syntax

Notes

I suspect it is best if reader is a string. i.e reader can be pickled. fileobjects may be cause issues if used with multiprocessing.process

geotecha.inputoutput.inputoutput.modules_in_package(package_name, exclude=['test'])[source]

List of modules in a package

Parameters:
package_name : string

Name of package to import and get modules from.

exclude : list of string, optional

Module names to exclude. Default exclude=[‘test’]

Returns:
module_list : lsit of string

List of modules in package_name ommiting any names in the exclude list.

geotecha.inputoutput.inputoutput.next_output_stem(prefix, path=None, start=1, inc=1, zfill=3, overwrite=False)[source]

Find next unique prefix-number in sequence of numbered files/folders

Looks in folder of path for files/folders with prefix-number combos of the form ‘prefixdddxyz.ext’. If found then the ddd is incremented by inc and the new ‘prefixddd’ is returned. E.g. if file ‘prefix004_exact.out’ exists you will get ‘prefix_005’ as the next output stem.

Parameters:
prefix : string

Start of file/folder name to search for.

path : string, optional

Folder to seach in. Default path=None i.e. search in current working directory.

start : int, optional

If no existing files/folders match the numbering will start at start. Default start=1.

inc : int, optional

If matching files/folders are found then the number will increment by inc. Default inc=1.

zfill : int, optional

Fill number with zeros to the left. eg. if zfill is 3 and the number is 8, then the number will be output as ‘008’.

overwrite : True/False

When True the prefix-number combo will not be incremented and the highest exisiting prefix-number combo will be returned.

Returns:
stem : string

Next output stem.

geotecha.inputoutput.inputoutput.object_members(obj, info='function', join=True)[source]

Get a list of object members.

Parameters:
obj : object

Object to get members of.

info : string, optional

Type of members to gather. Members will be gathered according to inspect.is<member_type>. e.g. info=’function’ will check in object for inspect.isfunction. Other values include ‘method’ ‘function’ ‘routine’. Default info=’function’. NOTE that it is safer to use ‘routine’ when getting functions. There is a custom check for info=’ufunc’ to give ufunc members of numpy.

join : bool, optional

If join==True then list will be joined together into one large space separated string.

Returns:
members : list of str, or str

List of member names of specified types, or space separated names i single string.

class geotecha.inputoutput.inputoutput.print_all_nodes[source]

Bases: ast.NodeVisitor

Simple ast.NodeVisitor sub class that prints each node when visited

Examples

>>> text="a=[3,2]*2"
>>> x=print_all_nodes()
>>> tree=ast.parse(text)
>>> x.visit(tree)
     Module : Module(body=[Assign(targets=[Name(id='a', ctx=Store())], value=BinOp(left=List(elts=[Num(n=3), Num(n=2)], ctx=Load()), op=Mult(), right=Num(n=2)))])
     Assign : Assign(targets=[Name(id='a', ctx=Store())], value=BinOp(left=List(elts=[Num(n=3), Num(n=2)], ctx=Load()), op=Mult(), right=Num(n=2)))
     Name : Name(id='a', ctx=Store())
     Store : Store()
     BinOp : BinOp(left=List(elts=[Num(n=3), Num(n=2)], ctx=Load()), op=Mult(), right=Num(n=2))
     List : List(elts=[Num(n=3), Num(n=2)], ctx=Load())
     Num : Num(n=3)
     Num : Num(n=2)
     Load : Load()
     Mult : Mult()
     Num : Num(n=2)

Methods

generic_visit(node) Called if no explicit visitor function exists for a node.
visit(node) Visit a node.
generic_visit(node)[source]

Called if no explicit visitor function exists for a node.

geotecha.inputoutput.inputoutput.save_grid_data_to_file(data_dicts, directory=None, file_stem='out_000', create_directory=True, ext='.csv')[source]

Save grid data to files using a common filename stem

Saves grid data in directory. Each data filename will begin with file_stem. Grid data is basically 2d data with rows and columns.

Parameters:
data_dicts : list of dict or single dict

Each data_dict contains info for outputing a piece of data to a file. Although the data_dicts parameter is listed last, each data_dict should appear at the start of the argument list when calling the function.

data_dict key description
name String to be added to end of stem to create file_name.
data array of data to save to file. If data is a pandas dataframe then row_labels and column labels will be ignored (i.e. it will be assumed that the dataframe already has row labels and column labels).
row_labels List of row labels for data. default = None which will give no row labels.
row_labels_label If there are row_labels then the column label for the row_label column. Default = None which will give ‘item’.
column_labels Column lables for data. Default = None which will give nothing.
header String to appear before data. Default = None.
df_kwargs dict of kwargs to pass to pandas.DataFrame.to_csv(). Default ={}.
directory : string, optional

Path of directory to save data in. Default directory=None which will save to the current working directory.

file_stem : string, optional

beginning of file name, Default file_stem=’out_000’. Filename will be made from file_stem + [data_dict`[‘name’]] + `ext.

ext : string, optional

File extension. Default ext=”.csv”.

create_directory : True/False, optional

If True, all data files will be placed in a directory named file_stem. So you might get files path_to_directoryout_000out_000_cow.csv etc. If False, all data files will be placed in directory. So you would get files path_to_directoryout_000_cow.csv etc. Default create_directory=True.

geotecha.inputoutput.inputoutput.string_of_object_attributes(obj, attributes=[], none_at_bottom=True, numpy_array_prefix='np.')[source]

Put repr of objects attributes into one string

The repr of each attribute will be put in a line within the output string. If the attribute is not found then None will be given.

Parameters:
obj : object

Object containing attributes.

attributes : list of string, optional

List of attribute names.

none_at_bottom : True/False

If True then any attribute that is None will be placed at the end of the output string.

numpy_array_prefix : string, optional

repr of numpy arrays by default do not print with anything in front of ‘array’. with numpy_array_prefix wou can add a ‘np.’ etc. default= ‘np.’ Use None for no prefix.

Returns:
out : str

String

geotecha.inputoutput.inputoutput.working_directory(path)[source]

Change working directory for duration of with statement

Parameters:
path : str

Path to new current working directory

Notes

e.g. with working_directory(datastuff):

References

Taken straight from http://stackoverflow.com/a/3012921/2530083