devito package

Submodules

devito.arguments module

class devito.arguments.Argument(name, provider, default_value=None)[source]

Bases: object

Abstract base class for any object that represents a run time argument for generated kernels.

as_symbol
dtype
is_PtrArgument = False
is_ScalarArgument = False
is_TensorArgument = False
ready
reset()[source]
value
verify
class devito.arguments.ArgumentProvider(*args, **kwargs)[source]

Bases: object

Abstract base class for any object that, post code-generation, might resolve resolve to runtime arguments. We assume that one source object (e.g. Dimension, SymbolicData) might provide multiple runtime arguments.

rtargs

Return a list of RuntimeArgument objects that this object needs.

class devito.arguments.ConstantDataArgProvider(*args, **kwargs)[source]

Bases: devito.arguments.ArgumentProvider

Class used to decorate Constat Data objects with behaviour required for runtime arguments.

rtargs
class devito.arguments.DimensionArgProvider(*args, **kwargs)[source]

Bases: devito.arguments.ArgumentProvider

This class is used to decorate the Dimension class with behaviour required to handle runtime arguments. All properties/methods defined here are available in any Dimension object.

decl
dtype

The data type of the iteration variable

reducer()

max(iterable[, key=func]) -> value max(a, b, c, …[, key=func]) -> value

With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.

reset()[source]
rtargs
value
verify(value)[source]
class devito.arguments.ObjectArgProvider(*args, **kwargs)[source]

Bases: devito.arguments.ArgumentProvider

Class used to decorate Objects with behaviour required for runtime arguments.

rtargs
class devito.arguments.PtrArgument(name, provider)[source]

Bases: devito.arguments.Argument

Class representing arbitrary arguments that a kernel might expect. These are passed as void pointers and then promptly casted to their actual type.

is_PtrArgument = True
verify(value)[source]
class devito.arguments.ScalarArgument(name, provider, reducer, default_value=None)[source]

Bases: devito.arguments.Argument

Class representing scalar arguments that a kernel might expect. Most commonly used to pass dimension sizes

is_ScalarArgument = True
verify(value)[source]
class devito.arguments.ScalarFunctionArgProvider(*args, **kwargs)[source]

Bases: devito.arguments.ArgumentProvider

Class used to decorate Scalar Function objects with behaviour required for runtime arguments.

rtargs
class devito.arguments.TensorArgument(name, provider)[source]

Bases: devito.arguments.Argument

Class representing tensor arguments that a kernel might expect. Most commonly used to pass numpy-like multi-dimensional arrays.

is_TensorArgument = True
verify(value)[source]
class devito.arguments.TensorDataArgProvider(*args, **kwargs)[source]

Bases: devito.arguments.ArgumentProvider

Class used to decorate Symbolic Data objects with behaviour required for runtime arguments.

rtargs
class devito.arguments.TensorFunctionArgProvider(*args, **kwargs)[source]

Bases: devito.arguments.ArgumentProvider

Class used to decorate Tensor Function objects with behaviour required for runtime arguments.

rtargs
devito.arguments.log_args(arguments)[source]

devito.backends module

The Devito backend configuration engine.

Warning

The backend should always be set via devito.init()

devito.backends.get_backend()[source]

Get the Devito backend.

devito.backends.init_backend(backend)[source]

Initialise Devito: select the backend and other configuration options.

devito.backends.initialised_backend()[source]

Check whether Devito has been yet initialised.

devito.backends.set_backend(backend)[source]

Set the Devito backend.

class devito.backends.void[source]

Bases: object

Dummy backend.

devito.base module

Metaclasses used to construct classes of proper backend type at runtime.

class devito.base.ConstantData(*args, **kwargs)[source]

Bases: devito.interfaces.ConstantData

Data object for constant values.

default_assumptions = {}
class devito.base.DenseData(*args, **kwargs)[source]

Bases: devito.interfaces.DenseData

Data object for spatially varying data acting as a SymbolicData.

Parameters:
  • name – Name of the symbol
  • dtype – Data type of the scalar
  • shape – The shape of the tensor
  • dimensions – The symbolic dimensions of the tensor.
  • space_order – Discretisation order for space derivatives
  • initializer – Function to initialize the data, optional

Note

DenseData objects are assumed to be constant in time and therefore do not support time derivatives. Use TimeData for time-varying grid data.

default_assumptions = {}
class devito.base.Operator(expressions, **kwargs)[source]

Bases: devito.operator.Operator

Represent a C function.

Parameters:
  • name – The name of the function.
  • body – A Node or an iterable of Node objects representing the body of the function.
  • retval – The type of the value returned by the function.
  • parameters – An iterable of SymbolicData objects in input to the function, or None if the function takes no parameter.
  • prefix – An iterable of qualifiers to prepend to the function declaration. The default value is (‘static’, ‘inline’).
default_assumptions = {}
is_algebraic
is_antihermitian
is_commutative
is_complex
is_composite
is_even
is_finite
is_hermitian
is_imaginary
is_infinite
is_integer
is_irrational
is_negative
is_noninteger
is_nonnegative
is_nonpositive
is_nonzero
is_odd
is_polar
is_positive
is_prime
is_rational
is_real
is_transcendental
is_zero
class devito.base.PointData(*args, **kwargs)[source]

Bases: devito.pointdata.PointData

Data object for sparse point data that acts as a Function symbol

Parameters:
  • name – Name of the resulting sympy.Function symbol
  • npoint – Number of points to sample
  • nt – Size of the time dimension for point data
  • ndim – Dimension of the coordinate data, eg. 2D or 3D
  • coordinates – Optional coordinate data for the sparse points
  • dtype – Data type of the buffered data
default_assumptions = {}
class devito.base.ScalarFunction(*args, **kwargs)[source]

Bases: devito.interfaces.ScalarFunction

Symbolic object representing a scalar.

Parameters:
  • name – Name of the symbol
  • dtype – Data type of the scalar
default_assumptions = {}
class devito.base.TensorFunction(*args, **kwargs)[source]

Bases: devito.interfaces.TensorFunction

Symbolic object representing a tensor.

Parameters:
  • name – Name of the symbol
  • dtype – Data type of the scalar
  • shape – The shape of the tensor
  • dimensions – The symbolic dimensions of the tensor.
  • onstack – Pass True to enforce allocation on stack
default_assumptions = {}
class devito.base.TimeData(*args, **kwargs)[source]

Bases: devito.interfaces.TimeData

Data object for time-varying data that acts as a Function symbol

Parameters:
  • name – Name of the resulting sympy.Function symbol
  • shape – Shape of the spatial data grid
  • dimensions – The symbolic dimensions of the function in addition to time.
  • dtype – Data type of the buffered data
  • save – Save the intermediate results to the data buffer. Defaults to False, indicating the use of alternating buffers.
  • time_dim – Size of the time dimension that dictates the leading dimension of the data buffer if :param save: is True.
  • time_order – Order of the time discretization which affects the final size of the leading time dimension of the data buffer.

Note

The parameter shape should only define the spatial shape of the grid. The temporal dimension will be inserted automatically as the leading dimension, according to the time_dim, time_order and whether we want to write intermediate timesteps in the buffer. The same is true for explicitly provided dimensions, which will be added to the automatically derived time dimensions symbol. For example:

In []: TimeData(name="a", dimensions=(x, y, z))
Out[]: a(t, x, y, z)

In []: TimeData(name="a", shape=(20, 30))
Out[]: a(t, x, y)
default_assumptions = {}

devito.cgen_utils module

class devito.cgen_utils.Allocator[source]

Bases: object

Generate C strings to declare pointers, allocate and free memory.

onheap
onstack
push_heap(obj)[source]

Generate cgen objects to declare, allocate memory, and free memory for obj, of type SymbolicData.

push_stack(scope, obj)[source]

Generate a cgen statement that allocates obj on the stack.

class devito.cgen_utils.CodePrinter(settings={})[source]

Bases: sympy.printing.ccode.CCodePrinter

custom_functions = {'INT': '(int)', 'FLOAT': '(float)'}

Decorator for sympy.printing.ccode.CCodePrinter.

Parameters:settings – A dictionary containing relevant settings
class devito.cgen_utils.FLOAT

Bases: sympy.core.function.AppliedUndef

default_assumptions = {}
class devito.cgen_utils.INT

Bases: sympy.core.function.AppliedUndef

default_assumptions = {}
devito.cgen_utils.ccode(expr, **settings)[source]

Generate C++ code from an expression calling CodePrinter class

Parameters:
  • expr – The expression
  • settings – A dictionary of settings for code printing
Returns:

The resulting code as a string. If it fails, then it returns the expr

devito.cgen_utils.ccode_eq(eq, **settings)[source]

Generate C++ assignment from an equation assigning RHS to LHS

Parameters:
  • eq – The equation
  • settings – A dictionary of settings for code printing
Returns:

The resulting code as a string

devito.cgen_utils.printmark(i)
devito.cgen_utils.printvar(i)

devito.compiler module

devito.compiler.jit_compile(ccode, compiler)[source]

JIT compile the given ccode.

Parameters:
  • ccode – String of C source code.
  • compiler – The toolchain used for compilation.
Returns:

The name of the compilation unit.

devito.compiler.load(basename, compiler)[source]

Load a compiled library

Parameters:
  • basename – Name of the .so file.
  • compiler – The toolchain used for compilation.
Returns:

The loaded library.

Note: If the provided compiler is of type IntelMICCompiler we utilise the pymic package to manage device streams.

devito.compiler.make(loc, args)[source]

Invoke make command from within loc with arguments args.

class devito.compiler.GNUCompiler(*args, **kwargs)[source]

Bases: devito.compiler.Compiler

Set of standard compiler flags for the GCC toolchain.

devito.dimension module

class devito.dimension.Dimension(*args, **kwargs)[source]

Bases: sympy.core.symbol.Symbol, devito.arguments.DimensionArgProvider

Index object that represents a problem dimension and thus defines a potential iteration space.

Parameters:
  • size – Optional, size of the array dimension.
  • reverse – Traverse dimension in reverse order (default False)
  • buffered – Optional, boolean flag indicating whether to buffer variables when iterating this dimension.
default_assumptions = {}
is_Buffered = False
is_Lowered = False
symbolic_size

The symbolic size of this dimension.

devito.exceptions module

exception devito.exceptions.CompilationError[source]

Bases: devito.exceptions.DevitoError

exception devito.exceptions.DLEException[source]

Bases: devito.exceptions.DevitoError

exception devito.exceptions.DSEException[source]

Bases: devito.exceptions.DevitoError

exception devito.exceptions.DevitoError[source]

Bases: exceptions.Exception

exception devito.exceptions.InvalidArgument[source]

Bases: devito.exceptions.DevitoError

exception devito.exceptions.InvalidOperator[source]

Bases: devito.exceptions.DevitoError

exception devito.exceptions.StencilOperationError[source]

Bases: devito.exceptions.DevitoError

exception devito.exceptions.VisitorException[source]

Bases: devito.exceptions.DevitoError

devito.finite_difference module

devito.finite_difference.first_derivative(*args, **kwargs)[source]

Derives first derivative for a product of given functions.

Parameters:
  • *args – All positional arguments must be fully qualified function objects, eg. f(x, y) or g(t, x, y, z).
  • dims – symbol defining the dimension wrt. which to differentiate, eg. x, y, z or t.
  • diff – Finite Difference symbol to insert, default h.
  • side – Side of the shift for the first derivatives.
Returns:

The first derivative

Example: Deriving the first-derivative of f(x)*g(x) wrt. x via:
cross_derivative(f(x), g(x), dim=x, side=1, order=1) results in: *(-f(x)*g(x) + f(x + h)*g(x + h) ) / h
devito.finite_difference.second_derivative(*args, **kwargs)[source]

Derives second derivative for a product of given functions.

Parameters:
  • *args – All positional arguments must be fully qualified function objects, eg. f(x, y) or g(t, x, y, z).
  • dim – Symbol defininf the dimension wrt. which to differentiate, eg. x, y, z or t.
  • diff – Finite Difference symbol to insert, default h.
  • order – Discretisation order of the stencil to create.
Returns:

The second derivative

Example: Deriving the second derivative of f(x, y)*g(x, y) wrt. x via
second_derivative(f(x, y), g(x, y), order=2, dim=x) results in (-2.0*f(x, y)*g(x, y) + 1.0*f(-h + x, y)*g(-h + x, y) + 1.0*f(h + x, y)*g(h + x, y)) / h**2.
devito.finite_difference.cross_derivative(*args, **kwargs)[source]

Derives cross derivative for a product of given functions.

Parameters:
  • *args – All positional arguments must be fully qualified function objects, eg. f(x, y) or g(t, x, y, z).
  • dims – 2-tuple of symbols defining the dimension wrt. which to differentiate, eg. x, y, z or t.
  • diff – Finite Difference symbol to insert, default h.
Returns:

The cross derivative

Example: Deriving the cross-derivative of f(x, y)*g(x, y) wrt. x and y via:
cross_derivative(f(x, y), g(x, y), dims=(x, y)) results in: 0.5*(-2.0*f(x, y)*g(x, y) + f(x, -h + y)*g(x, -h + y) + f(x, h + y)*g(x, h + y) + f(-h + x, y)*g(-h + x, y) - f(-h + x, h + y)*g(-h + x, h + y) + f(h + x, y)*g(h + x, y) - f(h + x, -h + y)*g(h + x, -h + y)) / h**2

devito.interfaces module

class devito.interfaces.Symbol[source]

Bases: sympy.core.symbol.Symbol

A sympy.Symbol capable of mimicking an sympy.Indexed

default_assumptions = {}
func(*args)[source]
class devito.interfaces.Indexed[source]

Bases: sympy.tensor.indexed.Indexed

default_assumptions = {'commutative': True}
is_commutative = True
class devito.interfaces.ConstantData(*args, **kwargs)[source]

Bases: devito.interfaces.SymbolicData, devito.arguments.ConstantDataArgProvider

Data object for constant values.

data

The value of the data object, as a scalar (int, float, …).

default_assumptions = {}
is_ConstantData = True
is_Scalar = True
class devito.interfaces.DenseData(*args, **kwargs)[source]

Bases: devito.interfaces.TensorData

Data object for spatially varying data acting as a SymbolicData.

Parameters:
  • name – Name of the symbol
  • dtype – Data type of the scalar
  • shape – The shape of the tensor
  • dimensions – The symbolic dimensions of the tensor.
  • space_order – Discretisation order for space derivatives
  • initializer – Function to initialize the data, optional

Note

DenseData objects are assumed to be constant in time and therefore do not support time derivatives. Use TimeData for time-varying grid data.

data

The value of the data object, as a numpy.ndarray storing elements in the classical row-major storage layout.

default_assumptions = {}
dx

Symbol for the first derivative wrt the x dimension

dx2

Symbol for the second derivative wrt the x dimension

dx2y2

Symbol for the second cross derivative wrt the x,y dimension

dx2z2

Symbol for the second cross derivative wrt the x,z dimension

dx4

Symbol for the fourth derivative wrt the x dimension

dxl

Symbol for the derivative wrt to x with a left stencil

dxr

Symbol for the derivative wrt to x with a right stencil

dxy

Symbol for the cross derivative wrt the x and y dimension

dxz

Symbol for the cross derivative wrt the x and z dimension

dy

Symbol for the first derivative wrt the y dimension

dy2

Symbol for the second derivative wrt the y dimension

dy2z2

Symbol for the second cross derivative wrt the y,z dimension

dy4

Symbol for the fourth derivative wrt the y dimension

dyl

Symbol for the derivative wrt to y with a left stencil

dyr

Symbol for the derivative wrt to y with a right stencil

dyz

Symbol for the cross derivative wrt the y and z dimension

dz

Symbol for the first derivative wrt the z dimension

dz2

Symbol for the second derivative wrt the z dimension

dz4

Symbol for the fourth derivative wrt the z dimension

dzl

Symbol for the derivative wrt to z with a left stencil

dzr

Symbol for the derivative wrt to z with a right stencil

initialize()[source]

Apply the data initilisation function, if it is not None.

is_DenseData = True
laplace

Symbol for the second derivative wrt all spatial dimensions

laplace2(weight=1)[source]

Symbol for the double laplacian wrt all spatial dimensions

class devito.interfaces.TimeData(*args, **kwargs)[source]

Bases: devito.interfaces.DenseData

Data object for time-varying data that acts as a Function symbol

Parameters:
  • name – Name of the resulting sympy.Function symbol
  • shape – Shape of the spatial data grid
  • dimensions – The symbolic dimensions of the function in addition to time.
  • dtype – Data type of the buffered data
  • save – Save the intermediate results to the data buffer. Defaults to False, indicating the use of alternating buffers.
  • time_dim – Size of the time dimension that dictates the leading dimension of the data buffer if :param save: is True.
  • time_order – Order of the time discretization which affects the final size of the leading time dimension of the data buffer.

Note

The parameter shape should only define the spatial shape of the grid. The temporal dimension will be inserted automatically as the leading dimension, according to the time_dim, time_order and whether we want to write intermediate timesteps in the buffer. The same is true for explicitly provided dimensions, which will be added to the automatically derived time dimensions symbol. For example:

In []: TimeData(name="a", dimensions=(x, y, z))
Out[]: a(t, x, y, z)

In []: TimeData(name="a", shape=(20, 30))
Out[]: a(t, x, y)
backward

Symbol for the time-backward state of the function

default_assumptions = {}
dim

Returns the spatial dimension of the data object

dt

Symbol for the first derivative wrt the time dimension

dt2

Symbol for the second derivative wrt the t dimension

forward

Symbol for the time-forward state of the function

initialize()[source]
is_TimeData = True

devito.logger module

The Devito logger.

devito.logger.set_log_level(level)[source]

Set the log level of the Devito logger.

Parameters:level – accepted values are: DEBUG, INFO, AUTOTUNER, DSE, DSE_WARN, DLE, DLE_WARN, WARNING, ERROR, CRITICAL
devito.logger.set_log_noperf()[source]

Do not print performance-related messages.

devito.logger.log(msg, level=20, *args, **kwargs)[source]

Wrapper of the main Python’s logging function. Print ‘msg % args’ with the severity ‘level’.

Parameters:
  • msg – the message to be printed.
  • level – accepted values are: DEBUG, INFO, AUTOTUNER, DSE, DSE_WARN, DLE, DLE_WARN, WARNING, ERROR, CRITICAL
devito.logger.log(msg, level=20, *args, **kwargs)[source]

Wrapper of the main Python’s logging function. Print ‘msg % args’ with the severity ‘level’.

Parameters:
  • msg – the message to be printed.
  • level – accepted values are: DEBUG, INFO, AUTOTUNER, DSE, DSE_WARN, DLE, DLE_WARN, WARNING, ERROR, CRITICAL
devito.logger.warning(msg, *args, **kwargs)[source]
devito.logger.error(msg, *args, **kwargs)[source]
devito.logger.info_at(msg, *args, **kwargs)[source]
devito.logger.dse(msg, *args, **kwargs)[source]
devito.logger.dse_warning(msg, *args, **kwargs)[source]
devito.logger.dle(msg, *args, **kwargs)[source]
devito.logger.dle_warning(msg, *args, **kwargs)[source]

devito.memory module

class devito.memory.CMemory(shape, dtype=<type 'numpy.float32'>, alignment=None)[source]

Bases: object

fill(val)[source]
devito.memory.first_touch(array)[source]

Uses the Propagator low-level API to initialize the given array(in Devito types) in the same pattern that would later be used to access it.

devito.memory.free(internal_pointer)[source]

Use the C function free to free the memory allocated for the given pointer.

devito.memory.malloc_aligned(shape, alignment=None, dtype=<type 'numpy.float32'>)[source]

Allocate memory using the C function malloc_aligned :param shape: Shape of the array to allocate :param alignment: number of bytes to align to. Defaults to page size if not set. :param dtype: Numpy datatype to allocate. Default to np.float32

:returns (pointer, data_pointer) the first element of the tuple is the reference that can be used to access the data as a ctypes object. The second element is the low-level reference that is needed only for the call to free.

devito.nodes module

The Iteration/Expression hierarchy.

class devito.nodes.Node[source]

Bases: object

args

Arguments used to construct the Node.

args_frozen

Arguments used to construct the Node that cannot be traversed.

ccode

Generate C code.

This is a shorthand for

children

Return the traversable children.

is_Block = False
is_Element = False

_traversable. A list of traversable objects (ie, traversed by Visitor objects). A traversable object is intended as an argument of a Node constructor and is represented as a string.

is_Expression = False
is_FunCall = False
is_Function = False
is_Iteration = False
is_IterationFold = False
is_List = False
is_Node = True
view

Generate a representation of the Iteration/Expression tree rooted in self.

class devito.nodes.Block(header=None, body=None, footer=None)[source]

Bases: devito.nodes.Node

children
is_Block = True
class devito.nodes.Denormals(header=None, body=None, footer=None)[source]

Bases: devito.nodes.List

Macros to make sure denormal numbers are flushed in hardware.

class devito.nodes.Expression(expr, dtype=None)[source]

Bases: devito.nodes.Node

Class encpasulating a single SymPy equation.

is_Expression = True
is_scalar

Return True if a scalar expression, False otherwise.

is_tensor

Return True if a tensor expression, False otherwise.

output

Return the symbol written by this Expression.

output_function

Return the function written by this Expression.

shape

Return the shape of the written LHS.

stencil

Compute the stencil of the expression.

substitute(substitutions)[source]

Apply substitutions to the expression.

Parameters:substitutions – Dict containing the substitutions to apply to the stored expression.
class devito.nodes.Function(name, body, retval, parameters=None, prefix=('static', 'inline'))[source]

Bases: devito.nodes.Node

Represent a C function.

Parameters:
  • name – The name of the function.
  • body – A Node or an iterable of Node objects representing the body of the function.
  • retval – The type of the value returned by the function.
  • parameters – An iterable of SymbolicData objects in input to the function, or None if the function takes no parameter.
  • prefix – An iterable of qualifiers to prepend to the function declaration. The default value is (‘static’, ‘inline’).
children
is_Function = True
class devito.nodes.FunCall(name, params=None)[source]

Bases: devito.nodes.Node

A node representing a function call.

is_FunCall = True
class devito.nodes.Iteration(nodes, dimension, limits, index=None, offsets=None, properties=None, pragmas=None, uindices=None)[source]

Bases: devito.nodes.Node

Iteration object that encapsualtes a single loop over nodes.

Parameters:
  • nodes – Single or list of Node objects defining the loop body.
  • dimensionDimension object over which to iterate.
  • limits – Limits for the iteration space, either the loop size or a tuple of the form (start, finish, stepping).
  • index – Symbol to be used as iteration variable.
  • offsets – Optional map list of offsets to honour in the loop.
  • properties – A bag of strings indicating properties of this Iteration. For example, the string ‘parallel’ may be used to identify a parallelizable Iteration.
  • pragmas – A bag of pragmas attached to this Iteration.
  • uindices – a bag of UnboundedIndex objects, representing free iteration variables (i.e., the Iteration end point is independent of any of these UnboundedIndex).
bounds(start=None, finish=None)[source]

Return the start and end points of the Iteration if the limits are available (either statically known or provided through start/ finish). None is used as a placeholder in the returned 2-tuple if a limit is unknown.

bounds_symbolic

Return a 2-tuple representing the symbolic bounds of the object.

children

Return the traversable children.

end(finish=None)[source]

Return the end point of the Iteration if the upper limit is known, None otherwise.

end_symbolic

Return the symbolic extent of the Iteration.

extent(start=None, finish=None)[source]

Return the number of iterations executed if the limits are known, None otherwise.

extent_symbolic

Return the symbolic extent of the Iteration.

is_Closed
is_Elementizable
is_Iteration = True
is_Linear
is_Open
is_Parallel
is_Remainder
is_Sequential
is_Vectorizable
retag(tag_value=None)[source]

Create a new Iteration object which is identical to self, except for the tag. If provided, tag_value is used as new tag; otherwise, an internally generated tag is used.

start(start=None)[source]

Return the start point of the Iteration if the lower limit is known, None otherwise.

start_symbolic

Return the symbolic extent of the Iteration.

tag
class devito.nodes.List(header=None, body=None, footer=None)[source]

Bases: devito.nodes.Block

Class representing a sequence of one or more statements.

is_List = True
class devito.nodes.LocalExpression(expr, dtype)[source]

Bases: devito.nodes.Expression

Class encpasulating a single expression with known data type (represented as a NumPy data type).

class devito.nodes.TimedList(lname, gname, body)[source]

Bases: devito.nodes.List

Wrap a Node with C-level timers.

name

devito.operator module

class devito.operator.FunMeta(root, local)

Bases: tuple

Metadata for functions called by an Operator. local = True means that the function was generated by Devito itself.

local

Alias for field number 1

root

Alias for field number 0

class devito.operator.Operator(expressions, **kwargs)[source]

Bases: devito.nodes.Function

arguments(**kwargs)[source]

Process any apply-time arguments passed to apply and derive values for any remaining arguments

cfunction

Returns the JIT-compiled C function as a ctypes.FuncPtr object.

compile

JIT-compile the C code generated by the Operator.

It is ensured that JIT compilation will only be performed once per Operator, reagardless of how many times this method is invoked.

Returns:The file name of the JIT-compiled function.
elemental_functions
class devito.operator.OperatorRunnable(expressions, **kwargs)[source]

Bases: devito.operator.Operator

A special Operator that, besides generation and compilation of C code evaluating stencil expressions, can also execute the computation.

apply(**kwargs)[source]

Apply the stencil kernel to a set of data objects

devito.operator.set_dle_mode(mode)[source]

Transform Operator input in a format understandable by the DLE.

devito.operator.set_dse_mode(mode)[source]

Transform Operator input in a format understandable by the DLE.

devito.parameters module

The parameters dictionary contains global parameter settings.

devito.parameters.configuration = Parameters([('log_level', 'DEBUG'), ('backend', 'core'), ('first_touch', False), ('dse', 'advanced'), ('compiler', DevitoJITCompiler[GNUCompiler]), ('openmp', False), ('debug_compiler', False), ('dle', 'advanced'), ('dle_options', {'blockalways': False, 'blockshape': None, 'blockinner': False}), ('travis_test', True), ('autotuning', 'basic')])

The Devito configuration parameters.

devito.parameters.init_configuration()[source]

devito.pointdata module

class devito.pointdata.PointData(*args, **kwargs)[source]

Bases: devito.interfaces.CompositeData

Data object for sparse point data that acts as a Function symbol

Parameters:
  • name – Name of the resulting sympy.Function symbol
  • npoint – Number of points to sample
  • nt – Size of the time dimension for point data
  • ndim – Dimension of the coordinate data, eg. 2D or 3D
  • coordinates – Optional coordinate data for the sparse points
  • dtype – Data type of the buffered data
coefficients

Symbolic expression for the coefficients for sparse point interpolation according to: https://en.wikipedia.org/wiki/Bilinear_interpolation.

Returns:List of coefficients, eg. [b_11, b_12, b_21, b_22]
coordinate_bases

Symbol for the base coordinates of the reference grid point

coordinate_indices

Symbol for each grid index according to the coordinates

coordinate_symbols

Symbol representing the coordinate values in each dimension

default_assumptions = {}
inject(field, expr, offset=0, **kwargs)[source]

Symbol for injection of an expression onto a grid

Parameters:
  • field – The grid field into which we inject.
  • expr – The expression to inject.
  • offset – Additional offset from the boundary for absorbing boundary conditions.
  • u_t – (Optional) time index to use for indexing into field.
  • p_t – (Optional) time index to use for indexing into expr.
interpolate(expr, offset=0, **kwargs)[source]

Creates a sympy.Eq equation for the interpolation of an expression onto this sparse point collection.

Parameters:
  • expr – The expression to interpolate.
  • offset – Additional offset from the boundary for absorbing boundary conditions.
  • u_t – (Optional) time index to use for indexing into field data in expr.
  • p_t – (Optional) time index to use for indexing into the sparse point data.
is_PointData = True
point_increments

Index increments in each dimension for each point symbol

point_symbols

Symbol for coordinate value in each dimension of the point

devito.profiling module

class devito.profiling.Profile(name, ops, memory)

Bases: tuple

Metadata for a profiled code section.

memory

Alias for field number 2

name

Alias for field number 0

ops

Alias for field number 1

devito.profiling.create_profile(node)[source]

Create a Profiler for the Iteration/Expression tree node. The following code sections are profiled:

* The whole ``node``;
* A sequence of perfectly nested loops that have common :class:`Iteration`
  dimensions, but possibly different extent. For example: ::

    for x = 0 to N
      ..
    for x = 1 to N-1
      ..

  Both Iterations have dimension ``x``, and will be profiled as a single
  section, though their extent is different.
* Any perfectly nested loops.

devito.stencil module

class devito.stencil.Stencil(*args)[source]

Bases: devito.tools.DefaultOrderedDict

A Stencil is a mapping from Dimension symbols to the set of integer offsets used with it in expressions (the “neighboring points accessed”).

This also include zero offsets.

The mapping is ordered based on the order in which dimensions are encountered (if extracted from expressions) or inserted.

Note: Expressions must have been indexified for a Stencil to be computed.

add(o)[source]

Compute the set union of each Dimension in self with the corresponding Dimension in o.

anti(o)[source]

Compute the anti-Stencil of self constrained by o.

Examples:

Assuming one single dimension (omitted for brevity)

self = {-3, -2, -1, 0, 1, 2, 3} o = {-3, -2, -1, 0, 1, 2, 3} self.anti(o) >> {}

self = {-3, -2, -1, 0, 1, 2, 3} o = {-2, -1, 0, 1} self.anti(o) >> {-1, 0, 1, 2}

self = {-1, 0, 1} o = {-2, -1, 0, 1, 2} self.anti(o) >> {-1, 0, 1}

dimensions
empty
entries
classmethod extract(expr)[source]

Compute the stencil of expr.

frozen
get(k, v=None)[source]
null()[source]

Return the null Stencil of self.

Examples:

self = {i: {-1, 0, 1}, j: {-2, -1, 0, 1, 2}} self.null() >> {i: {0}, j: {0}}

rshift(m)[source]

Right-shift the Dimensions d of self appearing in the mapper m by the constant quantity m[d].

section(d)[source]

Return a view of the Stencil in which the Dimensions in d have been dropped.

split(ds=None)[source]

Split self into two Stencils, one with the negative axis, and one with the positive axis. If ds is provided, the split occurs only along the Dimensions listed in ds.

subtract(o)[source]

Compute the set difference of each Dimension in self with the corresponding Dimension in o.

classmethod union(*dicts)[source]

Compute the union of an iterable of Stencil objects.

class devito.stencil.StencilEntry(dim, ofs)

Bases: tuple

dim

Alias for field number 0

ofs

Alias for field number 1

devito.tools module

class devito.tools.DefaultOrderedDict(default_factory=None, *a, **kw)[source]

Bases: collections.OrderedDict

copy()[source]
devito.tools.as_tuple(item, type=None, length=None)[source]

Force item to a tuple.

Partly extracted from: https://github.com/OP2/PyOP2/.

class devito.tools.change_directory(newPath)[source]

Bases: object

Context manager for changing the current working directory.

Adapted from:

https://stackoverflow.com/questions/431684/how-do-i-cd-in-python/
devito.tools.ctypes_pointer(name)[source]

Create a ctypes type representing a C pointer to a custom data type name.

devito.tools.ctypes_to_C(ctype)[source]

Map ctypes types to C types.

devito.tools.filter_ordered(elements, key=None)[source]

Filter elements in a list while preserving order.

Parameters:key – Optional conversion key used during equality comparison.
devito.tools.filter_sorted(elements, key=None)[source]

Filter elements in a list and sort them by key

devito.tools.flatten(l)[source]

Flatten a hierarchy of nested lists into a plain list.

devito.tools.grouper(iterable, n)[source]

Split an interable into groups of size n, plus a reminder

devito.tools.invert(mapper)[source]

Invert a dict of lists preserving the order.

devito.tools.numpy_to_ctypes(dtype)[source]

Map numpy types to ctypes types.

devito.tools.partial_order(elements)[source]

Compute a partial order for the items in elements. If a partial order cannot be established, return the empty list. If multiple partial orderings are possible, determinism in ensured.

devito.tools.pprint(node, verbose=True)[source]

Shortcut to pretty print Iteration/Expression trees.

devito.tools.roundm(x, y)[source]

Return x rounded up to the closest multiple of y.

devito.visitors module

Visitor hierarchy to inspect and/or create Expression/Iteration trees.

The main Visitor class is extracted from https://github.com/coneoproject/COFFEE.

class devito.visitors.FindNodes(match, mode='type')[source]

Bases: devito.visitors.Visitor

classmethod default_retval()[source]
rules = {'scope': <function <lambda>>, 'type': <function <lambda>>}
visit_Node(o, ret=None)[source]
visit_object(o, ret=None)[source]
visit_tuple(o, ret=None)[source]
class devito.visitors.FindSections[source]

Bases: devito.visitors.Visitor

classmethod default_retval()[source]
visit_Element(o, ret=None, queue=None)
visit_Expression(o, ret=None, queue=None)[source]
visit_FunCall(o, ret=None, queue=None)
visit_Iteration(o, ret=None, queue=None)[source]
visit_Node(o, ret=None, queue=None)[source]
visit_tuple(o, ret=None, queue=None)[source]
class devito.visitors.FindSymbols(mode='kernel-data')[source]

Bases: devito.visitors.Visitor

classmethod default_retval()[source]
rules = {'free-symbols': <function <lambda>>, 'kernel-data': <function <lambda>>, 'symbolics-writes': <function <lambda>>, 'dimensions': <function <lambda>>, 'symbolics': <function <lambda>>}
visit_Expression(o)[source]
visit_Iteration(o)[source]
visit_tuple(o)[source]
class devito.visitors.FindScopes[source]

Bases: devito.visitors.FindSections

classmethod default_retval()[source]
visit_Element(o, ret=None, queue=None)
visit_Expression(o, ret=None, queue=None, in_omp_region=False)
visit_FunCall(o, ret=None, queue=None, in_omp_region=False)[source]
class devito.visitors.IsPerfectIteration[source]

Bases: devito.visitors.Visitor

Return True if an Iteration defines a perfect loop nest, False otherwise.

visit_Iteration(o, found=False, multi=False)[source]
visit_Node(o, found=False, **kwargs)[source]
visit_object(o, **kwargs)[source]
visit_tuple(o, **kwargs)[source]
class devito.visitors.SubstituteExpression(subs={})[source]

Bases: devito.visitors.Transformer

Transformer that performs symbol substitution on Expression objects in a given tree.

Parameters:subs – Dict defining the symbol substitution
visit_Expression(o)[source]
devito.visitors.printAST(node, verbose=True)[source]
class devito.visitors.CGen[source]

Bases: devito.visitors.Visitor

Return a representation of the Iteration/Expression tree as a :module:`cgen` tree.

visit_Block(o)[source]
visit_Element(o)[source]
visit_Expression(o)[source]
visit_FunCall(o)[source]
visit_Function(o)[source]
visit_Iteration(o)[source]
visit_List(o)[source]
visit_LocalExpression(o)[source]
visit_Operator(o)[source]
visit_tuple(o)[source]
class devito.visitors.ResolveIterationVariable(mapper={})[source]

Bases: devito.visitors.Transformer

Transformer class that creates a substitution dictionary for replacing Dimension instances with explicit loop variables in Iteration nodes. For buffered dimensions it also inserts the relevant definitions for buffer index variables, for exaple.:

for (int t = 0; t < t_size; t += 1)
{
    int t0 = (t) % 2;
    int t1 = (t + 1) % 2;
visit_Expression(o, subs={}, offsets=defaultdict(<type 'set'>, {}))[source]

Collect all offsets used with a dimension

visit_Iteration(o, subs={}, offsets=defaultdict(<type 'set'>, {}))[source]
class devito.visitors.Transformer(mapper={})[source]

Bases: devito.visitors.Visitor

Given an Iteration/Expression tree T and a mapper from nodes in T to a set of new nodes L, M : N –> L, build a new Iteration/Expression tree T’ where a node n in N is replaced with M[n].

In the special case in which M[n] is None, n is dropped from T’.

In the special case in which M[n] is an iterable of nodes, n is “extended” by pre-pending to its body the nodes in M[n].

visit(o, *args, **kwargs)[source]
visit_Node(o, **kwargs)[source]
visit_list(o, **kwargs)
visit_object(o, **kwargs)[source]
visit_tuple(o, **kwargs)[source]
class devito.visitors.NestedTransformer(mapper={})[source]

Bases: devito.visitors.Transformer

Unlike a Transformer, a NestedTransforer applies replacements in a depth-first fashion.

visit_Node(o, **kwargs)[source]
class devito.visitors.FindAdjacentIterations[source]

Bases: devito.visitors.Visitor

classmethod default_retval()[source]
handler(o, parent=None, ret=None)[source]
visit_Iteration(o, parent=None, ret=None)[source]
visit_Node(o, parent=None, ret=None)[source]
visit_object(o, parent=None, ret=None)[source]
visit_tuple(o, parent=None, ret=None)[source]

Module contents

devito.clear_cache()[source]
devito.print_defaults()[source]

Print the environment variables accepted by Devito, their default value, as well as all of the accepted values.

devito.print_state()[source]

Print the current configuration state.