API Reference#

Oct2Py#

class oct2py.Oct2Py(logger=None, timeout=None, oned_as='row', temp_dir=None, convert_to_float=True, backend=None)[source]#

Manages an Octave session.

Uses MAT files to pass data between Octave and Numpy. The function must either exist as an m-file in this directory or on Octave’s path. The first command will take about 0.5s for Octave to load up. The subsequent commands will be much faster.

You may provide a logger object for logging events, or the oct2py.get_log() default will be used. When calling commands, logger.info() will be used to stream output, unless a stream_handler is provided.

Parameters:
  • logger (logging object, optional) – Optional logger to use for Oct2Py session

  • timeout (float, optional) – Timeout in seconds for commands

  • oned_as ({'row', 'column'}, optional) – If ‘column’, write 1-D numpy arrays as column vectors. If ‘row’, write 1-D numpy arrays as row vectors.}

  • temp_dir (str, optional) – If specified, the session’s MAT files will be created in the directory, otherwise a default directory is used. This can be a shared memory (tmpfs) path.

  • convert_to_float (bool, optional) – If true, convert integer types to float when passing to Octave.

  • backend (string, optional) – The graphics_toolkit to use for plotting.

Start Octave and set up the session.

property logger#

The logging instance used by the session.

exit()[source]#

Quits this octave session and cleans up.

push(name, var, timeout=None, verbose=True)[source]#

Put a variable or variables into the Octave session.

Parameters:
  • name (str or list) – Name of the variable(s).

  • var (object or list) – The value(s) to pass.

  • timeout (float) – Time to wait for response from Octave (per line).

  • **kwargs (Deprecated kwargs, ignored.) –

Examples

>>> from oct2py import octave
>>> y = [1, 2]
>>> octave.push('y', y)
>>> octave.pull('y')
array([[1., 2.]])
>>> octave.push(['x', 'y'], ['spam', [1, 2, 3, 4]])
>>> octave.pull(['x', 'y'])  
[u'spam', array([[1, 2, 3, 4]])]

Notes

Integer type arguments will be converted to floating point unless convert_to_float=False.

pull(var, timeout=None, verbose=True)[source]#

Retrieve a value or values from the Octave session.

Parameters:
  • var (str or list) – Name of the variable(s) to retrieve.

  • timeout (float, optional.) – Time to wait for response from Octave (per line).

  • **kwargs (Deprecated kwargs, ignored.) –

Returns:

out – Object returned by Octave.

Return type:

object

Raises:

Oct2PyError – If the variable does not exist in the Octave session.

Examples

>>> from oct2py import octave
>>> y = [1, 2]
>>> octave.push('y', y)
>>> octave.pull('y')
array([[1., 2.]])
>>> octave.push(['x', 'y'], ['spam', [1, 2, 3, 4]])
>>> octave.pull(['x', 'y'])  
[u'spam', array([[1, 2, 3, 4]])]
get_pointer(name, timeout=None)[source]#

Get a pointer to a named object in the Octave workspace.

Parameters:
  • name (str) – The name of the object in the Octave workspace.

  • timeout (float, optional.) – Time to wait for response from Octave (per line).

Examples

>>> from oct2py import octave
>>> octave.eval('foo = [1, 2];')
>>> ptr = octave.get_pointer('foo')
>>> ptr.value
array([[1., 2.]])
>>> ptr.address
'foo'
>>> # Can be passed as an argument
>>> octave.disp(ptr)  
1  2
>>> from oct2py import octave
>>> sin = octave.get_pointer('sin')  # equivalent to `octave.sin`
>>> sin.address
'@sin'
>>> x = octave.quad(sin, 0, octave.pi())
>>> x
2.0

Notes

Pointers can be passed to feval or dynamic functions as function arguments. A pointer passed as a nested value will be passed by value instead.

Raises:

Oct2PyError – If the variable does not exist in the Octave session or is of unknown type.

Return type:

A variable, object, user class, or function pointer as appropriate.

extract_figures(plot_dir, remove=False)[source]#

Extract the figures in the directory to IPython display objects.

Parameters:
  • plot_dir (str) – The plot dir where the figures were created.

  • remove (bool, optional.) – Whether to remove the plot directory after saving.

feval(func_path, *func_args, **kwargs)[source]#

Run a function in Octave and return the result.

Parameters:
  • func_path (str) – Name of function to run or a path to an m-file.

  • func_args (object, optional) – Args to send to the function.

  • nout (int or str, optional.) – The desired number of returned values, defaults to 1. If nout value is ‘max_nout’, _get_max_nout() will be used.

  • store_as (str, optional) – If given, saves the result to the given Octave variable name instead of returning it.

  • verbose (bool, optional) – Log Octave output at INFO level. If False, log at DEBUG level.

  • stream_handler (callable, optional) – A function that is called for each line of output from the evaluation.

  • timeout (float, optional) – The timeout in seconds for the call.

  • plot_dir (str, optional) – If specified, save the session’s plot figures to the plot directory instead of displaying the plot window.

  • plot_backend (str, optional) – The plotting back end to use.

  • plot_name (str, optional) – Saved plots will start with plot_name and end with “_%%.xxx’ where %% is the plot number and xxx is the plot_format.

  • plot_format (str, optional) – The format in which to save the plot.

  • plot_width (int, optional) – The plot with in pixels.

  • plot_height (int, optional) – The plot height in pixels.

Notes

The function arguments passed follow Octave calling convention, not Python. That is, all values must be passed as a comma separated list, not using x=foo assignment.

Examples

>>> from oct2py import octave
>>> cell = octave.feval('cell', 10, 10, 10)
>>> cell.shape
(10, 10, 10)
>>> from oct2py import octave
>>> x = octave.feval('linspace', 0, octave.pi() / 2)
>>> x.shape
(1, 100)
>>> from oct2py import octave
>>> x = octave.feval('svd', octave.hilb(3))
>>> x
array([[1.40831893],
       [0.12232707],
       [0.00268734]])
>>> # specify three return values
>>> (u, v, d) = octave.feval('svd', octave.hilb(3), nout=3)
>>> u.shape
(3, 3)
Return type:

The Python value(s) returned by the Octave function call.

eval(cmds, verbose=True, timeout=None, stream_handler=None, temp_dir=None, plot_dir=None, plot_name='plot', plot_format='svg', plot_backend=None, plot_width=None, plot_height=None, plot_res=None, nout=0, **kwargs)[source]#

Evaluate an Octave command or commands.

Parameters:
  • cmds (str or list) – Commands(s) to pass to Octave.

  • verbose (bool, optional) – Log Octave output at INFO level. If False, log at DEBUG level.

  • stream_handler (callable, optional) – A function that is called for each line of output from the evaluation.

  • timeout (float, optional) – Time to wait for response from Octave (per line). If not given, the instance timeout is used.

  • nout (int or str, optional.) – The desired number of returned values, defaults to 0. If nout is 0, the ans will be returned as the return value. If nout value is ‘max_nout’, _get_max_nout() will be used.

  • temp_dir (str, optional) – If specified, the session’s MAT files will be created in the directory, otherwise a the instance temp_dir is used. a shared memory (tmpfs) path.

  • plot_dir (str, optional) – If specified, save the session’s plot figures to the plot directory instead of displaying the plot window.

  • plot_name (str, optional) – Saved plots will start with plot_name and end with “_%%.xxx’ where %% is the plot number and xxx is the plot_format.

  • plot_format (str, optional) – The format in which to save the plot (PNG by default).

  • plot_width (int, optional) – The plot with in pixels.

  • plot_height (int, optional) – The plot height in pixels.

  • plot_backend (str, optional) – The plot backend to use.

  • plot_res (int, optional) – The plot resolution in pixels per inch.

  • kwargs. (**kwargs Deprecated) –

Examples

>>> from oct2py import octave
>>> octave.eval('disp("hello")') 
hello
>>> x = octave.eval('round(quad(@sin, 0, pi/2));')
>>> x
1.0
>>> a = octave.eval('disp("hello");1;')  
hello
>>> a = octave.eval('disp("hello");1;', verbose=False)
>>> a
1.0
>>> from oct2py import octave
>>> lines = []
>>> octave.eval('for i = 1:3; disp(i);end',                         stream_handler=lines.append)
>>> lines  
[' 1', ' 2', ' 3']
Returns:

out – Octave “ans” variable, or None.

Return type:

object

Notes

The deprecated log kwarg will temporarily set the logger level to WARN. Using the logger settings directly is preferred. The deprecated return_both kwarg will still work, but the preferred method is to use the stream_handler. If stream_handler is given, the return_both kwarg will be honored but will give an empty string as the response.

Raises:

Oct2PyError – If the command(s) fail.

restart()[source]#

Restart an Octave session in a clean state

Struct#

class oct2py.Struct[source]#

Octave style struct, enhanced.

Notes

Supports dictionary and attribute style access. Can be pickled, and supports code completion in a REPL.

Examples

>>> from pprint import pprint
>>> from oct2py import Struct
>>> a = Struct()
>>> a.b = 'spam'  # a["b"] == 'spam'
>>> a.c["d"] = 'eggs'  # a.c.d == 'eggs'
>>> pprint(a)
{'b': 'spam', 'c': {'d': 'eggs'}}

Cell#

class oct2py.Cell(value, session=None)[source]#

A Python representation of an Octave cell array.

Notes

This class is not meant to be directly created by the user. It is created automatically for cell array values received from Octave. The last axis is squeezed if it is of size 1 to simplify element access.

Examples

>>> from oct2py import octave
>>> # generate the struct array
>>> octave.eval("x = cell(2,2); x(:) = 1.0;")
>>> x = octave.pull('x')
>>> x
Cell([[1.0, 1.0],
       [1.0, 1.0]])
>>> x[0]
Cell([1.0, 1.0])
>>> x[0].tolist()
[1.0, 1.0]

Create a cell array from a value and optional Octave session.

StructArray#

class oct2py.StructArray(value, session=None)[source]#

A Python representation of an Octave structure array.

Notes

Accessing a record returns a Cell containing the values. This class is not meant to be directly created by the user. It is created automatically for structure array values received from Octave. The last axis is squeezed if it is of size 1 to simplify element access.

Examples

>>> from oct2py import octave
>>> # generate the struct array
>>> octave.eval('x = struct("y", {1, 2}, "z", {3, 4});')
>>> x = octave.pull('x')
>>> x.y  # attribute access -> oct2py Cell
Cell([[1.0, 2.0]])
>>> x['z']  # item access -> oct2py Cell
Cell([[3.0, 4.0]])
>>> x[0, 0]  # index access -> numpy record
(1.0, 3.0)
>>> x[0, 1].z
4.0

Create a struct array from a value and optional Octave session.

Oct2PyError#

class oct2py.Oct2PyError[source]#

Called when we can’t open Octave or Octave throws an error

get_log#

oct2py.get_log(name=None)[source]#

Return a console logger.

Output may be sent to the logger using the debug, info, warning, error and critical methods.

Parameters:

name (str) – Name of the log.

kill_octave#

oct2py.kill_octave()[source]#

Kill all octave instances (cross-platform).

This will restart the “octave” instance. If you have instantiated Any other Oct2Py objects, you must restart them.