PyLaGriT

class pylagrit.PyLaGriT(lagrit_exe=None, verbose=True, batch=False, batchfile='pylagrit.lgi', gmv_exe=None, paraview_exe=None, timeout=300, *args, **kwargs)

Python lagrit class

Parameters:
  • lagrit_exe (str) – Path to LaGriT executable
  • verbose (bool) – If True, LaGriT terminal output will be displayed
  • batch (bool) – If True, PyLaGriT will be run in batch mode, collecting LaGriT commands until the run_batch method is called.
  • batchfile (str) – Name of batch file to use if batch is True
  • gmv_exe (str) – Path to GMV executable
  • paraview_exe (str) – Path to ParaView executable
  • timeout – Number of seconds to wait for response from LaGriT
addmesh(mo1, mo2, style='add', name=None, *args)
addmesh_add(mo1, mo2, name=None, refine_factor=None, refine_style='edge')
addmesh_amr(mo1, mo2, name=None)
addmesh_append(mo1, mo2, name=None)
addmesh_delete(mo1, mo2, name=None)
addmesh_excavate(mo1, mo2, name=None, bfs=False, connect=False)
addmesh_glue(mo1, mo2, name=None)
addmesh_intersect(pset, mo1, mo2, name=None)
addmesh_merge(mo1, mo2, name=None)
addmesh_pyramid(mo1, mo2, name=None)
boundary_components(style='node', material_id_number=None, reset=None)

Calculates the number of connected components of a mesh for diagnostic purposes.

Parameters:
  • style (string) – May be element or node
  • material_id_number (int) – Only examines nodes with imt = mat. id number
  • reset (bool) – May be either True, False, or None
cmo_status(cmo=None, brief=False, verbose=True)
convert(pattern, new_ft)

Convert File(s)

For each file of the pattern, creates a new file in the new_ft format. The new files will be inside the directory that the LaGriT object was instantiated. The name of each file will be the same as the original file with the extension changed to new_ft.

Supports conversion from avs, and gmv files. Supports conversion to avs, exo, and gmv files.

Parameters:
  • pattern (str) – Path, name or unix style file pattern of files to be converted.
  • new_ft (str) – New format to convert files.
Example:
>>> #To use pylagrit, import the module.
>>> import pylagrit
>>>
>>> #Create your pylagrit session.
>>> lg = pylagrit.PyLaGriT()
>>>
>>> #Create a mesh object and dump it to a gmv file 'test.gmv'.
>>> mo = lg.create(name='test')
>>> mo.createpts_brick_xyz((5,5,5), (0,0,0), (5,5,5,))
>>> mo.dump('gmv', 'test.gmv')
>>>
>>> #Convert test.gmv to exoduce and contour files.
>>> lg.convert('test.gmv', 'exo')
>>> lg.convert('test.gmv', 'avs')
copy(mo, name=None)

Copy Mesh Object

Copies a mesh object, mo, and returns the MO object.

create(elem_type='tet', name=None, npoints=0, nelements=0)

Create a Mesh Object

Creates a mesh object in lagrit and an MO in the LaGriT object. Returns the mesh object.

Parameters:
  • name (str) – Name to be given to the mesh object.
  • mesh (str) – The type of mesh object to create.
  • npoints (int) – The number of points.
  • nelements (int) – The number of elements.

Returns: MO

create_hex(name=None, npoints=0, nelements=0)

Create a hexagon mesh object.

create_hyb(name=None, npoints=0, nelements=0)

Create a hybrid mesh object.

create_line(npoints=0, mins=[], maxs=[], rz_switch=(1, 1, 1), name=None)

Create a line mesh object.

create_pri(name=None, npoints=0, nelements=0)

Create a prism mesh object.

create_pyr(name=None, npoints=0, nelements=0)

Create a pyramid mesh object.

create_qua(name=None, npoints=0, nelements=0)

Create a quadrilateral mesh object.

create_tet(name=None, npoints=0, nelements=0)

Create a tetrahedron mesh object.

create_tri(name=None, npoints=0, nelements=0)

Create a triangle mesh object.

create_triplane(name=None, npoints=0, nelements=0)

Create a triplane mesh object.

createpts(crd, npts, mins, maxs, elem_type, vc_switch=(1, 1, 1), rz_switch=(1, 1, 1), rz_value=(1, 1, 1), connect=False, name=None)

Create and Connect Points

Parameters:
  • crd (str) – Coordinate type of either ‘xyz’ (cartesian coordinates), ‘rtz’ (cylindrical coordinates), or ‘rtp’ (spherical coordinates).
  • npts (tuple(int)) – The number of points to create in line
  • mins (tuple(int, int, int)) – The starting value for each dimension.
  • maxs (tuple(int, int, int)) – The ending value for each dimension.
  • elem_type (str) – The type of mesh object to create
  • vc_switch (tuple(int, int, int)) – Determines if nodes represent vertices (1) or cell centers (0).
  • rz_switch (tuple(int, int, int)) – Determines true or false (1 or 0) for using ratio zoning values.
Returns:

MO

createpts_dxyz(dxyz, mins, maxs, elem_type, clip='under', hard_bound='min', rz_switch=(1, 1, 1), rz_value=(1, 1, 1), connect=True, name=None)

Create and Connect Points to create an orthogonal hexahedral mesh. The vertex spacing is based on dxyz and the mins and maxs specified. mins (default, see hard_bound option) or maxs will be adhered to, while maxs (default) or mins will be modified based on the clip option to be truncated at the nearest value ‘under’ (default) or ‘over’ the range maxs-mins. clip and hard_bound options can be mixed by specifying tuples (see description below).

Parameters:
  • dxyz (tuple(float,float,float)) – The spacing between points in x, y, and z directions
  • mins (tuple(float,float,float)) – The starting value for each dimension.
  • maxs (tuple(float,float,float)) – The ending value for each dimension.
  • mesh (str) – The type of mesh object to create, automatically set to ‘triplane’ if 2d or ‘tet’ if 3d.
  • clip (string or tuple(string,string,string)) – How to handle bounds if range does not divide by dxyz, either clip ‘under’ or ‘over’ range
  • hard_bound (string or tuple(string,string,string)) – Whether to use the “min” or “max” as the hard constraint on dimension
  • rz_switch (tuple(int, int, int)) – Determines true or false (1 or 0) for using ratio zoning values.
  • connect (boolean) – Whether or not to connect points
Example:
>>> from pylagrit import PyLaGriT
>>> l = PyLaGriT()
>>> 
>>> # Create 2x2x2 cell mesh
>>> m = l.create()
>>> m.createpts_dxyz((0.5,0.5,0.5),(0.,0.,0.),(1.,1.,1.),rz_switch=[1,1,1],connect=True)
>>> m.paraview()
>>> #m.gmv()
>>> 
>>> # Create 2x2x2 mesh where maxs will be truncated to nearest value under given maxs
>>> m_under = l.create()
>>> m_under.createpts_dxyz((0.4,0.4,0.4),(0.,0.,0.),(1.,1.,1.),rz_switch=[1,1,1],connect=True)
>>> m_under.paraview()
>>> #m_under.gmv()
>>> 
>>> # Create 3x3x3 mesh where maxs will be truncated to nearest value over given maxs
>>> m_over = l.create()
>>> m_over.createpts_dxyz((0.4,0.4,0.4),(0.,0.,0.),(1.,1.,1.),clip='over',rz_switch=[1,1,1],connect=True)
>>> m_over.paraview()
>>> #m_over.gmv()
>>> 
>>> # Create 3x3x3 mesh where x and y maxs will be truncated to nearest value over given maxs
>>> # and z min will be truncated  to nearest value
>>> m_mixed = l.create()
>>> m_mixed.createpts_dxyz((0.4,0.4,0.4),(0.,0.,-1.),(1.,1.,0.),hard_bound=('min','min','max'),clip=('under','under','over'),rz_switch=[1,1,1],connect=True)
>>> m_mixed.paraview()
>>> #m_mixed.gmv()
createpts_line(npts, mins, maxs, elem_type='line', vc_switch=(1, 1, 1), rz_switch=(1, 1, 1), name=None)

Create and Connect Points in a line

Parameters:
  • npts (int) – The number of points to create in line
  • mins (tuple(int, int, int)) – The starting value for each dimension.
  • maxs (tuple(int, int, int)) – The ending value for each dimension.
  • vc_switch (tuple(int, int, int)) – Determines if nodes represent vertices (1) or cell centers (0).
  • rz_switch (tuple(int, int, int)) – Determines true or false (1 or 0) for using ratio zoning values.
createpts_rtp(npts, mins, maxs, elem_type, vc_switch=(1, 1, 1), rz_switch=(1, 1, 1), rz_value=(1, 1, 1), connect=True)
createpts_rtz(npts, mins, maxs, elem_type, vc_switch=(1, 1, 1), rz_switch=(1, 1, 1), rz_value=(1, 1, 1), connect=True)
createpts_xyz(npts, mins, maxs, elem_type, vc_switch=(1, 1, 1), rz_switch=(1, 1, 1), rz_value=(1, 1, 1), connect=True, name=None)
define(**kwargs)

Pass in a variable number of arguments to be defined in LaGriT’s internal global scope.

Note that it is generally considered bad practice in PyLaGriT to rely on LaGriT’s variable system for parameters; however, there are use-cases where it is necessary: i.e., macro scripts.

Usage:

lg.define(MO_PTS=mo_pts.name,OUTFILE=’mesh.inp’,PERTURB32=1.3244)

>> define / MO_PTS / mo1 >> define / OUTFILE / mesh.inp >> define / PERTURB32 / 1.3244

dump(filename, mos=[], filetype='binary')

Dump lagrit binary file :arg filename: name of lagrit binary file to create :type filename: string :arg mos: List of mesh objects to include, default is all :type mos: list(MO) :arg filetype: Filetype to dump, ‘binary’ or ‘ascii’ :type mos: string

expect(expectstr='Enter a command', timeout=8640000.0)

This seeks through the stream until a pattern is matched. The pattern is overloaded and may take several types. The pattern can be a StringType, EOF, a compiled re, or a list of any of those types. Strings will be compiled to re types. This returns the index into the pattern list. If the pattern was not a list this returns index 0 on a successful match. This may raise exceptions for EOF or TIMEOUT. To avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern list. That will cause expect to match an EOF or TIMEOUT condition instead of raising an exception.

If you pass a list of patterns and more than one matches, the first match in the stream is chosen. If more than one pattern matches at that point, the leftmost in the pattern list is chosen. For example:

# the input is 'foobar'
index = p.expect(['bar', 'foo', 'foobar'])
# returns 1('foo') even though 'foobar' is a "better" match

Please note, however, that buffering can affect this behavior, since input arrives in unpredictable chunks. For example:

# the input is 'foobar'
index = p.expect(['foobar', 'foo'])
# returns 0('foobar') if all input is available at once,
# but returns 1('foo') if parts of the final 'bar' arrive late

When a match is found for the given pattern, the class instance attribute match becomes an re.MatchObject result. Should an EOF or TIMEOUT pattern match, then the match attribute will be an instance of that exception class. The pairing before and after class instance attributes are views of the data preceding and following the matching pattern. On general exception, class attribute before is all data received up to the exception, while match and after attributes are value None.

When the keyword argument timeout is -1 (default), then TIMEOUT will raise after the default value specified by the class timeout attribute. When None, TIMEOUT will not be raised and may block indefinitely until match.

When the keyword argument searchwindowsize is -1 (default), then the value specified by the class maxread attribute is used.

A list entry may be EOF or TIMEOUT instead of a string. This will catch these exceptions and return the index of the list entry instead of raising the exception. The attribute ‘after’ will be set to the exception type. The attribute ‘match’ will be None. This allows you to write code like this:

index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
    do_something()
elif index == 1:
    do_something_else()
elif index == 2:
    do_some_other_thing()
elif index == 3:
    do_something_completely_different()

instead of code like this:

try:
    index = p.expect(['good', 'bad'])
    if index == 0:
        do_something()
    elif index == 1:
        do_something_else()
except EOF:
    do_some_other_thing()
except TIMEOUT:
    do_something_completely_different()

These two forms are equivalent. It all depends on what you want. You can also just expect the EOF if you are waiting for all output of a child to finish. For example:

p = pexpect.spawn('/bin/ls')
p.expect(pexpect.EOF)
print p.before

If you are trying to optimize for speed then see expect_list().

On Python 3.4, or Python 3.3 with asyncio installed, passing async_=True will make this return an asyncio coroutine, which you can yield from to get the same result that this method would normally give directly. So, inside a coroutine, you can replace this code:

index = p.expect(patterns)

With this non-blocking form:

index = yield from p.expect(patterns, async_=True)
extract_surfmesh(name=None, cmo_in=None, stride=[1, 0, 0], reorder=True, resetpts_itp=True, external=False, append=None)
gridder(x=None, y=None, z=None, connect=False, elem_type='tet', name=None, filename='gridder.inp')

Generate a logically rectangular orthogonal mesh corresponding to vectors of nodal positions.

Parameters:
  • x (array(floats)) – x discretization locations
  • y (array(floats)) – y discretization locations
  • z (array(floats)) – z discretization locations
  • connect (bool) – Should the points be connected
  • elem_type (string) – Type of element for created mesh object
  • filename (string) – Name of avs file created with nodal coordinates
Returns:

MO

Example:
>>> from pylagrit import PyLaGriT
>>> import numpy
>>> lg = PyLaGriT()
>>> x0 = -numpy.logspace(1,2,15,endpoint=True)
>>> x1 = numpy.arange(-10,10,1)
>>> x2 = -x0
>>> x = numpy.concatenate([x0,x1,x2])
>>> y = x
>>> mqua = lg.gridder(x,y,elem_type='quad',connect=True)
>>> mqua.paraview()
interact(escape_character='^')

This gives control of the child process to the interactive user (the human at the keyboard). Keystrokes are sent to the child process, and the stdout and stderr output of the child process is printed. This simply echos the child stdout and child stderr to the real stdout and it echos the real stdin to the child stdin. When the user types the escape_character this method will return None. The escape_character will not be transmitted. The default for escape_character is entered as Ctrl - ], the very same as BSD telnet. To prevent escaping, escape_character may be set to None.

If a logfile is specified, then the data sent and received from the child process in interact mode is duplicated to the given log.

You may pass in optional input and output filter functions. These functions should take a string and return a string. The output_filter will be passed all the output from the child process. The input_filter will be passed all the keyboard input from the user. The input_filter is run BEFORE the check for the escape_character.

Note that if you change the window size of the parent the SIGWINCH signal will not be passed through to the child. If you want the child window size to change when the parent’s window size changes then do something like the following example:

import pexpect, struct, fcntl, termios, signal, sys
def sigwinch_passthrough (sig, data):
    s = struct.pack("HHHH", 0, 0, 0, 0)
    a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
        termios.TIOCGWINSZ , s))
    if not p.closed:
        p.setwinsize(a[0],a[1])

# Note this 'p' is global and used in sigwinch_passthrough.
p = pexpect.spawn('/bin/bash')
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
p.interact()
merge(mesh_objs, elem_type='tet', name=None)

Merge Mesh Objects

Merges two or more mesh objects together and returns the combined mesh object.

Parameters:mesh_objs (MO list) – An argument list of mesh objects.

Returns: MO.

Example:
>>> #To use pylagrit, import the module.
>>> import pylagrit
>>> import numpy
>>> #Instantiate the lagrit object.
>>> lg = pylagrit.PyLaGriT()
>>> # Create list with mesh object as first element
>>> dxyz = numpy.array([0.25]*3)
>>> mins = numpy.array([0.]*3)
>>> maxs = numpy.array([1.]*3)
>>> ms = [lg.createpts_dxyz(dxyz,mins,maxs,'tet',connect=True)]
>>> # Create three new mesh objects, each one directly above the other
>>> for i in range(3):
>>>     ms.append(ms[-1].copy())
>>>     ms[-1].trans(ms[-1].mins,ms[-1].mins+numpy.array([0.,0.,1.]))
>>> # Merge list of mesh objects and clean up
>>> mo_merge = lg.merge(ms)
>>> for mo in ms: mo.delete()
>>> mo_merge.rmpoint_compress(filter_bool=True,resetpts_itp=True)
>>> mo_merge.paraview(filename='mo_merge.inp')
points(coords, connect=False, elem_type='tet', filename='points.inp')

Generate a mesh object of points defined by x, y, z vectors.

Parameters:
  • coords – list of 3-tuples containing (x,y,z) coorinates
  • connect (bool) – Should the points be connected
  • elem_type (string) – Type of element for created mesh object
  • filename (string) – Name of avs file created with nodal coordinates
Returns:

MO

Example:
>>> from pylagrit import PyLaGriT
>>> lg = PyLaGriT()
>>> coords = [[0,0,0],[1,0,0],[1,1,0],[0,1,1],[0,0,1],[0,1,0],[1,1,1],[1,0,1]]
>>> m = lg.points(coords,elem_type='tet',connect=True)
>>> m.paraview()
read(filename, filetype=None, name=None, binary=False)

Read in mesh

Parameters:
  • filename (str) – Name of mesh file to read in
  • filetype (str) – Type of file, automatically detected if not specified
  • name (str) – Internal Lagrit name of new mesh object, automatically created if None
  • binary (bool) – Indicates that file is binary if True, ascii if False
Returns:

MO

Example 1:
>>> #To use pylagrit, import the module.
>>> import pylagrit
>>> #Create your pylagrit session.
>>> lg = pylagrit.PyLaGriT()
>>> #Create a mesh object and dump it to a gmv file 'test.gmv'.
>>> mo = lg.create(name='test')
>>> mo.createpts_brick_xyz((5,5,5), (0,0,0), (5,5,5,))
>>> mo.dump('test.gmv')
>>> mo.dump('test.avs')
>>> mo.dump('test.lg')
>>> mo1 = lg.read('test.gmv')
>>> mo2 = lg.read('test.avs')
>>> mo3 = lg.read('test.lg',name='test')
Example 2 - Reading in LaGriT binary file, autodetect mesh object name
>>> #To use pylagrit, import the module.
>>> import pylagrit
>>> import numpy
>>> #Instantiate the lagrit object.
>>> lg = pylagrit.PyLaGriT()
>>> # Create list with mesh object as first element
>>> dxyz = numpy.array([0.25]*3)
>>> mins = numpy.array([0.]*3)
>>> maxs = numpy.array([1.]*3)
>>> ms = [lg.createpts_dxyz(dxyz,mins,maxs,'tet',connect=True,name='testmo')]
>>> # Create three new mesh objects, each one directly above the other
>>> for i in range(3):
>>>     ms.append(ms[-1].copy())
>>>     ms[-1].trans(ms[-1].mins,ms[-1].mins+numpy.array([0.,0.,1.]))
>>> lg.dump('lagrit_binary.lg')
>>> lg.close()
>>> lg = pylagrit.PyLaGriT()
>>> ms_read = lg.read('lagrit_binary.lg')
>>> print 'Name of mesh object read in should be testmo, is: ', ms_read.name
read_att(fname, attributes, mesh=None, operation='add')

Reads data from a file into an attribute.

read_fehm(filename, avs_filename='temp.inp', elem_type=None)
read_modflow(materials_file, nrows, ncols, name=None, DXY=[100, 100], height=7.75, filename=None)

Reads in a Modflow elevation file (and, optionally, an HDF5/txt file containing node materials) and generates and returns hexagonal mesh.

Parameters:
  • filename (str) – Filename of Modflow elevation data file
  • nrows (int) – Number of rows in elevation file
  • ncols (int) – Number of columns in elevation file
  • name (str) – Name of returned mesh (optional)
  • DXY (list (number)) – Spacing in x/y directions
  • height (float) – The ‘thickness’ in the Z-direction of the returned hex mesh
  • materials_file (str) – A text or HDF5 binary file containing materials properties for an elevation mesh
  • materials_keys (list (str)) – A list containing the keys to the materials array, ordered sequentially. If set, it is assumed materials_file is an HDF5 file.
Returns:

MO

read_script(fname)

Read a LaGriT Script

Given a script name, executes the script in LaGriT.

Parameters:fname (str) – The name or path to the lagrit script.
read_sheetij(name, filename, NXY, minXY, DXY, connect=True, file_type='ascii', flip='none', skip_lines=0, data_type='float')

Creates a quad mesh from an elevation file. Note the input file is read as Z(i,j) into the cmo attribute ‘zic’

Parameters:
  • name (string) – name of mesh object
  • filename (string) – Elevation filename
  • NXY (list) – [nx, ny] - [columns in x-direction, rows in y-direction]
  • minXY (list) – [minX, minY] - location of lower left corner
  • DXY (list) – [Dx, Dy] - cell size in x and y directions
  • connect (bool) – True will create a quad grid, otherwise keeps data as points
  • file_type (string) – May be either ascii or binary
  • flip (string) – May be ‘x’, ‘y’ to reflect across those axes, or ‘none’ to keep static
  • skip_lines (integer) – skip n number of header lines
  • data_type (string) – read in elevation data as either float or double
Returns:

MO

Example 1 - Building a surface mesh from Modflow elevation file:
>>> #To use pylagrit, import the module.
>>> from pylagrit import PyLaGriT
>>> import numpy as np
>>> 
>>> # Instantiate PyLaGriT
>>> l = PyLaGriT()
>>> 
>>> # Elevation files are typically headerless unwrapped vectors
>>> # Define parameters to pack these elements into a matrix
>>> ncols = 276
>>> nrows = 313
>>> DXY = [100,100]
>>> 
>>> elev_surface = l.read_sheetij('surfacemesh', 'example.mod', [ncols, nrows], [0, 0], DXY, flip='y')
>>> elev_surface.paraview()
run_batch()
sendline(cmd, verbose=True, expectstr='Enter a command')

Wraps send(), sending string s to child process, with os.linesep automatically appended. Returns number of bytes written. Only a limited number of bytes may be sent for each line in the default terminal mode, see docstring of send().

tri_mo_from_polyline(coords, order='clockwise', filename='polyline.inp', name=None)

Create polygon tri mesh object from points Points are expected to be defined clockwise by default

Parameters:
  • coords (lst(floats) or ndarray(floats)) – x,y,z coordinates defined in npoints by 3 array, points expected to be ordered clockwise by default
  • order (string) – ordering of points, clockwise by default
  • filename (string) – Name of avs polyline file to create
  • name (string) – Internal lagrit name for mesh object
Returns:

PyLaGriT Mesh Object

Example:
>>> from pylagrit import PyLaGriT
>>> lg = PyLaGriT()
>>> mo = lg.tri_mo_from_polyline([[0.,0.],[0.,1.],[1.,1.],[1.,0.]])