<<

Oct2Py Documentation Release 4.3.0

Oct2Py contributors

May 02, 2019

CONTENTS

1 Features 3

2 API Reference 17

3 Installation 19

4 Examples 21

5 Type Conversions 23

6 Information 25

Python Module Index 27

i ii Oct2Py Documentation, Release 4.3.0

Oct2Py allows you to seamlessly call M-files and Octave functions from Python. It manages the Octave session for you, sharing data behind the scenes using MAT files. Usage is as simple as:

>>> oc= oct2py.Oct2Py() >>> x= oc.zeros(3,3) >>> print(x, x.dtype) [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] float64 ...

If you want to run legacy m-files, do not have MATLAB®, and do not fully trust a code translator, this is your library.

CONTENTS 1 Oct2Py Documentation, Release 4.3.0

2 CONTENTS CHAPTER ONE

FEATURES

• Supports all Octave datatypes and most Python datatypes and Numpy dtypes. • Provides OctaveMagic for IPython, including inline plotting in notebooks. • Supports cell arrays and structs/struct arrays with arbitrary nesting. • Supports matrices. • Builds methods on the fly linked to Octave commands (e.g. zeros above). • Thread-safety: each Oct2Py object uses an independent Octave session. • Can be used as a context manager. • Supports characters. • Supports logging of session commands. • Optional timeout command parameter to prevent runaway Octave sessions.

1.1 Installation

1.1.1 Library Installation

You must have GNU Octave installed and in your PATH (see instructions below). The library is only known to work with Octave 4.0+. Additionally, you must have the Numpy and Scipy libraries for Python installed. The simplest way to get them is to use the Anaconda distribution. Once the dependencies have been installed, run:

$ install oct2py

If using conda, it is available on conda-forge:

$ conda install - conda-forge oct2py

1.1.2 GNU Octave Installation

• On platforms, try your , or follow the instructions from Octave. You must also have gnuplot installed, and gnuplot-x11 or gnuplot-, if available. • On OSX, the recommended methods are listed on this wiki.

3 Oct2Py Documentation, Release 4.3.0

• On Windows, download the latest MinGW or .NET version. Cygwin is NOT supported. The MinGW version requires the 7zip program for installation. sure to install gnuplot if prompted. Finally, to add Octave to your path. You can do so from the Environmental Variables dialog for your version of Windows, or set from the command prompt:

setx PATH"%PATH%;

Where the folder has the file “octave.exe”. If you see the message: “WARNINGS: The data being saved is truncated to 1024 characters” It means your PATH variable is too long. You’ll have to manually trim in in the Windows Environmental Variables editor. • To test, open a command window (or terminal) and type: octave. If Octave starts, you should be good to go. • Alternatively, you can specify the path to your Octave executable by creating an OCTAVE_EXECUTABLE en- vironmental variable.

1.2 Demo

Output of Oct2Py demo script, showing most of the features of the library. Note that the two plot commands will generate an interactive plot in the actual demo. To run interactively:

>>> ######################### >>> # Oct2Py demo >>> ######################### >>> import numpy as np >>> from oct2py import Oct2Py >>> oc= Oct2Py() >>> # basic commands >>> print(oc.abs(-1)) 1 >>> print(oc.upper('xyz')) XYZ >>> # plotting >>> oc.plot([1,2,3],'-o','linewidth',2) Press Enter to continue...

4 Chapter 1. Features Oct2Py Documentation, Release 4.3.0

>>> oc.close() >>> xx= np.arange(-2 *np.pi,2 *np.pi, 0.2) >>> oc.surf(np.subtract.outer(np.sin(xx), np.cos(xx))) Press Enter to continue...

1.2. Demo 5 Oct2Py Documentation, Release 4.3.0

>>> oc.close() >>> # getting help >>> help(oc.svd)

Help on function svd in module oct2py.session: svd(*args, **kwargs) `svd' is a function from the file c:\Program Files\Octave-3.6.2\lib\octave\3.6.

˓→2\oct\i686-pc-mingw32\svd.oct

-- Loadable Function: S = svd (A) -- Loadable Function: [U, S, V] = svd (A) -- Loadable Function: [U, S, V] = svd (A, ECON) Compute the singular value decomposition of A

A = U*S*V'

The function `svd' normally returns only the vector of singular values. When called with three return values, it computes U, S, and V. For example,

svd (hilb (3)) (continues on next page)

6 Chapter 1. Features Oct2Py Documentation, Release 4.3.0

(continued from previous page)

returns

ans =

1.4083189 0.1223271 0.0026873

and

[u, s, v] = svd (hilb (3))

returns

u =

-0.82704 0.54745 0.12766 -0.45986 -0.52829 -0.71375 -0.32330 -0.64901 0.68867

s =

1.40832 0.00000 0.00000 0.00000 0.12233 0.00000 0.00000 0.00000 0.00269

v =

-0.82704 0.54745 0.12766 -0.45986 -0.52829 -0.71375 -0.32330 -0.64901 0.68867

If given a second argument, `svd' returns an economy-sized decomposition, eliminating the unnecessary rows or columns of U or V.

See also: svd_driver, svds, eig

Additional help for built-in functions and operators is available in the on-line version of the manual. Use the command `doc ' to search the manual index.

Help and information about Octave is also available on the WWW at http://www.octave.org and via the [email protected] mailing list.

>>> # single vs. multiple return values >>> print(oc.svd(np.array([[1,2], [1,3]]))) [[ 3.86432845] [ 0.25877718]] >>> U, S, V= oc.svd([[1,2], [1,3]], nout=3) >>> print(U, S, V) [[-0.57604844 -0.81741556] [-0.81741556 0.57604844]] [[ 3.86432845 0. ] (continues on next page)

1.2. Demo 7 Oct2Py Documentation, Release 4.3.0

(continued from previous page) [ 0. 0.25877718]] [[-0.36059668 -0.93272184] [-0.93272184 0.36059668]] >>> # low level constructs >>> oc.eval("y=ones(3,3)") >>> print(oc.pull("y")) [[ 1. 1. 1.] [ 1. 1. 1.] [ 1. 1. 1.]] >>> oc.eval("x=zeros(3,3)", verbose=True) >>> t= oc.eval('rand(1, 2)', verbose=True) >>> y= np.zeros((3,3)) >>> oc.push('y', y) >>> print(oc.pull('y')) [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] >>> from oct2py import Struct >>> y= Struct() >>> y.b='spam' >>> y.c.d='eggs' >>> print(y.c['d']) eggs >>> print(y) {'c': {'d': 'eggs'}, 'b': 'spam'} >>> ######################### >>> # Demo Complete! >>> #########################

1.3 Examples

1.3.1 OctaveMagic

Oct2Py provides a plugin for IPython to bring Octave to the IPython prompt or the IPython Notebook.

1.3.2 M-File Examples

M-files in the directory where oct2py was initialized, or those in the Octave path, can be called like any other Octave function. To explicitly add to the path, use:

>>> from oct2py import octave >>> octave.addpath('/path/to/directory') to add the directory in which your m-file is located to Octave’s path.

Roundtrip roundtrip.m function [x, class] = roundtrip(y) % returns the input variable and its class (continues on next page)

8 Chapter 1. Features Oct2Py Documentation, Release 4.3.0

(continued from previous page) x = y class = class(x)

Python Session

>>> from oct2py import octave >>> import numpy as np >>> x= np.array([[1,2], [3,4]], dtype=float) >>> out, oclass= octave.roundtrip(x) >>> import pprint >>> pprint.pprint([x, x.dtype, out, oclass, out.dtype]) [array([[ 1., 2.], [ 3., 4.]]), dtype('float64'), array([[ 1., 2.], [ 3., 4.]]), 'double', dtype('float64')]

Test Datatypes test_datatypes.m function test= test_datatypes() % Test of returning a structure with multiple % nesting and multiple return types

%%%%%%%%%%%%%%% % numeric types % integers test.num.int.int8= int8(-2^7); test.num.int.int16= int16(-2^15); test.num.int.int32= int32(-2^31); test.num.int.int64= int64(-2^63); test.num.int.uint8= uint8(2^8-1); test.num.int.uint16= uint16(2^16-1); test.num.int.uint32= uint32(2^32-1); test.num.int.uint64= uint64(2^64-1);

%floats test.num.float32= single(pi); test.num.float64= double(pi); test.num.complex=3+1j; test.num.complex_matrix=(1+1j) * rand([22])

% misc test.num.inf= inf test.num.NaN= NaN test.num.matrix=[12;34] test.num.vector=[1234] test.num.column_vector=[1;2;3;4] test.num.matrix3d= rand([234]) (continues on next page)

1.3. Examples 9 Oct2Py Documentation, Release 4.3.0

(continued from previous page) test.num.matrix5d= rand(1,2,3,4,5)

%%%%%%%%%%%%%%% % logical type test.logical=[10 20 30 40 50]> 30

%%%%%%%%%%%%%%% % string types test.string.basic='spam' test.string.char_array={'spam','eggs';'foo','bar'} test.string.cell_array={'spam','eggs'}

%%%%%%%%%%%%%%% % struct types test.struct.array(1).name='Sharon' test.struct.array(1).age= 31 test.struct.array(2).name='Bill' test.struct.array(2).age= 42

%%%%%%%%%%%%%%% % cell array types test.cell.vector={'spam', 4.0,[123]} test.cell.matrix={'Bob', 40;'Pam', 41}

Python Session

>>> from oct2py import octave >>> out= octave.test_dataypes() >>> import pprint >>> pprint.pprint(out) {u'cell': {u'matrix': [['Bob', 'Pam'], [40.0, 41.0]], u'vector': ['spam', 4.0, array([[ 1., 2., 3.]])]}, u'logical': array([[0, 0, 0, 1, 1]]), u'num': {u'NaN': nan, u'column_vector': array([[ 1.], [ 2.], [ 3.], [ 4.]]), u'complex': (3+1j), u'complex_matrix': array([[ 0.29801132+0.29801132j, 0.25385592+0.

˓→25385592j], [ 0.36628765+0.36628765j, 0.17222843+0.17222843j]]), u'float32': 3.1415927, u'float64': 3.1415926535897931, u'inf': inf, u'int': {u'int16': -32768, u'int32': -2147483648, u'int64': -9223372036854775808, u'int8': -128, u'uint16': 65535, u'uint32': 4294967295, u'uint64': 18446744073709551615, u'uint8': 255}, u'matrix': array([[ 1., 2.], (continues on next page)

10 Chapter 1. Features Oct2Py Documentation, Release 4.3.0

(continued from previous page) [ 3., 4.]]), u'matrix3d': array([[[ 0.37748504, 0.42576504, 0.33770276, 0.28353423], [ 0.07772849, 0.79317342, 0.35633704, 0.84392906], [ 0.27743843, 0.58173155, 0.60478932, 0.15784762]],

[[ 0.61831316, 0.52826816, 0.2561059 , 0.69882897], [ 0.78915391, 0.55164477, 0.34382527, 0.23743691], [ 0.7984285 , 0.13977171, 0.77679021, 0.22355376]]]), u'matrix5d': array([[[[[ 0.87245616, 0.3935346 , 0.00509518, 0.18260647,

˓→ 0.2328523 ], [ 0.57790841, 0.26083328, 0.82910847, 0.79100768, 0.111686 ], [ 0.01399121, 0.80096565, 0.50399158, 0.51631872, 0.07292035], [ 0.59993558, 0.62226338, 0.26245502, 0.71373283, 0.54863195]],

[[ 0.47438503, 0.17510892, 0.31801117, 0.09766319, 0.72427364], [ 0.02762037, 0.73835099, 0.6464369 , 0.59452631, 0.26695231], [ 0.01843247, 0.10938661, 0.68805356, 0.43229338, 0.84202539], [ 0.77406571, 0.21564875, 0.6492912 , 0.18763039, 0.02976736]],

[[ 0.32019185, 0.67178221, 0.33481521, 0.39093148, 0.51177757], [ 0.59023927, 0.91152032, 0.26690269, 0.46438787, 0.02999184], [ 0.08864962, 0.97042015, 0.10310935, 0.12789306, 0.71532619], [ 0.19870871, 0.14683877, 0.0367708 , 0.96534334, 0.04710378]]],

[[[ 0.97058297, 0.12706106, 0.05109758, 0.16347541, 0.88931781], [ 0.43036654, 0.97654587, 0.99862712, 0.33365358, 0.74330177], [ 0.41980651, 0.74997277, 0.9978432 , 0.44787774, 0.60519502], [ 0.94386177, 0.12320678, 0.01164074, 0.34409676, 0.34135462]],

[[ 0.92895971, 0.81883047, 0.27796085, 0.9303487 , 0.01020294], [ 0.30430039, 0.74434446, 0.3828099 , 0.15817473, 0.74870604], [ 0.82601961, 0.28806172, 0.75975623, 0.76901488, 0.06666695], [ 0.58065392, 0.96855147, 0.7603041 , 0.98177511, 0.59357169]],

[[ 0.86808738, 0.89797971, 0.16175654, 0.93365793, 0.25343561], [ 0.25567182, 0.75436271, 0.94137345, 0.04822251, 0.69818659], [ 0.18410575, 0.07060479, 0.20660155, 0.06567875, 0.83880553], [ 0.61876976, 0.64932156, 0.21524418, 0.99559647, 0.34971336]]]]]), u'vector': array([[ 1., 2., 3., 4.]])}, u'string': {u'basic': 'spam', u'cell_array': ['spam', 'eggs'], u'char_array': [['spam', 'foo '], ['eggs', 'bar ']]}, u'struct': {u'array': {u'age': [31.0, 42.0], u'name': ['Sharon', 'Bill']}}}

1.4 Conversions

1.4.1 Python to Octave Types

Shows the round-trip data types, originating in Python. Lists and sets will be converted to a numeric array if possible, falling back on cells. If an Octave cell consisting of numbers is desired, use a tuple. Cell, Struct, StructArray are Oct2Py convenience classes.

1.4. Conversions 11 Oct2Py Documentation, Release 4.3.0

Python Octave Python int int32 np.int32 long int64 np.int64 float double np.float64 complex double np.complex128 str char unicode unicode cell unicode bool logical np.bool None nan np.nan dict struct Struct tuple cell Cell list array or cell ndarray or Cell set array or cell ndarray or Cell Struct struct Struct StructArray struct array StructArray

1.4.2 Numpy to Octave Types

Note that when convert_to_float is set (default is True), integer types are converted to floating point before sending them to Octave.

Numpy Octave Numpy np.int8 int8 np.int8 np.int16 int16 np.int16 np.int32 int32 np.int32 np.int64 int64 np.int64 np.uint8 uint8 np.uint8 np.uint16 uint16 np.uint16 np.uint32 uint32 np.uint32 np.uint64 uint64 np.uint64 np.float16 double np.float64 np.float32 single np.float32 np.float64 double np.float64 np.float128 double np.float64 np.double double np.float64 np.complex64 double np.complex64 np.complex128 double np.complex128 np.complex256 double np.complex128 np.bool logical bool np.str cell list np.object cell list sparse sparse sparse recarray struct array StructArray

1.4.3 Octave to Python Types

These are handled unambiguously. The only known data type that is not transferable is a function pointer, since Octave cannot save them to the v6 MAT file format.

12 Chapter 1. Features Oct2Py Documentation, Release 4.3.0

Octave Python array ndarray cell Cell struct Struct struct array StructArray logical ndarray (of uint8) sparse sparse user defined object Oct2Py object pointer

1.5 API Reference

1.5.1 Oct2Py

1.5.2 Struct

1.5.3 Cell

1.5.4 StructArray

1.5.5 Oct2PyError

1.5.6 get_log

1.5.7 kill_octave

1.6 Information

1.6.1 Dynamic Functions

Oct2Py will create methods for you on the fly, which correspond to Octave functions. For example:

>>> from oct2py import octave >>> octave.ones(3) array([[ 1., 1., 1.], [ 1., 1., 1.], [ 1., 1., 1.]])

If you pass keyword arguments to the function, they will be treated as Octave keywords, for example, octave.plot(x, y, linewidth=3) becomes plot(x, y, ‘linewidth’, 3). Arguments that are integer type will be converted to floats unless you set convert_to_float=False. Additionally, you can look up the documentation for one of these methods using help()

>>> help(octave.ones) 'ones' is a built-in function ...

1.5. API Reference 13 Oct2Py Documentation, Release 4.3.0

1.6.2 Interactivity

Oct2Py supports code completion in IPython, so once you have created a method, you can recall it on the fly, so octave.one would give you ones. Structs (mentioned below) also support code completion for attributes. You can share data with an Octave session explicitly using the push and pull methods. When using other Oct2Py methods, the variable names in Octave with underscores because they are temporary (you would only see this if you were using logging).

>>> from oct2py import octave >>> octave.push('a',1) >>> octave.pull('a') 1

1.6.3 Using M-Files

In order to use an m-file in Oct2Py you must first call addpath for the directory containing the script. You can then use it as a dynamic function or use the eval function to call it. Alternatively, you can call feval with the full path.

>>> from oct2py import octave >>> octave.addpath('/path/to/') >>> octave.myscript(1,2) >>> # or >>> octave.eval("myscript(1, 2)") >>> # as feval >>> octave.feval('/path/to/myscript',1,2)

1.6.4 Direct Interaction

Oct2Py supports the Octave keyboard function which drops you into an interactive Octave prompt in the current session. This also works in the IPython Notebook. Note: If you use the keyboard command and the session hangs, try opening an Octave session from your terminal and see if the keyboard command hangs there too. You may need to update your version of Octave.

1.6.5 Logging

Oct2Py supports logging of session interaction. You can provide a logger to the constructor or set one at any time.

>>> import logging >>> from oct2py import Oct2Py, get_log >>> oc= Oct2Py(logger=get_log()) >>> oc.logger= get_log('new_log') >>> oc.logger.setLevel(logging.INFO)

All Oct2Py methods support a verbose keyword. If True, the commands are logged at the INFO level, otherwise they are logged at the DEBUG level.

1.6.6 Shadowed Function Names

If you’d like to call an Octave function that is also an Oct2Py method, you must add a trailing underscore. For example:

14 Chapter 1. Features Oct2Py Documentation, Release 4.3.0

>>> from oct2py import octave >>> octave.eval_('a=1') 'a = 1'

The methods that shadow Octave builtins are: exit and eval.

1.6.7 Timeout

Oct2Py sessions have a timeout attribute that determines how long to wait for a command to complete. The default is 1e6 seconds (indefinite). You may either set the timeout for the session, or as a keyword argument to an individual command. The session is closed in the event of a timeout.

>>> from oct2py import octave >>> octave.timeout=3 >>> octave.sleep(2) >>> octave.sleep(2, timeout=1) Traceback (most recent call last): ... oct2py.utils.Oct2PyError: Session timed out

1.6.8 Graphics Toolkit

Oct2Py uses the gnuplot graphics toolkit by default. Fltk has been known not to work on some systems. To change toolkits:

>>> from oct2py import octave >>> octave.available_graphics_toolkits() [u'fltk', u'gnuplot'] >>> octave.graphics_toolkit('fltk')

1.6.9 Context Manager

Oct2Py can be used as a Context Manager. The session will be closed and the temporary m-files will be deleted when the Context Manager exits.

>>> from oct2py import Oct2Py >>> with Oct2Py() as oc: >>> oc.ones(10)

1.6.10 Structs

Struct is a convenience class that mimics an Octave structure variable type. It is a dictionary with attribute lookup, and it creates sub-structures on the fly of arbitrary nesting depth. It can be pickled. You can also use tab completion for attributes when in IPython.

>>> from oct2py import Struct >>> test= Struct() >>> test['foo']=1 >>> test.bizz['buzz']='bar' >>> test (continues on next page)

1.6. Information 15 Oct2Py Documentation, Release 4.3.0

(continued from previous page) {'foo': 1, 'bizz': {'buzz': 'bar'}} >>> import pickle >>> p= pickle.dumps(test)

1.6.11 Unicode

Oct2Py supports Unicode characters, so you may feel free to use m-files that contain them.

1.6.12 Speed

There is a performance penalty for passing information using MAT files. If you have a lot of calculations, it is probably better to make an m-file that does the looping and data aggregation, and pass that back to Python for further processing. To see an example of the speed penalty on your machine, run:

>>> import oct2py >>> oct2py.speed_check()

1.6.13 Threading

If you want to use threading, you must create a new Oct2Py instance for each thread. The octave convenience instance is in itself not threadsafe. Each Oct2Py instance has its own dedicated Octave session and will not interfere with any other session.

1.6.14 IPython Notebook

Oct2Py provides OctaveMagic for IPython, including inline plotting in notebooks. This requires IPython >= 1.0.0.

16 Chapter 1. Features CHAPTER TWO

API REFERENCE

Documentation for the functions included in Oct2Py.

17 Oct2Py Documentation, Release 4.3.0

18 Chapter 2. API Reference CHAPTER THREE

INSTALLATION

How to install Oct2Py.

19 Oct2Py Documentation, Release 4.3.0

20 Chapter 3. Installation CHAPTER FOUR

EXAMPLES

Introductory examples.

21 Oct2Py Documentation, Release 4.3.0

22 Chapter 4. Examples CHAPTER FIVE

TYPE CONVERSIONS

Oct2Py data type conversions.

23 Oct2Py Documentation, Release 4.3.0

24 Chapter 5. Type Conversions CHAPTER SIX

INFORMATION

Other information about Oct2Py.

25 Oct2Py Documentation, Release 4.3.0

26 Chapter 6. Information PYTHON MODULE INDEX

o oct2py, 13

27 Oct2Py Documentation, Release 4.3.0

28 Python Module Index INDEX

O oct2py (module), 13

29