Skip to content

Commit

Permalink
RELEASE v0.1.7 (#23)
Browse files Browse the repository at this point in the history
* Add indexing ops to DictPropertyWrapper

* Update matlab checker to be more robust

* Add error message to install MCR toolbox in checkPath

* Add wrapper generation scripts

* Fix wrapper script so pydoc help works

* Bugfix applying to SpinW and Horace

Move wrapper script matlab2python into libpymcr namespace
Fix packaging of matlab2python
Fix bug in wrapper argument parsing (convert to tuple)
MatlabProxyObject call() dunder methods needs wrapping
Convert subsref access ref to use Py-tuple to force mat-cell
Fix call.m nargout bug for function name collision ("fit")

* More bugfixes from testing with SpinW

Extend DictPropertyWrapper to lists allowing
  their elements to be set individually
Add new VectorPropertyWrapper so np column vectors
  can be indexed with a single index
Fix matlab2python script to properly handle packages
Bypass a disassembly bug in get_nlhs
Add R2024a to list of versions

* Update Changelog and citation
  • Loading branch information
mducle authored May 30, 2024
1 parent 3db5507 commit fc5fab4
Show file tree
Hide file tree
Showing 10 changed files with 581 additions and 96 deletions.
30 changes: 30 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,33 @@
# [v0.1.7](https://github.com/pace-neutrons/libpymcr/compare/v0.1.6...v0.1.7)

## New Features

Add a command `matlab2python` which generates Python wrappers for Matlab code in a specified directory (syntax is similar to `mcc`).
By default the Python wrappers are created in a package folder called `matlab_wrapped`.
If you have a package and want to call the Matlab functions without the `m.` prefix, you can do:

```
from matlab_wrapped import *
```

Matlab class properties which are standard types (`dict`s, `list`s and numpy arrays) are now better supported by a fix to `DictPropertyWrapper` and a new `VectorPropertyWrapper`, which allows syntax like:

```
obj.prop['a'] = 1
obj.prop[1] = 2
```

Matlab column vectors can be indexed with a single index (rather than requiring a tuple as in `obj.prop[1,2]` which numpy requires).

## Bugfixes

Bugfixes for some issues arising from testing in preparation for EDATC2

* Update matlab checker to be more robust and to output a warning of a licensed Matlab was found but the Compiler SDK toolbox is not installed.
* Fix `MatlabProxyObject` dunder methods to work with libpymcr.
* Fix `MatlabProxyObject` indexing bug where libpymcr converted the old list to a vector instead of a cell-array (now uses a tuple).
* Fix a bug in `call.m` where `nargout` is confused if the called function is shadowed (e.g. `fit`) and it could not determined the maximum `nargout`.

# [v0.1.6](https://github.com/pace-neutrons/libpymcr/compare/v0.1.5...v0.1.6)

## Bugfixes
Expand Down
2 changes: 1 addition & 1 deletion CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ authors:
given-names: "Gregory S."
orcid: https://orcid.org/0000-0002-2787-8054
title: "libpymcr"
version: "0.1.6"
version: "0.1.7"
date-released: "2024-04-26"
license: "GPL-3.0-only"
repository: "https://github.com/pace-neutrons/libpymcr"
Expand Down
2 changes: 1 addition & 1 deletion libpymcr/Matlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __getattr__(self, name):
class NamespaceWrapper(object):
def __init__(self, interface, name):
self._interface = interface
self._name = name
self._name = name[:-1] if name.endswith('_') else name

def __getattr__(self, name):
return NamespaceWrapper(self._interface, f'{self._name}.{name}')
Expand Down
86 changes: 62 additions & 24 deletions libpymcr/MatlabProxyObject.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from io import StringIO
from .utils import get_nlhs
import numpy as np
import re

def wrap(inputs, interface):
Expand All @@ -25,38 +26,75 @@ def unwrap(inputs, interface):
return interface.call('feval', meth_wrapper, inputs.proxy.handle)
elif isinstance(inputs, tuple):
return tuple(unwrap(v, interface) for v in inputs)
elif isinstance(inputs, list):
elif isinstance(inputs, list) or isinstance(inputs, range):
return [unwrap(v, interface) for v in inputs]
elif isinstance(inputs, dict):
return {k:unwrap(v, interface) for k, v in inputs.items()}
else:
return inputs


class VectorPropertyWrapper:
# A proxy for a Matlab (ndarray) column vector to allow single indexing
def __init__(self, val):
self.val = val

def __getitem__(self, ind):
return self.val[0, ind] if ind > 0 else self.val[ind]

def __setitem__(self, ind, value):
if ind > 0:
self.val[0, ind] = value
else:
self.val[ind] = value

def __repr__(self):
return self.val.__repr__()


class DictPropertyWrapper:
# A proxy for dictionary properties of classes to allow Matlab .dot syntax
def __init__(self, val, name, parent):
assert isinstance(val, dict), "DictPropertyWrapper can only wrap dict objects"
self.__dict__['val'] = val
self.__dict__['name'] = name
self.__dict__['parent'] = parent

def __getattr__(self, name):
rv = self.val[name]
if isinstance(rv, dict):
if isinstance(rv, dict) or isinstance(rv, list):
rv = DictPropertyWrapper(rv, name, self)
elif isinstance(rv, np.ndarray) and rv.shape[0] == 1:
rv = VectorPropertyWrapper(rv)
return rv

def __setattr__(self, name, value):
self.val[name] = value
setattr(self.parent, self.name, self.val)

def __getitem__(self, name):
rv = self.val[name]
if isinstance(rv, dict) or isinstance(rv, list):
rv = DictPropertyWrapper(rv, name, self)
return rv

def __setitem__(self, name, value):
self.val[name] = value
setattr(self.parent, self.name, self.val)

def __repr__(self):
rv = "Matlab struct with fields:\n"
for k, v in self.val.items():
rv += f" {k}: {v}\n"
return rv

@property
def __name__(self):
return self.name

@property
def __origin__(self):
return getattr(type(self.parent), self.name)


class matlab_method:
def __init__(self, proxy, method):
Expand Down Expand Up @@ -141,7 +179,7 @@ def __getattr__(self, name):
if name in self._getAttributeNames():
try:
rv = wrap(self.interface.call('subsref', self.handle, {'type':'.', 'subs':name}), self.interface)
if isinstance(rv, dict):
if isinstance(rv, dict) or isinstance(rv, list):
rv = DictPropertyWrapper(rv, name, self)
return rv
except TypeError:
Expand All @@ -168,38 +206,38 @@ def __dir__(self):
def __getitem__(self, key):
if not (isinstance(key, int) or (hasattr(key, 'is_integer') and key.is_integer())) or key < 0:
raise RuntimeError('Matlab container indices must be positive integers')
key = [float(key + 1)] # Matlab uses 1-based indexing
return self.interface.call('subsref', self.handle, {'type':'()', 'subs':key})
key = (float(key + 1),) # Matlab uses 1-based indexing
return wrap(self.interface.call('subsref', self.handle, {'type':'()', 'subs':key}), self.interface)

def __setitem__(self, key, value):
if not (isinstance(key, int) or (hasattr(key, 'is_integer') and key.is_integer())) or key < 0:
raise RuntimeError('Matlab container indices must be positive integers')
if not isinstance(value, MatlabProxyObject) or repr(value) != self.__repr__():
raise RuntimeError('Matlab container items must be same type.')
access = self.interface.call('substruct', '()', [float(key + 1)]) # Matlab uses 1-based indexing
self.__dict__['handle'] = self.interface.call('subsasgn', self.handle, access, value)
access = self.interface.call('substruct', '()', (float(key + 1),)) # Matlab uses 1-based indexing
self.__dict__['handle'] = self.interface.call('subsasgn', self.handle, access, value.handle)

def __len__(self):
return int(self.interface.call('numel', self.handle, nargout=1))

# Operator overloads
def __eq__(self, other):
return self.interface.call('eq', self.handle, other, nargout=1)
return self.interface.call('eq', self.handle, unwrap(other, self.interface), nargout=1)

def __ne__(self, other):
return self.interface.call('ne', self.handle, other, nargout=1)
return self.interface.call('ne', self.handle, unwrap(other, self.interface), nargout=1)

def __lt__(self, other):
return self.interface.call('lt', self.handle, other, nargout=1)
return self.interface.call('lt', self.handle, unwrap(other, self.interface), nargout=1)

def __gt__(self, other):
return self.interface.call('gt', self.handle, other, nargout=1)
return self.interface.call('gt', self.handle, unwrap(other, self.interface), nargout=1)

def __le__(self, other):
return self.interface.call('le', self.handle, other, nargout=1)
return self.interface.call('le', self.handle, unwrap(other, self.interface), nargout=1)

def __ge__(self, other):
return self.interface.call('ge', self.handle, other, nargout=1)
return self.interface.call('ge', self.handle, unwrap(other, self.interface), nargout=1)

def __bool__(self):
return self.interface.call('logical', self.handle, nargout=1)
Expand All @@ -208,7 +246,7 @@ def __and__(self, other): # bit-wise & operator (not `and` keyword)
return self.interface.call('and', self.handle, other, nargout=1)

def __or__(self, other): # bit-wise | operator (not `or` keyword)
return self.interface.call('or', self.handle, other, nargout=1)
return self.interface.call('or', self.handle, unwrap(other, self.interface), nargout=1)

def __invert__(self): # bit-wise ~ operator (not `not` keyword)
return self.interface.call('not', self.handle, nargout=1)
Expand All @@ -223,31 +261,31 @@ def __abs__(self):
return self.interface.call('abs', self.handle, nargout=1)

def __add__(self, other):
return self.interface.call('plus', self.handle, other, nargout=1)
return self.interface.call('plus', self.handle, unwrap(other, self.interface), nargout=1)

def __radd__(self, other):
return self.interface.call('plus', other, self.handle, nargout=1)
return self.interface.call('plus', unwrap(other, self.interface), self.handle, nargout=1)

def __sub__(self, other):
return self.interface.call('minus', self.handle, other, nargout=1)
return self.interface.call('minus', self.handle, unwrap(other, self.interface), nargout=1)

def __rsub__(self, other):
return self.interface.call('minus', other, self.handle, nargout=1)
return self.interface.call('minus', unwrap(other, self.interface), self.handle, nargout=1)

def __mul__(self, other):
return self.interface.call('mtimes', self.handle, other, nargout=1)
return self.interface.call('mtimes', self.handle, unwrap(other, self.interface), nargout=1)

def __rmul__(self, other):
return self.interface.call('mtimes', other, self.handle, nargout=1)
return self.interface.call('mtimes', unwrap(other, self.interface), self.handle, nargout=1)

def __truediv__(self, other):
return self.interface.call('mrdivide', self.handle, other, nargout=1)
return self.interface.call('mrdivide', self.handle, unwrap(other, self.interface), nargout=1)

def __rtruediv__(self, other):
return self.interface.call('mrdivide', other, self.handle, nargout=1)
return self.interface.call('mrdivide', unwrap(other, self.interface), self.handle, nargout=1)

def __pow__(self, other):
return self.interface.call('mpower', self.handle, other, nargout=1)
return self.interface.call('mpower', self.handle, unwrap(other, self.interface), nargout=1)

@property
def __doc__(self):
Expand Down
Loading

0 comments on commit fc5fab4

Please sign in to comment.