Oct2py Documentation Release 4.3.0
Total Page:16
File Type:pdf, Size:1020Kb
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 sparse 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 Unicode 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: $ pip install oct2py If using conda, it is available on conda-forge: $ conda install -c conda-forge oct2py 1.1.2 GNU Octave Installation • On Linux platforms, try your package manager, or follow the instructions from Octave. You must also have gnuplot installed, and gnuplot-x11 or gnuplot-qt, 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. Make 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%;<path-to-octave-dir> Where the folder <path-to-octave-dir> 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 <topic>' 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,