From 29af1049a0d6d7c5540b3059310bcb85acd7031d Mon Sep 17 00:00:00 2001 From: Duc Le Date: Sat, 23 Sep 2023 17:20:28 +0100 Subject: [PATCH 1/5] Update to use new libpymcr Remove most Python code (moved to libpymcr) Add new C++ call_python code (copied from libpymcr) this is temporary; will use a mex from libpymcr directly in future Brille and TobyFit+Euphonic test errors out need fixes to pyclasswrapper and call_python --- CMakeLists.txt | 7 +- pace_neutrons/CMakeLists.txt | 15 - pace_neutrons/DataTypes.py | 112 ------ pace_neutrons/FunctionWrapper.py | 68 ---- pace_neutrons/IPythonMagics.py | 260 ------------- pace_neutrons/MCR_license.txt | 28 -- pace_neutrons/Matlab.py | 198 ---------- pace_neutrons/MatlabFunction.py | 69 ---- pace_neutrons/MatlabProxyObject.py | 262 ------------- pace_neutrons/MatlabStruct.py | 2 - pace_neutrons/TypeWrappers.py | 67 ---- pace_neutrons/__init__.py | 6 - pace_neutrons/funcinspect.py | 312 --------------- src/CMakeLists.txt | 34 +- src/call.m | 232 ++++++----- src/call_method.m | 151 -------- src/call_python.cpp | 471 ++--------------------- src/call_python_m.m | 70 ---- src/check_wrapped_function.m | 12 - src/getArgOut.m | 21 - src/get_global.m | 11 - src/get_method_refs.m | 15 - src/has_thin_members.m | 24 -- src/load_matlab.cpp | 113 ++++++ src/load_matlab.hpp | 31 ++ src/matlab.cmake | 171 +++++++++ src/matlab_mex.hpp | 194 ++++++++++ src/pythonFunctionWrapper.m | 27 -- src/pythonRemoveFuncKey.cpp | 58 --- src/recfind.m | 65 ---- src/set_global.m | 8 - src/thinwrapper.m | 12 - src/type_converter.cpp | 591 +++++++++++++++++++++++++++++ src/type_converter.hpp | 176 +++++++++ src/waitforgui.m | 43 --- src/wrap_obj.m | 20 - 36 files changed, 1466 insertions(+), 2490 deletions(-) delete mode 100644 pace_neutrons/CMakeLists.txt delete mode 100644 pace_neutrons/DataTypes.py delete mode 100644 pace_neutrons/FunctionWrapper.py delete mode 100644 pace_neutrons/IPythonMagics.py delete mode 100644 pace_neutrons/MCR_license.txt delete mode 100644 pace_neutrons/Matlab.py delete mode 100644 pace_neutrons/MatlabFunction.py delete mode 100644 pace_neutrons/MatlabProxyObject.py delete mode 100644 pace_neutrons/MatlabStruct.py delete mode 100644 pace_neutrons/TypeWrappers.py delete mode 100644 pace_neutrons/__init__.py delete mode 100644 pace_neutrons/funcinspect.py delete mode 100644 src/call_method.m delete mode 100644 src/call_python_m.m delete mode 100644 src/check_wrapped_function.m delete mode 100644 src/getArgOut.m delete mode 100644 src/get_global.m delete mode 100644 src/get_method_refs.m delete mode 100644 src/has_thin_members.m create mode 100644 src/load_matlab.cpp create mode 100644 src/load_matlab.hpp create mode 100644 src/matlab.cmake create mode 100644 src/matlab_mex.hpp delete mode 100644 src/pythonFunctionWrapper.m delete mode 100644 src/pythonRemoveFuncKey.cpp delete mode 100644 src/recfind.m delete mode 100644 src/set_global.m delete mode 100644 src/thinwrapper.m create mode 100644 src/type_converter.cpp create mode 100644 src/type_converter.hpp delete mode 100644 src/waitforgui.m delete mode 100644 src/wrap_obj.m diff --git a/CMakeLists.txt b/CMakeLists.txt index 1fdaa60..54009c5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -63,9 +63,8 @@ endif() # You can set a specific Matlab version folder here #set(Matlab_ROOT_DIR "c:/Program Files/MATLAB/R2020a") -find_package(Matlab REQUIRED COMPONENTS MAIN_PROGRAM MEX_COMPILER MCC_COMPILER) -get_filename_component(Matlab_LIBRARY_DIR "${Matlab_MEX_LIBRARY}" DIRECTORY) -get_filename_component(Matlab_BIN_DIR "${Matlab_MAIN_PROGRAM}" DIRECTORY) +find_package(Matlab REQUIRED COMPONENTS MCC_COMPILER) +include(src/matlab.cmake) # Get the Matlab release from the VersionInfo.xml file file(READ "${Matlab_ROOT_DIR}/VersionInfo.xml" _release_info) @@ -86,4 +85,4 @@ endif() include(PACE) add_subdirectory(src) -add_subdirectory(pace_neutrons) +#add_subdirectory(pace_neutrons) diff --git a/pace_neutrons/CMakeLists.txt b/pace_neutrons/CMakeLists.txt deleted file mode 100644 index 65dc0be..0000000 --- a/pace_neutrons/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -add_custom_target(copy_python ALL) -if(WIN32) - add_custom_command( - TARGET copy_python PRE_BUILD - COMMAND ${POWERSHELL_COMMAND} New-Item -ItemType Directory -Force -Path "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/pace_neutrons" - COMMAND ${POWERSHELL_COMMAND} Copy-Item -Path "${CMAKE_CURRENT_SOURCE_DIR}/*py" -Destination "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/pace_neutrons" - ) -else() - add_custom_command( - TARGET copy_python PRE_BUILD - COMMAND ${BASH_COMMAND} mkdir -p "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/pace_neutrons" - COMMAND ${BASH_COMMAND} cp "${CMAKE_CURRENT_SOURCE_DIR}/*py" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/pace_neutrons/" - #COMMAND ${BASH_COMMAND} cp -r "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/pace_neutrons/*" "${CMAKE_CURRENT_SOURCE_DIR}/" - ) -endif() diff --git a/pace_neutrons/DataTypes.py b/pace_neutrons/DataTypes.py deleted file mode 100644 index 221c6a4..0000000 --- a/pace_neutrons/DataTypes.py +++ /dev/null @@ -1,112 +0,0 @@ -import six -import numpy as np -from numbers import Number -from .MatlabProxyObject import MatlabProxyObject -from .MatlabFunction import MatlabFunction -from .TypeWrappers import as_matlab, as_numpy -from .FunctionWrapper import pymatpy - -NPY_INT = [np.uint8, np.int8, np.uint16, np.int16, np.uint32, np.int32, np.uint64, np.int64, np.bool_] - -class DataTypes: - - def __init__(self, interface, pyMatlab): - """ - Data Converter to/from python and MATLAB - :param matlab: - """ - self.matlab = pyMatlab - self.interface = interface - # self.outNumpy = True - # self.transpose = True - - def _unwrap(self, datalist): - for ii in range(len(datalist)): - datalist[ii] = self.encode(datalist[ii]) - return datalist - - def encode(self, data): - - # What is data? - # 1) If it's a numpy array or a list, we convert. to matlab.double - # 2) If it is a dict, then we enumerate values and encode them. - # 3) If it's a tuple, it's a cell, which we enumerate. BUT, then we convert it into a list. - # 4) If it is a double it's a double, if a integer, we encode to a double as well. MATLAB is tricky :-/ - - if isinstance(data, bool): - data = self.matlab.logical([data]) - elif isinstance(data, list) or isinstance(data, range): - # Case 1) - try: - data = self.matlab.double(data) - except ValueError: - data = self._unwrap(data) - # If the list is not one of numbers leave it for Matlab to convert to a cell array - elif isinstance(data, np.ndarray): - if data.size < 1000 and data.dtype in NPY_INT: - data = self.matlab.double(data.tolist()) - else: - data = as_matlab(data) - elif isinstance(data, Number): - # Case 4) - data = float(data) - elif isinstance(data, MatlabFunction): - if isinstance(data._fun, six.string_types): - if data._parent: - data = self.interface.get_method_refs(data._fun, data._parent, nargout=1) - else: - data = self.interface.get_method_refs(data._fun, nargout=1) - else: - data = data._fun - elif isinstance(data, MatlabProxyObject): - data = data.handle - elif hasattr(data, '__call__'): - # A python callable - wrap it so that a Matlab mex using the C API can call it - data = pymatpy(data, self.interface) - else: - # Case 2, 3 - if isinstance(data, dict): - # Case 2) - for key, item in data.items(): - data[key] = self.encode(item) - elif isinstance(data, tuple): - # Case 3) - newdata = [] - for item in data: - newdata.append(self.encode(item)) - data = newdata - - # Unknown data i.e. text should pass through - # TODO Make sure this works for more data cases... - return data - - def decode(self, data): - # Decode the numeric data types. NOTE that we let the functions/methods slip through. - if isinstance(data, list): - # This is a cell return - for key, item in enumerate(data): - data[key] = self.decode(data[key]) - data = tuple(data) - elif isinstance(data, tuple): - return (self.decode(d) for d in data) - elif isinstance(data, self.matlab.double): - data = as_numpy(data) - elif isinstance(data, self.matlab.int8): - # TODO for all available data types - data = np.ndarray(data) - elif isinstance(data, str): - if len(data) == 34: - if data[0:2] == '!$': - try: - data = self.decode(self.interface.get_global(data[2:])) - except Exception as e: - print(e) - elif isinstance(data, dict): - for key, item in data.items(): - data[key] = self.decode(item) - elif self.interface.call('isobject', [data]): - data = MatlabProxyObject(self.interface, data, self) - elif self.interface.call('isa', [data, 'function_handle']): - data = MatlabFunction(self.interface, data, converter=self, parent=[]) - - return data diff --git a/pace_neutrons/FunctionWrapper.py b/pace_neutrons/FunctionWrapper.py deleted file mode 100644 index b400021..0000000 --- a/pace_neutrons/FunctionWrapper.py +++ /dev/null @@ -1,68 +0,0 @@ -import uuid -import numpy as np - -_globalObjectsDict = {} -_globalFunctionDict = {} - -def remove_object(object_string): - _globalObjectsDict.pop(object_string, None) - -def get_obj_prop(object_string, prop_name): - return getattr(_globalObjectsDict[object_string], prop_name) - -def call_obj_method(object_string, method_name, *args, **kwargs): - return getattr(_globalObjectsDict[object_string], method_name)(*args, **kwargs) - -_globalFunctionDict['remove_object'] = remove_object -_globalFunctionDict['get_obj_prop'] = get_obj_prop -_globalFunctionDict['call_obj_method'] = call_obj_method - - -def pymatpy(func, interface): - func_uuid = str(uuid.uuid4()) - _globalFunctionDict[func_uuid] = func - return interface.call('pythonFunctionWrapper', [func_uuid]) - - -class WrappedPythonClass(object): - def __init__(self, input_class, typename='pyobj'): - self.target_class = input_class - self.typename = typename - - def __call__(self, *args, **kwargs): - args = [_globalObjectsDict[arg] if (isinstance(arg, str) and arg.startswith('pyobj')) else arg for arg in args] - kwargs = {ky:(_globalObjectsDict[val] if (isinstance(val, str) and val.startswith('pyobj')) else val) for ky, val in kwargs.items()} - input_object = self.target_class(*args, **kwargs) - obj_uuid = str(uuid.uuid4()) - key_string = self.typename + obj_uuid - _globalObjectsDict[key_string] = input_object - return key_string - -try: - from brille.utils import create_bz, create_grid -except ImportError: - pass -else: - wrapped_create_bz = WrappedPythonClass(create_bz, 'pyobj_bz') - wrapped_create_grid = WrappedPythonClass(create_grid, 'pyobj_grid') - _globalFunctionDict['create_bz'] = wrapped_create_bz - _globalFunctionDict['create_grid'] = wrapped_create_grid - def brille_grid_fill(objstr, *args): - # We have to do the reshape here because Matlab swallows singleton dims - args = list(args) - for idx in ([0, 2, 3, 5] if len(args) > 5 else [0, 2]): - shp = np.shape(args[idx]) - if len(shp) < 3: - args[idx] = np.reshape(args[idx], (shp[0], shp[1], 1)) - for idx in ([1, 4] if len(args) > 5 else [1, 3]): - args[idx] = np.reshape(args[idx], (np.prod(np.shape(args[idx])),)).astype('int32') - if len(args) % 2 == 1: - args[-1] = args[-1][0] - return getattr(_globalObjectsDict[objstr], 'fill')(*args) - _globalFunctionDict['brille_grid_fill'] = brille_grid_fill - def brille_ir_interpolate_at(objstr, *args): - # Again we can't transpose in Matlab because brille needs a C-style array - hkl = args[0] if np.shape(args[0])[1] == 3 else np.transpose(args[0]) - kwargs = {args[idx]:args[idx+1] for idx in range(1, len(args), 2)} if len(args) > 1 else {} - return getattr(_globalObjectsDict[objstr], 'ir_interpolate_at')(hkl, **kwargs) - _globalFunctionDict['brille_ir_interpolate_at'] = brille_ir_interpolate_at diff --git a/pace_neutrons/IPythonMagics.py b/pace_neutrons/IPythonMagics.py deleted file mode 100644 index 8d408ae..0000000 --- a/pace_neutrons/IPythonMagics.py +++ /dev/null @@ -1,260 +0,0 @@ -from IPython import get_ipython -from IPython.core import magic_arguments -from IPython.core.magic import Magics, magics_class, line_magic -from IPython.display import Image, display -import ipykernel - -import threading -import ctypes -import time -import sys -import io -import os -try: - from tempfile import TemporaryDirectory, TemporaryFile, NamedTemporaryFile -except ImportError: - from backports.tempfile import TemporaryDirectory, TemporaryFile, NamedTemporaryFile - -_magic_class_ref = None - -# We will overload the `post_run_cell` event with this function -# That callback is a method of `EventManager` hence the `self` argument -def showPlot(self=None, result=None): - # We use a global reference to the magics class to get the reference to Matlab interpreter - # If it doesn't exist, we can't do anything, and assume the user is just using Python - ip = get_ipython() - if ip is None or _magic_class_ref is None or _magic_class_ref.plot_type != 'inline': - return - try: - from matlab import double as md - except ImportError: - return - else: - if _magic_class_ref.m is None: - from . import Matlab - _magic_class_ref.m = Matlab().interface - interface = _magic_class_ref.m - nfig = len(interface.call('get',(0., "children"))) - if nfig == 0: - return - if _magic_class_ref.next_pars: - width, height, resolution = (_magic_class_ref.next_pars[idx] for idx in ['width', 'height', 'resolution']) - else: - width, height, resolution = (_magic_class_ref.width, _magic_class_ref.height, _magic_class_ref.resolution) - interface.call('set', (0., 'defaultfigurepaperposition', md([0, 0, width / resolution, height / resolution])), nargout=0) - interface.call('set', (0., 'defaultfigurepaperunits', 'inches'), nargout=0) - format = 'png' - with TemporaryDirectory() as tmpdir: - try: - interface.call('eval', - ["arrayfun(@(h, i) print(h, sprintf('{}/%i', i), '-d{}', '-r{}'),get(0, 'children'), (1:{})')" - .format('/'.join(tmpdir.split(os.sep)), format, resolution, nfig)], - nargout=0) - interface.call('eval', ["arrayfun(@(h) close(h), get(0, 'children'))"], nargout=0) - for fname in sorted(os.listdir(tmpdir)): - display(Image(filename=os.path.join(tmpdir, fname))) - except Exception as exc: - ip.showtraceback() - return - finally: - interface.call('set', (0., 'defaultfigurevisible', 'off'), nargout=0) - if _magic_class_ref.next_pars: - _magic_class_ref.next_pars = None - -# Matlab writes to the C-level stdout / stderr file descriptors -# whereas IPython overloads the Python-level sys.stdout / sys.stderr streams -# To force Matlab output into the IPython cells we need to -# 1. Duplicate the stdout/err file descriptors into a pipe (with os.dup2) -# 2. Create a thread which watches the pipe and re-prints to IPython -# See: https://stackoverflow.com/questions/41216215/ -# https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/ - -class Redirection(object): - # Class which redirects a C-level file descriptor to the equiv. IPython stream - - thread = None - stop_flag = None - saved_fd = None - read_pipe = None - exc_info = None - - def __init__(self, target='stdout'): - self.target = {'stdout':sys.__stdout__, 'stderr':sys.__stderr__}[target].fileno() - self.output = {'stdout':sys.stdout, 'stderr':sys.stderr}[target] - self.ip = get_ipython() - self.flush = lambda: None - - def not_redirecting(self): - return ( - self.ip is None or _magic_class_ref is None or - (_magic_class_ref.output != 'inline' and self.saved_fd == None) - ) - - def pre(self): - if self.not_redirecting(): - return - if self.saved_fd == None: - self.saved_fd = os.dup(self.target) - self.read_pipe, write_pipe = os.pipe() - os.dup2(write_pipe, self.target) - os.close(write_pipe) - - def redirect_thread(): - try: - while not self.stop_flag: - raw = os.read(self.read_pipe, 1000) - if raw: - self.output.write(raw.decode()) - self.flush() - except Exception: - self.exc_info = sys.exc_info() - - self.stop_flag = False - self.thread = threading.Thread(target=redirect_thread) - self.thread.daemon = True # Makes the thread non-blocking - self.thread.start() - - def showtraceback(self): - self.ip.showtraceback() - - def post(self): - if self.not_redirecting() or self.saved_fd == None: - return - sys.stdout.flush() - os.dup2(self.saved_fd, self.target) - self.stop_flag = True - os.close(self.read_pipe) - os.close(self.saved_fd) - if sys.platform.startswith("linux") or sys.platform.startswith("darwin"): - self.thread.join() - self.thread = None - self.saved_fd = None - if self.exc_info: - self.showtraceback() - - -@magics_class -class MatlabMagics(Magics): - """ - Class for IPython magics for interacting with Matlab - - It defines several magic functions: - - %pace - sets up the plotting environment (default 'inline') - %matlab_fig - defines the inline figure size and resolution for the next plot only - """ - - def __init__(self, shell, interface): - super(MatlabMagics, self).__init__(shell) - self.m = interface - self.shell = get_ipython().__class__.__name__ - self.output = 'inline' - self.plot_type = 'inline' if self.shell == 'ZMQInteractiveShell' \ - else 'windowed' - self.width = 400 - self.height = 300 - self.resolution = 300 - self.next_pars = None - global _magic_class_ref - _magic_class_ref = self - - @line_magic - @magic_arguments.magic_arguments() - @magic_arguments.argument('plot_type', type=str, help="Matlab plot type, either: 'inline' or 'windowed'") - @magic_arguments.argument('output', nargs='?', type=str, help="Matlab output, either: 'inline' or 'console'") - @magic_arguments.argument('-w', '--width', type=int, help="Default figure width in pixels [def: 400]") - @magic_arguments.argument('-h', '--height', type=int, help="Default figure height in pixels [def: 300]") - @magic_arguments.argument('-r', '--resolution', type=int, help="Default figure resolution in dpi [def: 150]") - def pace(self, line): - """Set up pace_neutrons to work with IPython notebooks - - Use this magic function to set the behaviour of Matlab programs Horace and SpinW in Python. - You can specify how plots should appear: either 'inline' [default] or 'windowed'. - You can also specify how Matlab text output from functions appear: 'inline' [default] or 'console' - - Examples - -------- - By default the inline backend is used for both figures and outputs. - To switch behaviour use, use: - - In [1]: %pace windowed # windowed figures, output unchanged ('inline' default) - In [2]: %pace console # figure unchanged ('inline' default), console output - In [3]: %pace windowed console # windowed figures, console output - In [4]: %pace inline inline # inline figures, inline output - In [5]: %pace inline # inline figures, inline output - In [6]: %pace inline console # inline figures, console output - In [7]: %pace windowed inline # windowed figures, console output - - Note that if you specify `%pace inline` this sets `'inline'` for _both_ figures and outputs. - If you want inline figures and console outputs or windowed figures and inline output you must specify - that specifically. - - Note that using (default) inline text output imposes a slight performance penalty. - - For inlined figures, you can also set the default figure size and resolution with - - In [8]: %pace inline --width 400 --height 300 --resolution 150 - - The values are in pixels for the width and height and dpi for resolution. A short cut: - - In [9]: %pace inline -w 400 -h 300 -r 150 - - Also works. The width, height and resolution only applies to inline figures. - You should use the usual Matlab commands to resize windowed figures. - """ - args = magic_arguments.parse_argstring(self.pace, line) - plot_type = args.plot_type if args.plot_type else self.plot_type - output = args.output if args.output else self.output - if args.plot_type and args.plot_type == 'inline' and args.output == None: - output = 'inline' - self.output = output - if plot_type == 'inline': - self.plot_type = plot_type - if args.width: self.width = args.width - if args.height: self.height = args.height - if args.resolution: self.resolution = args.resolution - elif plot_type == 'windowed': - self.plot_type = plot_type - else: - raise RuntimeError(f'Unknown plot type {plot_type}') - try: - import matlab - except ImportError: - return - if plot_type == 'inline': - self.m.call('set', (0., 'defaultfigurevisible', 'off'), nargout=0) - self.m.call('set', (0., 'defaultfigurepaperpositionmode', 'manual'), nargout=0) - elif plot_type == 'windowed': - self.m.call('set', (0., 'defaultfigurevisible', 'on'), nargout=0) - self.m.call('set', (0., 'defaultfigurepaperpositionmode', 'auto'), nargout=0) - else: - raise RuntimeError(f'Unknown plot type {plot_type}') - - @line_magic - @magic_arguments.magic_arguments() - @magic_arguments.argument('-w', '--width', type=int, help="Default figure width in pixels [def: 400]") - @magic_arguments.argument('-h', '--height', type=int, help="Default figure height in pixels [def: 300]") - @magic_arguments.argument('-r', '--resolution', type=int, help="Default figure resolution in dpi [def: 150]") - def matlab_fig(self, line): - """Defines size and resolution of the next inline Matlab figure to be plotted - - Use this magic function to define the figure size and resolution of the next figure - (and only that figure) without changing the default size and resolution. - - Examples - -------- - Size and resolution is specified as options, any which is not defined here will use the default values - These values are reset after the figure is plotted (default: width=400, height=300, resolution=150) - - In [1]: %matlab_fig -w 800 -h 200 -r 300 - m.plot(-pi:0.01:pi, sin(-pi:0.01:pi), '-') - - In [2]: m.plot(-pi:0.01:pi, cos(-pi:0.01:pi), '-') - - The sine graph in the first cell will be 800x200 at 300 dpi, whilst the cosine graph is 400x300 150 dpi. - """ - args = magic_arguments.parse_argstring(self.matlab_fig, line) - width = args.width if args.width else self.width - height = args.height if args.height else self.height - resolution = args.resolution if args.resolution else self.resolution - self.next_pars = {'width':width, 'height':height, 'resolution':resolution} diff --git a/pace_neutrons/MCR_license.txt b/pace_neutrons/MCR_license.txt deleted file mode 100644 index 2400429..0000000 --- a/pace_neutrons/MCR_license.txt +++ /dev/null @@ -1,28 +0,0 @@ -The MathWorks, Inc. - -MATLAB RUNTIME LICENSE - -IMPORTANT NOTICE -BY CLICKING THE "YES" BUTTON BELOW, YOU ACCEPT THE TERMS OF THIS LICENSE. IF YOU ARE NOT WILLING TO DO SO, SELECT THE "NO" BUTTON AND THE INSTALLATION WILL BE ABORTED. - -1. LICENSE GRANT. Subject to the restrictions below, The MathWorks, Inc. ("MathWorks") hereby grants to you, whether you are an individual or an entity, a license to install and use the MATLAB Runtime ("Runtime"), solely and expressly for the purpose of running software created with the MATLAB Compiler (the "Application Software"), and for no other purpose. This license is personal, nonexclusive, and nontransferable. - -2. LICENSE RESTRICTIONS. You shall not modify or adapt the Runtime for any reason. You shall not disassemble, decompile, or reverse engineer the Runtime. You shall not alter or remove any proprietary or other legal notices on or in copies of the Runtime. Unless used to run Application Software, you shall not rent, lease, or loan the Runtime, time share the Runtime, provide service bureau use, or use the Runtime for supporting any other party's use of the Runtime. You shall not sublicense, sell, or otherwise transfer the Runtime to any third party. You shall not republish any documentation which may be provided in connection with the Runtime. All rights not granted, including without limitation rights to reproduce, sublicense, rent, sell, distribute, create derivative works, serve other software by means of, decompile, reverse engineer, and disassemble the Runtime, are expressly reserved by MathWorks. - -3. NO TECHNICAL SUPPORT. Technical support is not provided by MathWorks for users of the Runtime under this license. MathWorks may, at its sole discretion, offer bug fixes or updates to the Runtime. - -4. TERM AND TERMINATION. This license shall automatically terminate upon your failure to comply with this license. - -5. EXPORT CONTROL. The Runtime may be subject to U.S. and non-U.S. export control laws and other applicable governmental export and import laws and regulations. In exercising your rights under this license, you agree not to violate any such laws and regulations. You also represent and warrant that (i) you are not located in a country that is subject to a U.S. Government embargo, or that has been designated by the U.S. Government as a "terrorist supporting" country; and (ii) you are not listed on any U.S. Government list of prohibited or restricted parties. - -6. U.S. GOVERNMENT LICENSEES: You agree that the Runtime qualifies as commercial computer software or documentation as defined in the FAR and/or DFARS; that the terms and conditions of this MATLAB RUNTIME LICENSE shall govern your use, reproduction, performance, display, and disclosure of the Runtime, superseding any inconsistent government provisions. - -7. ASSIGNMENT. You may not assign or otherwise transfer this license and its rights and obligations hereunder, in whole or in part. - -8. LIMITATION OF LIABILITY. To the extent permitted by law, any liability of MathWorks (whether in relation to breach of contract, negligence or otherwise) shall be limited to ten dollars ($10.00 USD); and MathWorks shall have no liability for any indirect or consequential loss (whether foreseeable or otherwise and including loss of profits, loss of business, loss of opportunity, and loss of use, or unauthorized use or access, of any computer hardware or software). Some states do not allow the exclusion or limitation of incidental or consequential damages, so the above exclusion or limitation may not apply to you. MathWorks' liability for death or personal injury resulting from negligence or for any other matter in relation to which liability by law cannot be excluded or limited shall not be excluded or limited. - -9. DISCLAIMER OF WARRANTIES. The Runtime is delivered "as is" and MathWorks makes and you receive no additional express or implied warranties. MathWorks hereby expressly disclaims any and all other conditions, warranties, or other terms of any kind or nature concerning the Runtime (including, without limitation, any with regard to noninfringement, merchantability, quality, accuracy, or fitness for a particular purpose or for your purpose). MathWorks also expressly disclaims any warranties that may be implied from usage of trade, course of dealing, or course of performance. - -10. GOVERNING LAW; JURISDICTION. This license shall be governed by the laws of the Commonwealth of Massachusetts, United States of America, without regard to its conflicts of law provisions. Neither the U.N. Convention on Contracts for the International Sale of Goods nor the Uniform Computer Information Transactions Act, or any version thereof ("UCITA"), shall apply to this license. To the extent that UCITA is applicable, the parties agree to opt out of the applicability of UCITA. - -11. ENTIRE AGREEMENT. This license contains the entire understanding of the parties with respect to the Runtime provided hereunder, and may not be modified or amended except by written instrument, executed by MathWorks and you. This license shall not supersede any product license you have with MathWorks for the MATLAB Compiler. diff --git a/pace_neutrons/Matlab.py b/pace_neutrons/Matlab.py deleted file mode 100644 index 8d1d996..0000000 --- a/pace_neutrons/Matlab.py +++ /dev/null @@ -1,198 +0,0 @@ -import os, sys -import platform -import shutil -from .funcinspect import lhs_info -from pace_neutrons_cli.utils import get_runtime_version, checkPath - -# On Windows/Conda we need to load numpy DLLs before Matlab starts -import numpy -# On some systems we need to load the BLAS/LAPACK libraries with the DEEPBIND -# flag so it doesn't conflict with Matlab's BLAS/LAPACK. -# This only works if users `import pace_neutrons` before they import scipy... -if platform.system() == 'Linux': - old_flags = sys.getdlopenflags() - sys.setdlopenflags(os.RTLD_NOW | os.RTLD_DEEPBIND) - try: - import scipy.linalg - except ImportError: - pass - sys.setdlopenflags(old_flags) - -# Import brille here to load its C module before Matlab gets loaded -try: - import brille -except ImportError: - pass - - -def _disable_umr(): - # Mark Matlab libraries so Spyder does not reload (*delete*) them - if 'spydercustomize' not in sys.modules: - return - ll = '_internal,_internal.mlarray_utils,_internal.mlarray_sequence,mlarray,' \ - 'mlexceptions,matlab,matlab_pysdk,matlab_pysdk.runtime.errorhandler,' \ - 'matlab_pysdk.runtime.futureresult,matlab_pysdk.runtime.deployablefunc,' \ - 'matlab_pysdk.runtime.deployableworkspace,matlab_pysdk.runtime,' \ - 'matlab_pysdk.runtime.deployablepackage,matlabruntimeforpython3_8' - - if 'matlab_pysdk' not in sys.modules['spydercustomize'].__umr__.namelist: - sys.modules['spydercustomize'].__umr__.namelist += ll.split(',') - - -# Store the Matlab engine as a module global wrapped inside a class -# When the global ref is deleted (e.g. when Python exits) the __del__ method is called -# Which then gracefully shutsdown Matlab, else we get a segfault. -_global_matlab_ref = None -_has_registered_magic = None - -class _MatlabInstance(object): - def __init__(self, runtime_version, mlPath): - checkPath(runtime_version, mlPath) - # We do the import here as we have to set the ENV before we can import - from pace_neutrons import pace - self._interface = pace.initialize() - print('Interface opened') - self._interface.call('pyhorace_init', [], nargout=0) - if 'SPYDER_ARGS' in os.environ: - _disable_umr() - # Sets the parallel worker to the compiled worker if it exists - if 'worker' not in sys.argv[0]: - is_windows = platform.system() == 'Windows' - worker_path = os.path.join(os.path.dirname(sys.argv[0]), 'worker_v2') - if is_windows: - worker_path = worker_path + '.exe' - if not os.path.exists(worker_path): - # Tries to search for it on the path - worker_path = shutil.which('worker_v2') - if worker_path: - pc = self._interface.call('parallel_config', [], nargout=1) - access = self._interface.call('substruct', ['.', 'worker']) - self._interface.call('subsasgn', [pc, access, worker_path]) - - def __del__(self): - if self._interface: - self._interface.exit() - print('Interface closed') - self._interface = None - - def __getattr__(self, name): - if self._interface: - return getattr(self._interface, name) - else: - raise RuntimeError('Matlab interface is not open') - - -class NamespaceWrapper(object): - def __init__(self, matlab, name): - self._matlab = matlab - self._interface = matlab.interface - self._converter = matlab.converter - self._name = name - - def __getattr__(self, name): - return NamespaceWrapper(self._matlab, f'{self._name}.{name}') - - def __call__(self, *args, **kwargs): - nargout = kwargs.pop('nargout') if 'nargout' in kwargs.keys() else None - nreturn = lhs_info(output_type='nreturns') - if nargout is None: - mnargout, undetermined = self._interface.getArgOut(self._name, nargout=2) - if not undetermined: - nargout = max(min(int(mnargout), nreturn), 1) - else: - nargout = max(nreturn, 1) - m_args = [self._converter.encode(ar) for ar in args] - results = self._interface.call_method(self._name, [], m_args, nargout=nargout) - return self._converter.decode(results) - - def getdoc(self): - # To avoid error message printing in Spyder - raise NotImplementedError - - -class Matlab(object): - def __init__(self, mlPath=None): - """ - Create an interface to a matlab compiled python library and treat the objects in a python/matlab way instead of - the ugly way it is done by default. - - :param mlPath: Path to the SDK i.e. '/MATLAB/MATLAB_Runtime/v96' or to the location where matlab is installed - (MATLAB root directory) - """ - - self.interface = None - self.pyMatlab = None - self.converter = None - self.initialize(mlPath) - - def initialize(self, mlPath=None): - """ - Initialize the matlab environment. This can only be done after the module has been imported. - - :return: None. obj has been filled with initialization pars. - """ - global _global_matlab_ref - if _global_matlab_ref is None: - _global_matlab_ref = _MatlabInstance(get_runtime_version(), mlPath) - self.interface = _global_matlab_ref - import matlab as pyMatlab - from .DataTypes import DataTypes - self.pyMatlab = pyMatlab - self.converter = DataTypes(self.interface, pyMatlab) - - def __getattr__(self, name): - """ - Override for the get attribute. We don't want to call the process but the interface, so redirect calls there and - return a MatlabProxyObject - - :param name: The function/class to be called. - :return: MatlabProxyObject of class/function given by name - """ - return NamespaceWrapper(self, name) - - def __del__(self): - """ - Auto close the python/MATLAB interface. - :return: None - """ - if self.interface: - self.interface = None - self.pyMatlab = None - - def type(self, obj): - if obj._is_thin_wrapper: - return self.interface.call('evalin', ['base', 'class({})'.format(obj._objstr)], nargout=1) - else: - return self.interface.call('class', [obj.handle], nargout=1) - - -def register_ipython_magics(): - try: - import IPython - except ImportError: - return None - else: - running_kernel = IPython.get_ipython() - # Only register these magics when running in a notebook / lab - # Other values seen are: 'TerminalInteractiveShell' and 'InteractiveShellEmbed' - if (running_kernel.__class__.__name__ != 'ZMQInteractiveShell' - and running_kernel.__class__.__name__ != 'SpyderShell'): - return None - global _has_registered_magic - _has_registered_magic = True - if running_kernel is None or sys.__stdout__ is None or sys.__stderr__ is None: - return None - from . import IPythonMagics - from traitlets import Instance - shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) - magics = IPythonMagics.MatlabMagics(shell, None) - running_kernel.register_magics(magics) - running_kernel.events.register('post_run_cell', IPythonMagics.showPlot) - # Only do redirection for Jupyter notebooks - causes errors on Spyder - if running_kernel == 'ZMQInteractiveShell': - redirect_stdout = IPythonMagics.Redirection(target='stdout') - running_kernel.events.register('pre_run_cell', redirect_stdout.pre) - running_kernel.events.register('post_run_cell', redirect_stdout.post) - -if not _has_registered_magic: - register_ipython_magics() diff --git a/pace_neutrons/MatlabFunction.py b/pace_neutrons/MatlabFunction.py deleted file mode 100644 index 5e0eb2b..0000000 --- a/pace_neutrons/MatlabFunction.py +++ /dev/null @@ -1,69 +0,0 @@ -from .funcinspect import lhs_info - -class MatlabFunction(object): - - def __init__(self, interface, fun, converter=None, parent=None, caller=None): - ''' - - Create a proxt function to handle matlab calls - - :param interface: The callable MATLAB interface (where we run functions) - :param parent: What the function has been called from. Needed for handle class updates. - :param fun: String name of function to be executed. - ''' - self._interface = interface - self.converter = converter - if parent is None: - self._parent = [] - else: - self._parent = parent - self._fun = fun - self._caller = caller - - def __call__(self, *args, **kwargs): - """Call the Matlab function. - - Calling this function will transfer all function arguments - from Python to Matlab, and translate them to the appropriate - Matlab data structures. - - Return values are translated the same way, and transferred - back to Python. - - Parameters - ---------- - nargout : int - Call the function in Matlab with this many output - arguments. If the argument not given, we will try and work - out the correct value. - **kwargs : dict - Keyword arguments are transparently translated to Matlab's - key-value pairs. For example, ``matlab.struct(foo="bar")`` - will be translated to ``struct('foo', 'bar')``. - - """ - nreturns = lhs_info(output_type='nreturns') - nargout = kwargs.pop('nargout') if 'nargout' in kwargs.keys() else None - # serialize keyword arguments: - args += sum(kwargs.items(), ()) - - # Determination of the number of output arguments is a pain. - if nargout is None: - mnargout, undetermined = self._interface.getArgOut(self._fun, nargout=2) - if not undetermined: - nargout = max(min(int(mnargout), nreturns), 1) - else: # Hope user knows how many args there should be - nargout = max(nreturns, 1) - - if not args: - args = [] - args = [self.converter.encode(ar) for ar in args] - if nargout > 0: - d = self._interface.call_method(self._fun, self._parent, args, nargout=nargout) - else: - self._interface.call_method(self._fun, self._parent, args, nargout=nargout) - if self._caller is not None: - self._caller.updateProxy() - return - - return self.converter.decode(d) diff --git a/pace_neutrons/MatlabProxyObject.py b/pace_neutrons/MatlabProxyObject.py deleted file mode 100644 index 5a3a972..0000000 --- a/pace_neutrons/MatlabProxyObject.py +++ /dev/null @@ -1,262 +0,0 @@ -from io import StringIO - -from .MatlabFunction import MatlabFunction -from .funcinspect import lhs_info -import re -import uuid - - -class MatlabProxyObject(object): - """A Proxy for an object that exists in Matlab. - - All property accesses and function calls are executed on the - Matlab object in Matlab. - - Auto populates methods and properties and can be called ala matlab/python - - """ - - def __init__(self, interface, handle, converter): - """ - Create a non numeric object of class handle (an object from a non-numeric class). - :param interface: The callable MATLAB interface (where we run functions) - :param handle: The matlabObject which represents a class object - :param converter: The converter class between MATLAB/python - """ - self.__dict__['handle'] = handle - self.__dict__['interface'] = interface - self.__dict__['converter'] = converter - self.__dict__['_is_thinwrapper'] = self.interface.call('class', [self.handle], nargout=1) == 'thinwrapper' - self.__dict__['_is_handle_class'] = self.interface.call('isa', [self.handle, 'handle'], nargout=1) - if self._is_thinwrapper: - self.__dict__['_objstr'] = self.interface.call('subsref', [self.handle, self.interface.call('substruct', ['.', 'ObjectString'])]) - - # This cause performance slow downs for large data members and an recursion issue with - # samples included in sqw object (each sample object is copied to all dependent header "files") - #if not self._is_handle_class: - # # Matlab value class: properties will not change so copy them to the Python object - # for attribute in self._getAttributeNames(): - # self.__dict__[attribute] = self.__getattr__(attribute) - self._getAttributeNames() - for method in self._getMethodNames(): - super(MatlabProxyObject, self).__setattr__(method, - MatlabFunction(self.interface, method, - converter=self.converter, parent=self.handle, - caller=self)) - - def _getAttributeNames(self): - """ - Gets attributes from a MATLAB object - :return: list of attribute names - """ - if self._is_thinwrapper: - self.__dict__['_attributes'] = self.interface.call('evalin', ['base', 'fieldnames({})'.format(self._objstr)]) - return self._attributes - else: - return self.interface.call('fieldnames', [self.interface.call('handle', [self.handle])]) - - def _getMethodNames(self): - """ - Gets methods from a MATLAB object - :return: list of method names - """ - if self._is_thinwrapper: - self.__dict__['_methods'] = self.interface.call('evalin', ['base', 'methods({})'.format(self._objstr)]) - return self._methods - else: - return self.interface.call('methods', [self.interface.call('handle', [self.handle])]) - - def __getattr__(self, name): - """Retrieve a value or function from the object. - - Properties are returned as native Python objects or - :class:`MatlabProxyObject` objects. - - Functions are returned as :class:`MatlabFunction` objects. - - """ - m = self.interface - # if it's a property, just retrieve it - if self._is_thinwrapper: - if name in self._attributes: - return self.converter.decode(self.interface.call('evalin', ['base', '{}.{}'.format(self._objstr, name)])) - class matlab_method: - def __call__(_self, *args, **kwargs): - nreturn = lhs_info(output_type='nreturns') - nargout = max(min(int(kwargs.pop('nargout') if 'nargout' in kwargs.keys() else -1), nreturn), 1) - # serialize keyword arguments: - args += sum(kwargs.items(), ()) - args = [self.converter.encode(ar) for ar in args] - return self.converter.decode(self.interface.call_method(name, self.handle, args, nargout=nargout)) - return matlab_method() - elif name in self.interface.call('properties', [self.handle], nargout=1): - try: - return self.converter.decode(self.interface.call('subsref', [self.handle, self.interface.call('substruct', ['.', name])])) - except TypeError: - return None - # if it's a method, wrap it in a functor - elif name in self.interface.call('methods', [self.handle], nargout=1): - class matlab_method: - def __call__(_self, *args, **kwargs): - nreturn = lhs_info(output_type='nreturns') - nargout = max(min(int(kwargs.pop('nargout') if 'nargout' in kwargs.keys() else -1), nreturn), 1) - # serialize keyword arguments: - args += sum(kwargs.items(), ()) - return getattr(m, name)(self, *args, nargout=nargout) - - # only fetch documentation when it is actually needed: - @property - def __doc__(_self): - classname = getattr(m, 'class')(self) - return self.interface.call('help', ['{0}.{1}'.format(classname, name)], nargout=1) - - return matlab_method() - - def __setattr__(self, name, value): - if self._is_thinwrapper: - vstr = 'obj{}'.format(str(uuid.uuid4()).replace('-','')) - self.interface.call('assignin', ['base', vstr, value]) - self.interface.call('evalin', ['base', '{}.{} = {}'.format(self._objstr, name, vstr)], nargout=0) - else: - access = self.interface.call('substruct', ['.', name]) - self.interface.call('subsasgn', [self.handle, access, value]) - - def __repr__(self): - if self._is_thinwrapper: - out = StringIO() - objtype = self.interface.call('evalin', ['base', f"class({self._objstr})"], nargout=1, stdout=out) - return "".format(objtype) - else: - return "".format(self.interface.call('class', [self.handle])) - - def __str__(self): - # remove pseudo-html tags from Matlab output - if self._is_thinwrapper: - html_str = self.interface.call('evalin', ['base', f"evalc('display({self._objstr})')"], nargout=1) - else: - html_str = self.interface.call('eval', ["@(x) evalc('disp(x)')"]) - html_str = self.interface.call(html_str, [self.handle]) - return re.sub(']*>', '', html_str) - - def __dir__(self): - return list(set(super(MatlabProxyObject, self).__dir__() + list(self.__dict__.keys()) + self._getAttributeNames())) - - 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 = [self.converter.encode(key + 1)] # Matlab uses 1-based indexing - return self.converter.decode(self.interface.call('subsref', [self.handle, self.interface.call('substruct', ['()', key])])) - - 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.') - key = key + 1 # Matlab uses 1-based indexing - if self._is_thinwrapper: - self.interface.call('evalin', ['base', '{}({}) = {}'.format(self._objstr, key, value._objstr)], nargout=0) - else: - access = self.interface.call('substruct', ['()', [self.converter.encode(key)]]) - self.__dict__['handle'] = self.interface.call('subsasgn', [self.handle, access, self.converter.encode(value)]) - - def __len__(self): - return int(self.converter.decode(self.interface.call('numel', [self.handle], nargout=1))) - - # Operator overloads - def __eq__(self, other): - return self.converter.decode(self.interface.call_method('eq', self.handle, [self.converter.encode(other)], nargout=1)) - - def __ne__(self, other): - return self.converter.decode(self.interface.call_method('ne', self.handle, [self.converter.encode(other)], nargout=1)) - - def __lt__(self, other): - return self.converter.decode(self.interface.call_method('lt', self.handle, [self.converter.encode(other)], nargout=1)) - - def __gt__(self, other): - return self.converter.decode(self.interface.call_method('gt', self.handle, [self.converter.encode(other)], nargout=1)) - - def __le__(self, other): - return self.converter.decode(self.interface.call_method('le', self.handle, [self.converter.encode(other)], nargout=1)) - - def __ge__(self, other): - return self.converter.decode(self.interface.call_method('ge', self.handle, [self.converter.encode(other)], nargout=1)) - - def __bool__(self): - return self.converter.decode(self.interface.call_method('logical', self.handle, [], nargout=1)) - - def __and__(self, other): # bit-wise & operator (not `and` keyword) - return self.converter.decode(self.interface.call_method('and', self.handle, [self.converter.encode(other)], nargout=1)) - - def __or__(self, other): # bit-wise | operator (not `or` keyword) - return self.converter.decode(self.interface.call_method('or', self.handle, [self.converter.encode(other)], nargout=1)) - - def __invert__(self): # bit-wise ~ operator (not `not` keyword) - return self.converter.decode(self.interface.call_method('not', self.handle, [], nargout=1)) - - def __pos__(self): - return self.converter.decode(self.interface.call_method('uplus', self.handle, [], nargout=1)) - - def __neg__(self): - return self.converter.decode(self.interface.call_method('uminus', self.handle, [], nargout=1)) - - def __abs__(self): - return self.converter.decode(self.interface.call_method('abs', self.handle, [], nargout=1)) - - def __add__(self, other): - return self.converter.decode(self.interface.call_method('plus', self.handle, [self.converter.encode(other)], nargout=1)) - - def __radd__(self, other): - return self.converter.decode(self.interface.call_method('plus', self.converter.encode(other), [self.handle], nargout=1)) - - def __sub__(self, other): - return self.converter.decode(self.interface.call_method('minus', self.handle, [self.converter.encode(other)], nargout=1)) - - def __rsub__(self, other): - return self.converter.decode(self.interface.call_method('minus', self.converter.encode(other), [self.handle], nargout=1)) - - def __mul__(self, other): - return self.converter.decode(self.interface.call_method('mtimes', self.handle, [self.converter.encode(other)], nargout=1)) - - def __rmul__(self, other): - return self.converter.decode(self.interface.call_method('mtimes', self.converter.encode(other), [self.handle], nargout=1)) - - def __truediv__(self, other): - return self.converter.decode(self.interface.call_method('mrdivide', self.handle, [self.converter.encode(other)], nargout=1)) - - def __rtruediv__(self, other): - return self.converter.decode(self.interface.call_method('mrdivide', self.converter.encode(other), [self.handle], nargout=1)) - - def __pow__(self, other): - return self.converter.decode(self.interface.call_method('mpower', self.handle, [self.converter.encode(other)], nargout=1)) - - @property - def __doc__(self): - out = StringIO() - if self._is_thinwrapper: - return self.interface.call('evalin', ['base', f"evalc('help({self._objstr})')"], nargout=1, stdout=out) - else: - return self.interface.call('help', [self.handle], nargout=1, stdout=out) - - def __del__(self): - if self._is_thinwrapper: - try: - self.interface.call('evalin', ['base', f"clear('{self._objstr}')"], nargout=0) - except RuntimeError as err: - if not str(err).startswith('call() cannot be called after terminate()'): - raise - - def updateProxy(self): - """ - Perform a update on an objects fields. Useful for when dealing with handle classes. - :return: None - """ - # We assume methods can't change - for attribute in self._getAttributeNames(): - self.__dict__[attribute] = self.__getattr__(attribute) - - def updateObj(self): - """ - When you change an attributes value, the corresponding value should be changed in self.handle - :return: None - """ - raise NotImplementedError diff --git a/pace_neutrons/MatlabStruct.py b/pace_neutrons/MatlabStruct.py deleted file mode 100644 index d20cd69..0000000 --- a/pace_neutrons/MatlabStruct.py +++ /dev/null @@ -1,2 +0,0 @@ -class MatlabStruct(dict): - pass \ No newline at end of file diff --git a/pace_neutrons/TypeWrappers.py b/pace_neutrons/TypeWrappers.py deleted file mode 100644 index 27f952c..0000000 --- a/pace_neutrons/TypeWrappers.py +++ /dev/null @@ -1,67 +0,0 @@ -""" -Wrappers to avoid copying data between Matlab and Numpy, taken from: -https://stackoverflow.com/questions/10997254/converting-numpy-arrays-to-matlab-and-vice-versa -""" - -import numpy as np -import matlab -# This is actually `matlab._internal`, but matlab/__init__.py -# mangles the path making it appear as `_internal`. -# Importing it under a different name would be a bad idea. -from _internal.mlarray_utils import _get_strides, _get_mlsize - -def _wrapper__init__(self, arr): - assert arr.dtype == type(self)._numpy_type - self._python_type = type(arr.dtype.type().item()) - self._is_complex = np.issubdtype(arr.dtype, np.complexfloating) - self._size = _get_mlsize(arr.shape) - self._strides = _get_strides(self._size)[:-1] - self._start = 0 - - if self._is_complex: - self._real = arr.real.ravel(order='F') - self._imag = arr.imag.ravel(order='F') - else: - self._data = arr.ravel(order='F') - -_wrappers = {} -def _define_wrapper(matlab_type, numpy_type): - t = type(matlab_type.__name__, (matlab_type,), dict( - __init__=_wrapper__init__, - _numpy_type=numpy_type - )) - # this tricks matlab into accepting our new type - t.__module__ = matlab_type.__module__ - _wrappers[numpy_type] = t - -_define_wrapper(matlab.double, np.double) -_define_wrapper(matlab.single, np.single) -_define_wrapper(matlab.uint8, np.uint8) -_define_wrapper(matlab.int8, np.int8) -_define_wrapper(matlab.uint16, np.uint16) -_define_wrapper(matlab.int16, np.int16) -_define_wrapper(matlab.uint32, np.uint32) -_define_wrapper(matlab.int32, np.int32) -_define_wrapper(matlab.uint64, np.uint64) -_define_wrapper(matlab.int64, np.int64) -_define_wrapper(matlab.logical, np.bool_) -_define_wrapper(matlab.double, np.float64) -_define_wrapper(matlab.double, np.complex128) -_define_wrapper(matlab.single, np.float32) -_define_wrapper(matlab.single, np.complex64) - -def as_matlab(arr): - try: - cls = _wrappers[arr.dtype.type] - except KeyError: - raise TypeError("Unsupported data type") - return cls(arr) - -def as_numpy(arr): - if hasattr(arr, '_data'): - return np.ndarray(arr.size, dtype=arr._python_type, buffer=memoryview(arr._data), order='F') - else: # Probably complex matrix with real and imaginery parts in separate arrays - rp = np.ndarray(arr.size, dtype=arr._python_type, buffer=memoryview(arr._real), order='F') - ip = np.ndarray(arr.size, dtype=arr._python_type, buffer=memoryview(arr._imag), order='F') - return rp + 1j*ip # This is an implicit memory copy - diff --git a/pace_neutrons/__init__.py b/pace_neutrons/__init__.py deleted file mode 100644 index c90b1b7..0000000 --- a/pace_neutrons/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -from . import _version -__version__ = _version.get_versions()['version'] - -from .Matlab import Matlab -from .MatlabProxyObject import MatlabProxyObject -from .MatlabFunction import MatlabFunction diff --git a/pace_neutrons/funcinspect.py b/pace_neutrons/funcinspect.py deleted file mode 100644 index 4165367..0000000 --- a/pace_neutrons/funcinspect.py +++ /dev/null @@ -1,312 +0,0 @@ -# Mantid Repository : https://github.com/mantidproject/mantid -# -# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI, -# NScD Oak Ridge National Laboratory, European Spallation Source -# & Institut Laue - Langevin -# SPDX - License - Identifier: GPL - 3.0 + -""" - Defines functions that can be used to inspect the properties of a - function call. For example - - lhs_info() can be used to get retrieve the names and number of - arguments that are being assigned to a function - return -""" -from __future__ import (absolute_import, division, - print_function) -import opcode -import inspect -import sys -import dis -from six import PY3 - - -def replace_signature(func, signature): - """ - Replace the signature of the given function object with that given by - varnames - :param func: Function whose signature is to be replaced - :param signature: A tuple of names of arguments and local variables in Python 2 - or a Signature object in Python 3 - """ - if hasattr(signature, 'parameters'): - # A new Signature object - setattr(func, '__signature__', signature) - else: - # Drop this code when we dro Python 2 support - # Code object is different in Python 3 - if hasattr(func, 'func_code'): - # Version 2 - code_attr = 'func_code' - f = func.func_code - c = f.__new__(f.__class__, f.co_argcount, f.co_nlocals, f.co_stacksize, - f.co_flags, f.co_code, f.co_consts, f.co_names, - signature, f.co_filename, f.co_name, f.co_firstlineno, - f.co_lnotab, f.co_freevars) - else: - code_attr = '__code__' - f = func.__code__ - new_args = [f.__class__, f.co_argcount, f.co_kwonlyargcount, - f.co_nlocals, f.co_stacksize, f.co_flags, f.co_code, - f.co_consts, f.co_names, signature, - f.co_filename, f.co_name, f.co_firstlineno, - f.co_lnotab, f.co_freevars] - # Python 3.8 supports positional-only arguments and has an extra - # keyword in the constructor - if hasattr(f, 'co_posonlyargcount'): - new_args.insert(2, f.co_posonlyargcount) - c = f.__new__(*new_args) - #endif - setattr(func, code_attr, c) - - -def customise_func(func, name, signature, docstring): - """ - Takes the definition of the algorithm function and replaces - the attributes of the instance to make it look like a handwritten - function definition - :param func: A function object holding the definition - :param name: The name of the algorithm - :param signature: A new signature for the function. Expecting a 2-tuple - of arguments and local variables. See _replace_signature - :param docstring: A string containing the function documentation - """ - func.__name__ = str(name) - func.__doc__ = docstring - replace_signature(func, signature) - return func - -#------------------------------------------------------------------------------- -def decompile(code_object): - """ - Taken from - http://thermalnoise.wordpress.com/2007/12/30/exploring-python-bytecode/ - - Extracts dissasembly information from the byte code and stores it in - a list for further use. - - Call signature(s): - instructions=decompile(f.f_code) - - Required arguments: - ========= ===================================================================== - code_object A bytecode object extracted with inspect.currentframe() - or any other mechanism that returns byte code. - - Optional keyword arguments: NONE - - Outputs: - ========= ===================================================================== - instructions a list of offsets, op_codes, names, arguments, - argument_value which can be deconstructed to find out various things - about a function call. - - Example: - # Two frames back so that we get the callers' caller - f = inspect.currentframe().f_back.f_back - i = f.f_lasti # index of the last attempted instruction in byte code - ins = decompile(f.f_code) - """ - instructions = [] - - if PY3: - for ins in dis.get_instructions(code_object): - instructions.append( (ins.offset, ins.opcode, ins.opname, ins.arg, ins.argval) ) - else: - code = code_object.co_code - variables = code_object.co_cellvars + code_object.co_freevars - n = len(code) - i = 0 - e = 0 - while i < n: - i_offset = i - i_opcode = ord(code[i]) - i = i + 1 - if i_opcode >= opcode.HAVE_ARGUMENT: - i_argument = ord(code[i]) + (ord(code[i+1]) << (4*2)) + e - i = i + 2 - if i_opcode == opcode.EXTENDED_ARG: - e = i_argument << 16 - else: - e = 0 - if i_opcode in opcode.hasconst: - i_arg_value = repr(code_object.co_consts[i_argument]) - elif i_opcode in opcode.hasname: - i_arg_value = code_object.co_names[i_argument] - elif i_opcode in opcode.hasjrel: - i_arg_value = repr(i + i_argument) - elif i_opcode in opcode.haslocal: - i_arg_value = code_object.co_varnames[i_argument] - elif i_opcode in opcode.hascompare: - i_arg_value = opcode.cmp_op[i_argument] - elif i_opcode in opcode.hasfree: - i_arg_value = variables[i_argument] - else: - i_arg_value = i_argument - else: - i_argument = None - i_arg_value = None - instructions.append( (i_offset, i_opcode, opcode.opname[i_opcode], i_argument, i_arg_value) ) - return instructions - -#------------------------------------------------------------------------------- - -# A must list all of the operators that behave like a function calls in byte-code -# This is for the lhs functionality -__operator_names = set(['CALL_FUNCTION', 'CALL_FUNCTION_VAR', 'CALL_FUNCTION_KW', - 'CALL_FUNCTION_VAR_KW','UNARY_POSITIVE', - 'UNARY_NEGATIVE','UNARY_NOT', 'UNARY_CONVERT','UNARY_INVERT', - 'GET_ITER', 'BINARY_POWER', 'BINARY_MULTIPLY','BINARY_DIVIDE', - 'BINARY_FLOOR_DIVIDE', 'BINARY_TRUE_DIVIDE', 'BINARY_MODULO', - 'BINARY_ADD','BINARY_SUBTRACT', 'BINARY_SUBSCR','BINARY_LSHIFT', - 'BINARY_RSHIFT','BINARY_AND', 'BINARY_XOR','BINARY_OR', - 'INPLACE_POWER', 'INPLACE_MULTIPLY', 'INPLACE_DIVIDE', - 'INPLACE_TRUE_DIVIDE','INPLACE_FLOOR_DIVIDE', - 'INPLACE_MODULO', 'INPLACE_ADD', 'INPLACE_SUBTRACT', - 'INPLACE_LSHIFT','INPLACE_RSHIFT','INPLACE_AND', 'INPLACE_XOR', - 'INPLACE_OR', 'COMPARE_OP', - 'CALL_FUNCTION_EX', 'LOAD_METHOD', 'CALL_METHOD']) -#-------------------------------------------------------------------------------------- - -def process_frame(frame): - """Returns the number of arguments on the left of assignment along - with the names of the variables for the given frame. - - Call signature(s):: - - Required arguments: - =========================== ========== - frame The code frame to analyse - - Outputs: - ========= - Returns the a tuple with the number of arguments and their names - """ - # Index of the last attempted instruction in byte code - last_i = frame.f_lasti - ins_stack = decompile(frame.f_code) - - call_function_locs = {} - start_index = 0 - start_offset = 0 - - for index, instruction in enumerate(ins_stack): - (offset, op, name, argument, argvalue) = instruction - if name in __operator_names: - call_function_locs[start_offset] = (start_index, index) - start_index = index - start_offset = offset - - (offset, op, name, argument, argvalue) = ins_stack[-1] - # Append the index of the last entry to form the last boundary - call_function_locs[start_offset] = (start_index, len(ins_stack)-1) - - # last_i should be the offset of a call_function_locs instruction. - # We use this to bracket the bit which we are interested in. - # Bug: - # Some types of call, eg - # def foo(callableObj, *args, **kwargs): - # x = callableObj(*args, **kwargs) - # - # foo(FuncUsingLHS, 'Args') - # - # have the incorrect index at last_i due to the call being passed through - # an intermediate reference. Currently this method does not provide the - # correct answer and throws a KeyError. Ticket #4186 - output_var_names = [] - max_returns = [] - last_func_offset = call_function_locs[last_i][0] - (offset, op, name, argument, argvalue) = ins_stack[last_func_offset + 1] - if name == 'POP_TOP': # no return values - pass - if name == 'STORE_FAST' or name == 'STORE_NAME': # one return value - output_var_names.append(argvalue) - if name == 'UNPACK_SEQUENCE': # Many Return Values, One equal sign - for index in range(argvalue): - (offset_, op_, name_, argument_, argvalue_) = ins_stack[last_func_offset + 2 +index] - output_var_names.append(argvalue_) - max_returns = len(output_var_names) - if name == 'DUP_TOP': # Many Return Values, Many equal signs - # The output here should be a multi-dim list which mimics the variable unpacking sequence. - # For instance a,b=c,d=f() => [ ['a','b'] , ['c','d'] ] - # a,b=c=d=f() => [ ['a','b'] , 'c','d' ] So on and so forth. - - # put this in a loop and stack the results in an array. - count = 0 - max_returns = 0 # Must count the max_returns ourselves in this case - while count < len(ins_stack[call_function_locs[i][0]:call_function_locs[i][1]]): - (offset_, op_, name_, argument_, argvalue_) = ins[call_function_locs[i][0]+count] - if name_ == 'UNPACK_SEQUENCE': # Many Return Values, One equal sign - hold = [] - if argvalue_ > max_returns: - max_returns = argvalue_ - for index in range(argvalue_): - (_offset_, _op_, _name_, _argument_, _argvalue_) = ins[call_function_locs[i][0] + count+1+index] - hold.append(_argvalue_) - count = count + argvalue_ - output_var_names.append(hold) - # Need to now skip the entries we just appended with the for loop. - if name_ == 'STORE_FAST' or name_ == 'STORE_NAME': # One Return Value - if 1 > max_returns: - max_returns = 1 - output_var_names.append(argvalue_) - count = count + 1 - - return (max_returns, tuple(output_var_names)) - -#------------------------------------------------------------------------------- - -def lhs_info(output_type='both', frame=None): - """Returns the number of arguments on the left of assignment along - with the names of the variables. - - Acknowledgements: - Thanks to Tim Charlton and Jon Taylor of the ISIS facility for - figuring this out. - - Call signature(s):: - - Required arguments: NONE - - Optional keyword arguments Meaning: - =========================== ========== - output_type A string enumerating the type of output, one of - output_type = 'nreturns' : The number of return values - expected from the call - output_type = 'names' : Just return a list of - variable names - output_type = 'both' : A tuple containing both of - the above - frame A frame object that points to the frame containing a variable assignment. - Default = inspect.currentframe().f_back.f_back - - Outputs: - ========= - Depends on the value of the argument. See above. - - """ - if not frame: - try: - # Two frames back so that we get the callers' caller, i.e. this should only - # be called from within a function - frame = inspect.currentframe().f_back.f_back - except AttributeError: - raise RuntimeError("lhs_info cannot be used on the command line, only within a function") - - # Process the frame noting the advice here: - # http://docs.python.org/library/inspect.html#the-interpreter-stack - try: - ret_vals = process_frame(frame) - finally: - del frame - - if output_type == 'nreturns': - ret_vals = ret_vals[0] - elif output_type == 'names': - ret_vals = ret_vals[1] - else: - pass - - return ret_vals - -#------------------------------------------------------------------------------- diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ed52c34..efa32ed 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,18 +1,11 @@ -matlab_add_mex( +mcr_add_mex( NAME call_python - SRC call_python.cpp + SRC call_python.cpp type_converter.cpp load_matlab.cpp ) target_include_directories(call_python PUBLIC ${PYTHON_INCLUDE_DIRS}) target_include_directories(call_python PUBLIC "${pybind11_SOURCE_DIR}/include") - -matlab_add_mex( - NAME pythonRemoveFuncKey - SRC pythonRemoveFuncKey.cpp -) -target_include_directories(pythonRemoveFuncKey PUBLIC ${PYTHON_INCLUDE_DIRS}) -target_include_directories(pythonRemoveFuncKey PUBLIC "${pybind11_SOURCE_DIR}/include") -if(WIN32) - target_link_libraries(pythonRemoveFuncKey ${PYTHON_LIBRARIES}) +set_property(TARGET call_python PROPERTY LINK_LIBRARIES "") +if(NOT ${CMAKE_SYSTEM_NAME} STREQUAL "Linux") target_link_libraries(call_python ${PYTHON_LIBRARIES}) endif() @@ -44,29 +37,14 @@ endif() add_custom_command( TARGET compile_ctf PRE_BUILD COMMAND ${PYTHON_EXECUTABLE} "${CMAKE_MODULE_PATH}/patch_horace.py" "${CMAKE_CURRENT_SOURCE_DIR}/diffs" "${CMAKE_CURRENT_BINARY_DIR}/CTF" - COMMAND ${Matlab_MCC_COMPILER} -W python:pace -d "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/pace_neutrons" -v + COMMAND ${Matlab_MCC_COMPILER} -W ctf:pace_${Matlab_RELEASE} -U -d "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/pace_neutrons" -v -a "${CMAKE_CURRENT_BINARY_DIR}/CTF" -a "${CMAKE_CURRENT_SOURCE_DIR}/matlab_overrides" "${CMAKE_CURRENT_SOURCE_DIR}/call.m" - "${CMAKE_CURRENT_SOURCE_DIR}/call_method.m" - "${CMAKE_CURRENT_SOURCE_DIR}/thinwrapper.m" - "${CMAKE_CURRENT_SOURCE_DIR}/wrap_obj.m" - "${CMAKE_CURRENT_SOURCE_DIR}/has_thin_members.m" - "${CMAKE_CURRENT_SOURCE_DIR}/recfind.m" - "${CMAKE_CURRENT_SOURCE_DIR}/getArgOut.m" - "${CMAKE_CURRENT_SOURCE_DIR}/get_method_refs.m" - "${CMAKE_CURRENT_SOURCE_DIR}/get_global.m" - "${CMAKE_CURRENT_SOURCE_DIR}/set_global.m" - "${CMAKE_CURRENT_SOURCE_DIR}/waitforgui.m" - "${CMAKE_CURRENT_SOURCE_DIR}/pythonFunctionWrapper.m" - "${CMAKE_CURRENT_SOURCE_DIR}/call_python_m.m" - "${CMAKE_CURRENT_SOURCE_DIR}/pyclasswrapper.m" - "${CMAKE_CURRENT_SOURCE_DIR}/check_wrapped_function.m" "$/call_python.${Matlab_MEX_EXTENSION}" - "$/pythonRemoveFuncKey.${Matlab_MEX_EXTENSION}" "${CMAKE_CURRENT_SOURCE_DIR}/pyhorace_init.m" ) -add_dependencies(compile_ctf call_python pythonRemoveFuncKey) +add_dependencies(compile_ctf call_python) if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") pybind11_add_module(_stub _stub.cpp) diff --git a/src/call.m b/src/call.m index 2ccea73..c4eb16c 100644 --- a/src/call.m +++ b/src/call.m @@ -1,109 +1,171 @@ -function [out, varargout] = call(name, args) - -resultsize = nargout; -try - maxresultsize = nargout(name); - if maxresultsize == -1 +function [varargout] = call(name, varargin) + disp('[*] call.m: ') + disp(name) + disp(' ; ') + disp(evalc('disp(varargin)')) + if strcmp(name, 'set_fun') + disp(evalc('disp(varargin{3})')) + end + if strcmp(name, '_call_python') + varargout = call_python_m(varargin{:}); + return + end + resultsize = nargout; + try + maxresultsize = nargout(name); + if maxresultsize == -1 + maxresultsize = resultsize; + end + catch maxresultsize = resultsize; end -catch - maxresultsize = resultsize; -end -if resultsize > maxresultsize - resultsize = maxresultsize; -end -if nargin == 1 - args = {}; + if resultsize > maxresultsize + resultsize = maxresultsize; + end + if nargin == 1 + args = {}; + else + args = varargin; + end + for ir = 1:numel(args) + args{ir} = unwrap(args{ir}); + end + if resultsize > 0 + % call the function with the given number of + % output arguments: + varargout = cell(resultsize, 1); + try + [varargout{:}] = feval(name, args{:}); + catch err + if (strcmp(err.identifier,'MATLAB:unassignedOutputs')) + varargout = eval_ans(name, args); + else + rethrow(err); + end + end + else + varargout = eval_ans(name, args); + end + for ir = 1:numel(varargout) + varargout{ir} = wrap(varargout{ir}); + end end -% Checks if any arguments are thinwrappers - if they are, we have to -% to push all input variables into the global namespace and evaluate the function -% there rather than in this local namespace, because the real object behind the -% thinwrapper is only in the global namespace. -is_thin = false; -try - evalstr = sprintf('%s(', name); -catch - evalstr = []; -end -if numel(evalstr) > 0 - assargs = {}; - for ir = 1:numel(args) - if ir > 1; comma = ','; else comma = ''; end; - if strcmp(class(args{ir}), 'thinwrapper') - evalstr = sprintf('%s%s %s', evalstr, comma, args{ir}.ObjectString); - assargs{ir} = []; - is_thin = true; - else - args{ir} = check_wrapped_function(args{ir}); - evalstr = sprintf('%s%s arg%d', evalstr, comma, ir); - assargs{ir} = sprintf('arg%d', ir); +function out = unwrap(in_obj) + out = in_obj; + if isstruct(in_obj) && isfield(in_obj, 'libpymcr_func_ptr') + out = @(varargin) call('_call_python', [in_obj.libpymcr_func_ptr], varargin{:}); + elseif isa(in_obj, 'containers.Map') && in_obj.isKey('wrapped_oldstyle_class') + out = in_obj('wrapped_oldstyle_class'); + elseif iscell(in_obj) + for ii = 1:numel(in_obj) + out{ii} = unwrap(in_obj{ii}); end end end -if is_thin && (strcmp(name, 'class')) - is_thin = false; -end -if is_thin - for ir = 1:numel(args) - if ~isempty(assargs{ir}) - assignin('base', assargs{ir}, args{ir}); + +function out = wrap(obj) + out = obj; + if isobject(obj) && (isempty(metaclass(obj)) && ~isjava(obj)) || has_thin_members(obj) + out = containers.Map({'wrapped_oldstyle_class'}, {obj}); + elseif iscell(obj) + for ii = 1:numel(obj) + out{ii} = wrap(obj{ii}); end end - evalstr = [evalstr ')']; end -if resultsize > 0 - % call the function with the given number of - % output arguments: - results = cell(resultsize, 1); - try - if is_thin +function out = has_thin_members(obj) +% Checks whether any member of a class or struct is an old-style class +% or is already a wrapped instance of such a class + out = false; + if isobject(obj) || isstruct(obj) + try + fn = fieldnames(obj); + catch + return; + end + for ifn = 1:numel(fn) try - [results{:}] = evalin('base', evalstr); - catch err - %disp(err); - [results{:}] = feval(name, args{:}); + mem = subsref(obj, struct('type', '.', 'subs', fn{ifn})); + catch + continue; + end + if (isempty(metaclass(mem)) && ~isjava(mem)) + out = true; + break; end - else - [results{:}] = feval(name, args{:}); - end - catch err - if (strcmp(err.identifier,'MATLAB:unassignedOutputs')) - results = {[]}; - else - rethrow(err); - end - end - % Checks if any output is an old-style class, if so wrap it a new - % style class so it doesn't get converted to Python dict on return. - for ir = 1:numel(results) - if (isempty(metaclass(results{ir})) && ~isjava(results{ir})) || has_thin_members(results{ir}) - results{ir} = wrap_obj(results{ir}); end end - out = results{1}; - if length(results) > 1 - varargout = results(2:end); - end -else +end + +function results = eval_ans(name, args) % try to get output from ans: clear('ans'); - if is_thin - evalin('base', evalstr); + feval(name, args{:}); + try + results = {ans}; + catch err + results = {[]}; + end +end + +function [n, undetermined] = getArgOut(name, parent) + undertermined = false; + if isstring(name) + fun = str2func(name); try - results = evalin('base', 'ans'); - catch err - results = {[]}; + n = nargout(fun); + catch % nargout fails if fun is a method: + try + n = nargout(name); + catch + n = 0; + undetermined = true; + end end else - feval(name, args{:}); - try - results = {ans}; - catch err - results = {[]}; + n = 0; + undetermined = true; + end +end + +function out = call_python_m(varargin) + % Convert row vectors to column vectors for better conversion to numpy + for ii = 1:numel(varargin) + if size(varargin{ii}, 1) == 1 + varargin{ii} = varargin{ii}'; end end - out = results{1}; + fun_name = varargin{1}; + [kw_args, remaining_args] = get_kw_args(varargin(2:end)); + if ~isempty(kw_args) + remaining_args = [remaining_args {struct('pyHorace_pyKwArgs', 1, kw_args{:})}]; + end + out = call_python(fun_name, remaining_args{:}); + if ~iscell(out) + out = {out}; + end end + +function [kw_args, remaining_args] = get_kw_args(args) + % Finds the keyword arguments (string, val) pairs, assuming that they always at the end (last 2n items) + first_kwarg_id = numel(args) + 1; + for ii = (numel(args)-1):-2:1 + if ischar(args{ii}); args{ii} = string(args{ii}(:)'); end + if isstring(args{ii}) && ... + strcmp(regexp(args{ii}, '^[A-Za-z_][A-Za-z0-9_]*', 'match'), args{ii}) + % Python identifiers must start with a letter or _ and can contain charaters, numbers or _ + first_kwarg_id = ii; + else + break; + end + end + if first_kwarg_id < numel(args) + kw_args = args(first_kwarg_id:end); + remaining_args = args(1:(first_kwarg_id-1)); + else + kw_args = {}; + remaining_args = args; + end end diff --git a/src/call_method.m b/src/call_method.m deleted file mode 100644 index 36b41bf..0000000 --- a/src/call_method.m +++ /dev/null @@ -1,151 +0,0 @@ -function [out, varargout] = call_method(name, obj, args) - -resultsize = nargout; -try - maxresultsize = nargout(name); - if maxresultsize == -1 - maxresultsize = resultsize; - end -catch - maxresultsize = resultsize; -end -if resultsize > maxresultsize - resultsize = maxresultsize; -end -if nargin == 2 - args = {}; -end - -if isempty(obj) && (numel(args) > 0 && strcmp(class(args{1}), 'thinwrapper')) - obj = args{1}; - if numel(args) == 1 - args = {}; - else - args = args(2:end); - end -end - -% If the object or any arguments are a thinwrapper it means its an old-style class -% The wrapper is to basically put into the global Matlab namespace -% and to export only the variable name (as a string) to Python. -% So we have to push all input variables into the global namespace -% and evaluate the function there rather than in this local namespace. -is_thin = false; -try - evalstr = sprintf('%s(', name); -catch - evalstr = []; -end -if numel(evalstr) > 0 - assargs = {}; - assobj = false; - if ~isempty(obj) - if numel(args) > 0; comma = ','; else; comma = ''; end - if strcmp(class(obj), 'thinwrapper') - evalstr = sprintf('%s%s%s ', evalstr, obj.ObjectString, comma); - is_thin = true; - else - evalstr = sprintf('%s arg%d%s ', evalstr, 0, comma); - assobj = true; - end - end - for ir = 1:numel(args) - if ir > 1; comma = ','; else; comma = ''; end; - %disp(args{ir}) - if strcmp(class(args{ir}), 'thinwrapper') - evalstr = sprintf('%s%s %s', evalstr, comma, args{ir}.ObjectString); - assargs{ir} = []; - is_thin = true; - else - args{ir} = check_wrapped_function(args{ir}); - evalstr = sprintf('%s%s arg%d', evalstr, comma, ir); - assargs{ir} = sprintf('arg%d', ir); - end - end -end -if is_thin && (strcmp(name, 'class')) - is_thin = false; -end -if is_thin - for ir = 1:numel(args) - if ~isempty(assargs{ir}) - assignin('base', assargs{ir}, args{ir}); - end - end - if assobj - assignin('base', 'arg0', obj); - end - evalstr = [evalstr ')']; -end - -if resultsize > 0 - % call the function with the given number of - % output arguments: - results = cell(resultsize, 1); - has_failed = false; - if is_thin - try - [results{:}] = evalin('base', evalstr); - catch err - disp(err); - for ii = 1:numel(err.stack) - disp(err.stack(ii)); - end - has_failed = true; - end - end - if ~is_thin || has_failed - try - if isempty(obj) - [results{:}] = feval(name, args{:}); - else - [results{:}] = feval(name, obj, args{:}); - end - catch err - if (strcmp(err.identifier,'MATLAB:unassignedOutputs')) - results = {[]}; - else - rethrow(err); - end - end - end - % Checks if any output is an old-style class, if so wrap it a new - % style class so it doesn't get converted to Python dict on return. - for ir = 1:numel(results) - if (isempty(metaclass(results{ir})) && ~isjava(results{ir})) || has_thin_members(results{ir}) - results{ir} = wrap_obj(results{ir}); - end - end - out = results{1}; - if length(results) > 1 - varargout = results(2:end); - end -else - % try to get output from ans: - if is_thin - evalin('base', evalstr); - try - results = evalin('base', 'ans'); - catch err - results = {[]}; - end - else - clear('ans'); - if isempty(obj) - feval(name, args{:}); - else - feval(name, obj, args{:}); - end - try - results = {ans}; - catch err - results = {[]}; - end - end - out = results{1}; -end - -% Remove all non mapable reults -results = recfind(results); - -end diff --git a/src/call_python.cpp b/src/call_python.cpp index 5fdf712..6ff3f47 100644 --- a/src/call_python.cpp +++ b/src/call_python.cpp @@ -1,483 +1,80 @@ -#include "mex.hpp" -#include "mexAdapter.hpp" -#include "pybind11/pybind11.h" -#include "pybind11/numpy.h" -#include -#include -#include -#include -#include -#include - -#define MATLABERROR(errmsg) matlabPtr->feval(u"error", 0, std::vector({ factory.createScalar(errmsg) })); -#define MYINTEGER 1 -#define MYFLOAT 2 -#define MYCOMPLEX 4 -#define MYOTHER 8 +#include "matlab_mex.hpp" +#include "type_converter.hpp" using namespace matlab::data; using matlab::mex::ArgumentList; namespace py = pybind11; -// ------------------------------------------------------------------------------------------------------- -// Code to translate Matlab types to Python types -// ------------------------------------------------------------------------------------------------------- - -// Wraps a Matlab array in a numpy array without copying (should work with all numeric types) -template PyObject* matlab_to_python_t (const matlab::data::Array arr, py::handle owner) { - std::vector strides = {sizeof(T)}; - std::vector dims = arr.getDimensions(); - if (arr.getMemoryLayout() == matlab::data::MemoryLayout::COLUMN_MAJOR) { - for (size_t ii=0; ii<(dims.size()-1); ii++) { - strides.push_back(dims[ii] * strides[ii]); - } - } - else { - strides.resize(dims.size(), sizeof(T)); - for (size_t ii=dims.size()-2; ii>=0; ii--) { - strides[ii] = dims[ii+1] * strides[ii+1]; - } - } - // Needs to be const to avoid copying to a new (mutable) array - const matlab::data::TypedArray arr_t = matlab::data::TypedArray(arr); - // We need to pass a dummy python `base` object to own the reference otherwise PyBind will copy the data - // See: https://github.com/pybind/pybind11/issues/323 - const T &tmp = *arr_t.begin(); - py::array_t retval(dims, strides, (T*)(&tmp), owner); - PyObject* rv = retval.ptr(); - Py_INCREF(rv); - return rv; -} -// Specialisations for other types to generate the appropriate Python type -template <> PyObject* matlab_to_python_t(const matlab::data::Array input, py::handle owner) { - const matlab::data::TypedArray str(input); - return PyUnicode_FromKindAndData(2, (void*)(&(*str.begin())), str.getNumberOfElements()); -} -template <> PyObject* matlab_to_python_t>(const matlab::data::Array input, py::handle owner) { - const matlab::data::TypedArray str(input); - if (input.getNumberOfElements() == 1) { - const std::basic_string cstr(str[0]); - return PyUnicode_FromKindAndData(2, (void*)cstr.c_str(), cstr.size()); - } else { - PyObject* retval = PyList_New(0); - for (auto mstr: str) { - const std::basic_string cstr(mstr); - if (PyList_Append(retval, PyUnicode_FromKindAndData(2, (void*)cstr.c_str(), cstr.size()))) { - throw std::runtime_error("Error constructing python list from string array"); - } - } - return retval; - } -} -PyObject* matlab_to_python(const matlab::data::Array input, py::handle owner); -template <> PyObject* matlab_to_python_t(const matlab::data::Array input, py::handle owner) { - const matlab::data::StructArray in_struct(input); - if (input.getNumberOfElements() == 1) { - PyObject* retval = PyDict_New(); - for (auto ky : in_struct.getFieldNames()) { - PyObject* pyky = PyUnicode_FromString(std::string(ky).c_str()); - PyObject* pyval = matlab_to_python(in_struct[0][ky], owner); - if (PyDict_SetItem(retval, pyky, pyval)) { - throw std::runtime_error("Error constructing python dict from matlab struct"); - } - } - return retval; - } else { - PyObject* retval = PyList_New(0); - for (auto struc : in_struct) { - PyObject* elem = PyDict_New(); - for (auto ky : in_struct.getFieldNames()) { - PyObject* pyky = PyUnicode_FromString(std::string(ky).c_str()); - PyObject* pyval = matlab_to_python(struc[ky], owner); - if (PyDict_SetItem(elem, pyky, pyval)) { - throw std::runtime_error("Error constructing python dict from matlab struct"); - } - } - if (PyList_Append(retval, elem)) { - throw std::runtime_error("Error constructing python list from struct array"); - } - } - return retval; - } -} -template <> PyObject* matlab_to_python_t(const matlab::data::Array input, py::handle owner) { - const matlab::data::CellArray in_cell(input); - PyObject* retval = PyList_New(0); - for (auto elem : in_cell) { - PyObject *val = matlab_to_python(elem, owner); - if (PyList_Append(retval, val)) { - throw std::runtime_error("Error constructing python list from cell array"); - } - } - return retval; -} - -PyObject* matlab_to_python(const matlab::data::Array input, py::handle owner) { - matlab::data::ArrayType type = input.getType(); - switch(type) { - case matlab::data::ArrayType::DOUBLE: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::SINGLE: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::COMPLEX_SINGLE: return matlab_to_python_t>(input, owner); - case matlab::data::ArrayType::COMPLEX_DOUBLE: return matlab_to_python_t>(input, owner); - case matlab::data::ArrayType::LOGICAL: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::INT8: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::INT16: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::INT32: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::UINT8: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::UINT16: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::UINT32: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::CHAR: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::MATLAB_STRING: return matlab_to_python_t>(input, owner); - case matlab::data::ArrayType::STRUCT: return matlab_to_python_t(input, owner); - case matlab::data::ArrayType::CELL: return matlab_to_python_t(input, owner); - default: - throw std::runtime_error("Unrecognised input type"); - } -} - -py::tuple convMat2np(ArgumentList inputs, py::handle owner, size_t lastInd=-1) { - // Note that this function must be called when we have the GIL - size_t narg = inputs.size() + lastInd; - py::tuple retval(narg); - for (size_t idx = 1; idx <= narg; idx++) { - retval[idx - 1] = matlab_to_python(inputs[idx], owner); - } - return retval; -} - -// ------------------------------------------------------------------------------------------------------- -// Code to translate Python types to Matlab types -// ------------------------------------------------------------------------------------------------------- - -// Slower copy methods - follow data strides for non-contiguous arrays -template TypedArray raw_to_matlab(char *raw, size_t sz, std::vector dims, ssize_t *strides, matlab::data::ArrayFactory &factory) { - buffer_ptr_t buf = factory.createBuffer(sz); - T* ptr = buf.get(); - std::vector stride; - std::vector k = {dims[0]}; - for (size_t i=1; i -1) - stride.push_back(static_cast(strides[i])); - else - throw std::runtime_error("Invalid stride in numpy array"); - } - for (size_t i=0; i0; d--) { - vi = idx % k[d-1]; - offset += ((idx - vi) / k[d-1]) * stride[d]; - idx = vi; - } - offset += vi * stride[0]; - ptr[i] = *((T*)(raw + offset)); - } - return factory.createArrayFromBuffer(dims, std::move(buf), MemoryLayout::COLUMN_MAJOR); -} - -// Fast method block memory copy for contigous C- or Fortran-style arrays -template TypedArray raw_to_matlab_contiguous(T* begin, size_t sz, std::vector dims, bool f_contigous, matlab::data::ArrayFactory &factory) { - buffer_ptr_t buf = factory.createBuffer(sz); - memcpy(buf.get(), begin, sz * sizeof(T)); - if (f_contigous) { - return factory.createArrayFromBuffer(dims, std::move(buf), MemoryLayout::COLUMN_MAJOR); - } else { - return factory.createArrayFromBuffer(dims, std::move(buf), MemoryLayout::ROW_MAJOR); - } -} - -CellArray python_array_to_matlab(void *result, matlab::data::ArrayFactory &factory) { - // Cast the result to the PyArray C struct and its corresponding dtype struct - py::detail::PyArray_Proxy *arr = py::detail::array_proxy(result); - py::detail::PyArrayDescr_Proxy *dtype = py::detail::array_descriptor_proxy(arr->descr); - if (arr->nd == 0) { // 0-dimensional array - return a scalar - if (dtype->kind == 'f') { - if (dtype->elsize == sizeof(double)) return factory.createCellArray({1, 1}, factory.createScalar(*((double*)(arr->data)))); - else if (dtype->elsize == sizeof(float)) return factory.createCellArray({1, 1}, factory.createScalar(*((float*)(arr->data)))); - } else if (dtype->kind == 'c') { - if (dtype->elsize == sizeof(std::complex)) return factory.createCellArray({1, 1}, factory.createScalar(*((std::complex*)(arr->data)))); - else if (dtype->elsize == sizeof(std::complex)) return factory.createCellArray({1, 1}, factory.createScalar(*((std::complex*)(arr->data)))); - } - } - std::vector dims; - size_t numel = 1; - for (size_t id = 0; id < arr->nd; id++) { - dims.push_back(arr->dimensions[id]); - numel = numel * dims[id]; - } - int f_or_c_contiguous = 0; - if (py::detail::check_flags(result, py::detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_)) - f_or_c_contiguous = -1; - else if (py::detail::check_flags(result, py::detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_)) - f_or_c_contiguous = 1; - - char *begin = arr->data; - if (dtype->kind == 'f') { // Floating point array - if (dtype->elsize == sizeof(double)) { - if (f_or_c_contiguous) - return factory.createCellArray({1, 1}, raw_to_matlab_contiguous((double*)begin, numel, dims, f_or_c_contiguous==-1, factory)); - else - return factory.createCellArray({1, 1}, raw_to_matlab(begin, numel, dims, arr->strides, factory)); - } - else if(dtype->elsize == sizeof(float)) { - if (f_or_c_contiguous) - return factory.createCellArray({1, 1}, raw_to_matlab_contiguous((float*)begin, numel, dims, f_or_c_contiguous==-1, factory)); - else - return factory.createCellArray({1, 1}, raw_to_matlab(begin, numel, dims, arr->strides, factory)); - } - } - else if (dtype->kind == 'c') { // Complex array - if (dtype->elsize == sizeof(std::complex)) { - if (f_or_c_contiguous) - return factory.createCellArray({1, 1}, raw_to_matlab_contiguous((std::complex*)begin, numel, dims, f_or_c_contiguous==-1, factory)); - else - return factory.createCellArray({1, 1}, raw_to_matlab>(begin, numel, dims, arr->strides, factory)); - } - else if(dtype->elsize == sizeof(std::complex)) { - if (f_or_c_contiguous) - return factory.createCellArray({1, 1}, raw_to_matlab_contiguous((std::complex*)begin, numel, dims, f_or_c_contiguous==-1, factory)); - else - return factory.createCellArray({1, 1}, raw_to_matlab>(begin, numel, dims, arr->strides, factory)); - } - } - else - throw std::runtime_error("Python function returned a non-floating point array."); -} - -template T convert_py_obj (PyObject *obj) { - throw std::runtime_error("Unrecognised Python type"); } -template <> int64_t convert_py_obj (PyObject *obj) { - return PyLong_AsLong(obj); } -template <> double convert_py_obj (PyObject *obj) { - return PyFloat_AsDouble(obj); } -template <> std::complex convert_py_obj (PyObject *obj) { - return std::complex(PyComplex_RealAsDouble(obj), PyComplex_ImagAsDouble(obj)); } - -template CellArray fill_vec_from_pyobj(std::vector &objs, matlab::data::ArrayFactory &factory) { - std::vector vec; - vec.resize(objs.size()); - std::transform (objs.begin(), objs.end(), vec.begin(), convert_py_obj); - return factory.createCellArray({1, 1}, factory.createArray({1, vec.size()}, (T*)(&(*vec.begin())), (T*)(&(*vec.end())))); -} - -CharArray python_string_to_matlab(PyObject *result, matlab::data::ArrayFactory &factory) { - Py_ssize_t str_sz; - const char *str = PyUnicode_AsUTF8AndSize(result, &str_sz); - if (!str) { - PyErr_Print(); - throw std::runtime_error("Cannot create string from pyobject"); - } - return factory.createCharArray(std::string(str, str_sz)); -} - -CellArray listtuple_to_cell(PyObject *result, matlab::data::ArrayFactory &factory); -StructArray python_dict_to_matlab(PyObject *result, matlab::data::ArrayFactory &factory) { - Py_ssize_t pos = 0; - PyObject *key, *val; - std::vector keys; - std::vector vals; - while (PyDict_Next(result, &pos, &key, &val)) { - Py_ssize_t str_sz; - const char *str = PyUnicode_AsUTF8AndSize(key, &str_sz); - if (!str) { - throw std::runtime_error("Can only convert python dict with string keys to Matlab struct"); - } - keys.push_back(std::string(str, str_sz)); - vals.push_back(val); - } - StructArray retval = factory.createStructArray({1,1}, keys); - auto npy_api = py::detail::npy_api::get(); - for (size_t ii=0; ii({0}); - } else if (PyLong_Check(vals[ii])) { - retval[0][keys[ii]] = factory.createScalar(PyLong_AsLong(vals[ii])); - } else if (PyFloat_Check(vals[ii])) { - retval[0][keys[ii]] = factory.createScalar(PyFloat_AsDouble(vals[ii])); - } else if (PyComplex_Check(vals[ii])) { - retval[0][keys[ii]] = factory.createScalar(std::complex(PyComplex_RealAsDouble(vals[ii]), PyComplex_ImagAsDouble(vals[ii]))); - } else { - throw std::runtime_error("Unknown dict item type from Python function."); - } - } - return retval; -} - -CellArray listtuple_to_cell(PyObject *result, matlab::data::ArrayFactory &factory) { - size_t obj_size = PyTuple_Check(result) ? (size_t)PyTuple_Size(result) : (size_t)PyList_Size(result); - CellArray cell_out = factory.createCellArray({1, obj_size}); - auto npy_api = py::detail::npy_api::get(); - std::vector objs; - int typeflags = 0; - for(size_t ii=0; ii({0}); - typeflags |= MYOTHER; - } else if (PyLong_Check(item)) { - cell_out[0][ii] = factory.createScalar(PyLong_AsLong(item)); - typeflags |= MYINTEGER; - objs.push_back(item); - } else if (PyFloat_Check(item)) { - cell_out[0][ii] = factory.createScalar(PyFloat_AsDouble(item)); - typeflags |= MYFLOAT; - objs.push_back(item); - } else if (PyComplex_Check(item)) { - cell_out[0][ii] = factory.createScalar(std::complex(PyComplex_RealAsDouble(item), PyComplex_ImagAsDouble(item))); - typeflags |= MYCOMPLEX; - objs.push_back(item); - } else { - throw std::runtime_error("Unknown return type from Python function."); - } - } - if (typeflags == MYINTEGER) { - return fill_vec_from_pyobj(objs, factory); - } else if (typeflags == MYFLOAT) { - return fill_vec_from_pyobj(objs, factory); - } else if (typeflags == MYCOMPLEX) { - return fill_vec_from_pyobj>(objs, factory); - } else { - // We've got mixed or nonnumeric types - return a cell array of the elements - return cell_out; - } -} - // ------------------------------------------------------------------------------------------------------- // Mex class to run Python function referenced in a global dictionary // ------------------------------------------------------------------------------------------------------- class MexFunction : public matlab::mex::Function { + protected: + libpymcr::pymat_converter *_converter = nullptr; + py::tuple convMat2np(ArgumentList inputs, py::handle owner, size_t lastInd) { + // Note that this function must be called when we have the GIL + size_t narg = inputs.size() + lastInd; + py::tuple retval(narg); + for (size_t idx = 1; idx <= narg; idx++) { + retval[idx - 1] = _converter->to_python(inputs[idx]); + } + return retval; + } + public: void operator()(ArgumentList outputs, ArgumentList inputs) { - std::shared_ptr matlabPtr = getEngine(); matlab::data::ArrayFactory factory; - if (inputs.size() < 1 || - inputs[0].getType() != matlab::data::ArrayType::CHAR) { - MATLABERROR("First input must a string key to a Python function."); + if (inputs.size() < 1 || inputs[0].getNumberOfElements() != 1 || + inputs[0].getType() != matlab::data::ArrayType::UINT64) { // Matlab only supports 64-bit + throw std::runtime_error("Input must be pointer to a Python function."); } - matlab::data::CharArray key = inputs[0]; + uintptr_t key = inputs[0][0]; PyGILState_STATE gstate = PyGILState_Ensure(); // GIL{ - if (!Py_IsInitialized()) - throw std::runtime_error("Python not initialized."); - - // Imports the wrapper module and check its global dictionary for the function we want - py::module pyHoraceFn; - try { - pyHoraceFn = py::module::import("pace_neutrons.FunctionWrapper"); - } - catch (...) { - PyGILState_Release(gstate); - MATLABERROR("Cannot import Python pace_neutrons module.") - } - py::dict fnDict = pyHoraceFn.attr("_globalFunctionDict"); - // PyBind11 does not have bindings for the C API PyDict_GetItem* methods - PyObject *fnItem = PyDict_GetItemString(fnDict.ptr(), key.toAscii().c_str()); - if (fnItem == NULL) { - PyGILState_Release(gstate); - MATLABERROR("Unknown python function key."); + if (_converter == nullptr) { + _converter = new libpymcr::pymat_converter(); } - // The remainder of this code is an unholy mess of Python C API calls and undocumented internals of PyBind11 - // (not that PyBind is super well documented!) and should be considered _unsafe_ - // It should be refactored to use PyBind properly (perhaps after patching the PyBind headers with PyDict_GetItem*) + PyObject* fn_ptr = reinterpret_cast(key); - if (PyCallable_Check(fnItem)) { + if (PyCallable_Check(fn_ptr)) { PyObject *result; size_t endIdx = inputs.size() - 1; try { try { const matlab::data::StructArray in_struct(inputs[endIdx]); const matlab::data::Array v = in_struct[0][matlab::data::MATLABFieldIdentifier("pyHorace_pyKwArgs")]; - PyObject *kwargs = matlab_to_python(inputs[endIdx], fnItem); + PyObject *kwargs = _converter->to_python(inputs[endIdx]); PyDict_DelItemString(kwargs, "pyHorace_pyKwArgs"); - py::tuple arr_in = convMat2np(inputs, fnItem, -2); - result = PyObject_Call(fnItem, arr_in.ptr(), kwargs); + py::tuple arr_in = convMat2np(inputs, fn_ptr, -2); + result = PyObject_Call(fn_ptr, arr_in.ptr(), kwargs); } catch (...) { - py::tuple arr_in = convMat2np(inputs, fnItem); - result = PyObject_CallObject(fnItem, arr_in.ptr()); + py::tuple arr_in = convMat2np(inputs, fn_ptr, -1); + result = PyObject_CallObject(fn_ptr, arr_in.ptr()); } - } catch (char *e) { + } catch (...) { } if (result == NULL) { PyErr_Print(); PyGILState_Release(gstate); - MATLABERROR("Python function threw an error."); + throw std::runtime_error("Python function threw an error."); } else { - auto npy_api = py::detail::npy_api::get(); - bool is_arr = npy_api.PyArray_Check_(result); - if (is_arr) { - try { - outputs[0] = python_array_to_matlab((void*)result, factory); - } catch (char *e) { - Py_DECREF(result); - PyGILState_Release(gstate); - MATLABERROR(e); - } - } - else if(PyTuple_Check(result) || PyList_Check(result)) { - try { - outputs[0] = listtuple_to_cell(result, factory); - } catch (char *e) { - Py_DECREF(result); - PyGILState_Release(gstate); - MATLABERROR(e); - } - } - else if (PyUnicode_Check(result)) { - try { - outputs[0] = python_string_to_matlab(result, factory); - } catch (char *e) { - Py_DECREF(result); - PyGILState_Release(gstate); - MATLABERROR(e); - } - } - else if (PyDict_Check(result)) { - try { - outputs[0] = python_dict_to_matlab(result, factory); - } catch (char *e) { - Py_DECREF(result); - PyGILState_Release(gstate); - MATLABERROR(e); - } - } - else if (result != Py_None) { + try { + outputs[0] = _converter->to_matlab(result, Py_REFCNT(result)==1); + } catch (char *e) { Py_DECREF(result); PyGILState_Release(gstate); - MATLABERROR("Unknown return type from Python function."); + throw std::runtime_error(e); } Py_DECREF(result); } } else { PyGILState_Release(gstate); - MATLABERROR("Python function is not callable."); + throw std::runtime_error("Python function is not callable."); } PyGILState_Release(gstate); // GIL} diff --git a/src/call_python_m.m b/src/call_python_m.m deleted file mode 100644 index dd870ef..0000000 --- a/src/call_python_m.m +++ /dev/null @@ -1,70 +0,0 @@ -function varargout = call_function_m(varargin) - % Convert row vectors to column vectors for better conversion to numpy - for ii = 1:numel(varargin) - if size(varargin{ii}, 1) == 1 - varargin{ii} = varargin{ii}'; - end - end - fun_name = varargin{1}; - if strncmp(varargin{2}, 'pyobj', 5) - [kw_args, remaining_args] = get_kw_args(varargin(3:end)); - remaining_args = [varargin(2) remaining_args]; - else - [kw_args, remaining_args] = get_kw_args(varargin(2:end)); - end - kw_args = unwrap_pyclass(kw_args); - remaining_args = unwrap_pyclass(remaining_args); - kw_struct = struct('pyHorace_pyKwArgs', 1, kw_args{:}); - varargout = call_python(fun_name, remaining_args{:}, kw_struct); - varargout = unwrap_single(varargout); - if ~iscell(varargout) - varargout = {varargout}; - end -end - -function input = unwrap_single(input) - if iscell(input) - if numel(input) == 1 - input = input{1}; - else - for ii = 1:numel(input) - input{ii} = unwrap_single(input{ii}); - end - end - end -end - -function input = unwrap_pyclass(input) - if iscell(input) - for ii = 1:numel(input) - input{ii} = unwrap_pyclass(input{ii}); - end - else - if isa(input, 'pyclasswrapper') - input = input.pyObjectString; - end - end -end - -function [kw_args, remaining_args] = get_kw_args(args) - % Finds the keyword arguments (string, val) pairs, assuming that they always at the end (last 2n items) - first_kwarg_id = numel(args) + 1; - for ii = (numel(args)-1):-2:1 - if ischar(args{ii}); args{ii} = string(args{ii}(:)'); end - if isstring(args{ii}) && ... - strcmp(regexp(args{ii}, '^[A-Za-z_][A-Za-z0-9_]*', 'match'), args{ii}) - % Python identifiers must start with a letter or _ and can contain charaters, numbers or _ - first_kwarg_id = ii; - else - break; - end - end - if first_kwarg_id < numel(args) - kw_args = args(first_kwarg_id:end); - remaining_args = args(1:(first_kwarg_id-1)); - else - kw_args = {}; - remaining_args = args; - end -end - diff --git a/src/check_wrapped_function.m b/src/check_wrapped_function.m deleted file mode 100644 index c9bc619..0000000 --- a/src/check_wrapped_function.m +++ /dev/null @@ -1,12 +0,0 @@ -function out = check_wrapped_function(in_obj) - out = in_obj; - if strcmp(class(in_obj), 'pythonFunctionWrapper') - out = @(varargin) call_python_m(in_obj.func_uuid, varargin{:}); - elseif iscell(in_obj) - for ii = 1:numel(in_obj) - if strcmp(class(in_obj{ii}), 'pythonFunctionWrapper') - out{ii} = @(varargin) call_python_m(in_obj{ii}.func_uuid, varargin{:}); - end - end - end -end diff --git a/src/getArgOut.m b/src/getArgOut.m deleted file mode 100644 index 8d36b12..0000000 --- a/src/getArgOut.m +++ /dev/null @@ -1,21 +0,0 @@ -function [n, undetermined] = getArgOut(name, parent) - -undertermined = false; -if isstring(name) - fun = str2func(name); - try - n = nargout(fun); - catch % nargout fails if fun is a method: - try - n = nargout(name); - catch - n = 1; - undetermined = true; - end - end -else - n = 1; - undetermined = true; -end - -end diff --git a/src/get_global.m b/src/get_global.m deleted file mode 100644 index d02e161..0000000 --- a/src/get_global.m +++ /dev/null @@ -1,11 +0,0 @@ -function value = get_global(name) -existance = evalin('base', ['exist(''' name ''')']); -% exist doesn't find methods, though. -existance = existance | any(which(name)); -% value does not exist: -if ~existance - error('pyMATLAB:novariable' , ['Undefined variable ''' name '''.']); -else - value = evalin('base', name); -end -end \ No newline at end of file diff --git a/src/get_method_refs.m b/src/get_method_refs.m deleted file mode 100644 index 0b5e1ef..0000000 --- a/src/get_method_refs.m +++ /dev/null @@ -1,15 +0,0 @@ -function out = get_method_refs(name, parent) -% Gets a reference ("function handle") to a method of a class -% Note that if the class method shadows a Matlab function name -% (e.g. swpref.getpref) the built-in will take precedent unfortunately - if ~isstring(name) && ~ischar(name) - error('Method name must be string') - end - if nargin < 2 - out = str2func(name); - else - evalstr = ['@(par, varargin) ' name '(par, varargin{:})']; - fn0 = eval(evalstr); - out = @(varargin) fn0(parent, varargin{:}); - end -end diff --git a/src/has_thin_members.m b/src/has_thin_members.m deleted file mode 100644 index d75212f..0000000 --- a/src/has_thin_members.m +++ /dev/null @@ -1,24 +0,0 @@ -function out = has_thin_members(obj) -% Checks whether any member of a class or struct is an old-style class -% or is already a wrapped instance of such a class - out = false; - if isobject(obj) || isstruct(obj) - try - fn = fieldnames(obj); - catch - return; - end - for ifn = 1:numel(fn) - try - mem = subsref(obj, struct('type', '.', 'subs', fn{ifn})); - catch - continue; - end - if strcmp(class(mem), 'thinwrapper') || ... - (isempty(metaclass(mem)) && ~isjava(mem)) - out = true; - break; - end - end - end -end diff --git a/src/load_matlab.cpp b/src/load_matlab.cpp new file mode 100644 index 0000000..165b8e7 --- /dev/null +++ b/src/load_matlab.cpp @@ -0,0 +1,113 @@ +#include "load_matlab.hpp" + +// Global declaration of libraries +void *_LIBDATAARRAY, *_LIBMEX, *_LIBCPPSHARED; +std::string _MLVERSTR; + +void *_loadlib(std::string path, const char* libname, std::string mlver) { +#if defined _WIN32 + void* lib = (void*)LoadLibrary((path + "/win64/" + libname + mlver + ".dll").c_str()); +#else + if (mlver.length() > 0) + mlver = "." + mlver; +#if defined __APPLE__ + void* lib = dlopen((path + "/maci64/" + libname + mlver + ".dylib").c_str(), RTLD_LAZY); +#else + void* lib = dlopen((path + "/glnxa64/" + libname + ".so" + mlver).c_str(), RTLD_LAZY); +#endif +#endif + if (!lib) { + throw std::runtime_error(std::string("Cannot load ") + libname); + } + return lib; +} +void *_resolve(void* lib, const char* sym) { +#ifdef _WIN32 + return (void*)GetProcAddress((HMODULE)lib, sym); +#else + return dlsym(lib, sym); +#endif +} +std::string _getMLversion(std::string mlroot) { + if (_MLVERSTR.length()==0) { + std::ifstream verfile(mlroot + "/VersionInfo.xml", std::ifstream::in); + std::ostringstream verstr; + verstr << verfile.rdbuf(); + std::string vs = verstr.str(); + vs.replace(0, vs.find("version>")+8, ""); + vs.replace(vs.find(".", 3), vs.length(), ""); +#ifdef _WIN32 + vs.replace(vs.find("."), 1, "_"); +#endif + _MLVERSTR = vs; + } + return _MLVERSTR; +} +void _loadlibraries(std::string matlabroot) { + if (!_LIBCPPSHARED) { + _LIBDATAARRAY = _loadlib(matlabroot + "/extern/bin/", "libMatlabDataArray"); + _LIBCPPSHARED = _loadlib(matlabroot + "/runtime/", "libMatlabCppSharedLib", _getMLversion(matlabroot)); + _LIBMEX = _loadlib(matlabroot + "/bin/", "libmex"); + } +} +void _checklibs() { + if (!_LIBDATAARRAY || !_LIBCPPSHARED || !_LIBMEX) { + throw std::runtime_error("Matlab libraries must be initialised first."); + } +} +// Utils +void util_destroy_utf8(char* utf8) { _checklibs(); return ((void(*)(char*))_resolve(_LIBCPPSHARED, "util_destroy_utf8"))(utf8); } +void util_destroy_utf16(char16_t* utf16) { _checklibs(); return ((void(*)(char16_t*))_resolve(_LIBCPPSHARED, "util_destroy_utf16"))(utf16); } +void util_utf8_to_utf16(const char* utf8, char16_t** utf16, size_t* errType) { + _checklibs(); return ((void(*)(const char*, char16_t**, size_t*))_resolve(_LIBCPPSHARED, "util_utf8_to_utf16"))(utf8, utf16, errType); } +void util_utf16_to_utf8(const char16_t* utf16, char** utf8, size_t* errType) { + _checklibs(); return ((void(*)(const char16_t*, char**, size_t*))_resolve(_LIBCPPSHARED, "util_utf16_to_utf8"))(utf16, utf8, errType); } +// CPP_SHARED_LIB +void runtime_create_session(char16_t** options, size_t size) { + _checklibs(); return ((void(*)(char16_t**, size_t))_resolve(_LIBCPPSHARED, "runtime_create_session"))(options, size); } +void runtime_terminate_session() { _checklibs(); return ((void(*)())_resolve(_LIBCPPSHARED, "runtime_terminate_session"))(); } +uint64_t create_mvm_instance_async(const char16_t* name) { + _checklibs(); return ((uint64_t(*)(const char16_t*))_resolve(_LIBCPPSHARED, "create_mvm_instance_async"))(name); } +uint64_t create_mvm_instance(const char16_t* name, bool* errFlag) { + _checklibs(); return ((uint64_t(*)(const char16_t*, bool*))_resolve(_LIBCPPSHARED, "create_mvm_instance"))(name, errFlag); } +void terminate_mvm_instance(const uint64_t mvmHandle) { + _checklibs(); return ((void(*)(const uint64_t))_resolve(_LIBCPPSHARED, "terminate_mvm_instance"))(mvmHandle); } +void wait_for_figures_to_close(const uint64_t mvmHandle) { + _checklibs(); return ((void(*)(const uint64_t))_resolve(_LIBCPPSHARED, "wait_for_figures_to_close"))(mvmHandle); } +void cppsharedlib_destroy_handles(uintptr_t* handles) { + _checklibs(); return ((void(*)(uintptr_t*))_resolve(_LIBCPPSHARED, "cppsharedlib_destroy_handles"))(handles); } +uintptr_t cppsharedlib_feval_with_completion(const uint64_t matlabHandle, const char* function, size_t nlhs, bool scalar, + matlab::data::impl::ArrayImpl** args, size_t nrhs, + void(*success)(void*, size_t, bool, matlab::data::impl::ArrayImpl**), + void(*exception)(void*, size_t, bool, size_t, const void*), + void* p, void* output, void* error, void(*write)(void*, const char16_t*, size_t), + void(*deleter)(void*)) { + _checklibs(); + return ((uintptr_t(*)(const uint64_t, const char*, size_t, bool, matlab::data::impl::ArrayImpl**, size_t, + void(*)(void*, size_t, bool, matlab::data::impl::ArrayImpl**), + void(*)(void*, size_t, bool, size_t, const void*), void*, void*, void*, + void(*)(void*, const char16_t*, size_t), void(*)(void*)))_resolve(_LIBCPPSHARED, "cppsharedlib_feval_with_completion")) + (matlabHandle, function, nlhs, scalar, args, nrhs, success, exception, p, output, error, write, deleter); +} +bool cppsharedlib_cancel_feval_with_completion(uintptr_t taskHandle, bool allowInteruption) { + _checklibs(); return ((bool(*)(uintptr_t, bool))_resolve(_LIBCPPSHARED, "cppsharedlib_cancel_feval_with_completion"))(taskHandle, allowInteruption); } +void cppsharedlib_destroy_task_handle(uintptr_t taskHandle) { + _checklibs(); return ((void(*)(uintptr_t))_resolve(_LIBCPPSHARED, "cppsharedlib_destroy_task_handle"))(taskHandle); } +size_t cppsharedlib_get_stacktrace_number(const uintptr_t frameHandle) { + _checklibs(); return ((size_t(*)(const uintptr_t))_resolve(_LIBCPPSHARED, "cppsharedlib_get_stacktrace_number"))(frameHandle); } +const char* cppsharedlib_get_stacktrace_message(const uintptr_t frameHandle) { + _checklibs(); return ((const char*(*)(const uintptr_t))_resolve(_LIBCPPSHARED, "cppsharedlib_get_stacktrace_message"))(frameHandle); } +const char16_t* cppsharedlib_get_stackframe_file(const uintptr_t frameHandle, size_t frameNumber) { + _checklibs(); return ((const char16_t*(*)(const uintptr_t, size_t))_resolve(_LIBCPPSHARED, "cppsharedlib_get_stackframe_file"))(frameHandle, frameNumber); } +const char* cppsharedlib_get_stackframe_func(const uintptr_t frameHandle, size_t frameNumber) { + _checklibs(); return ((const char*(*)(const uintptr_t, size_t))_resolve(_LIBCPPSHARED, "cppsharedlib_get_stackframe_func"))(frameHandle, frameNumber); } +uint64_t cppsharedlib_get_stackframe_line(const uintptr_t frameHandle, size_t frameNumber) { + _checklibs(); return ((uint64_t(*)(const uintptr_t, size_t))_resolve(_LIBCPPSHARED, "cppsharedlib_get_stackframe_line"))(frameHandle, frameNumber); } +int cppsharedlib_run_main(int(*mainfcn)(int, const char**), int argc, const char** argv) { + _checklibs(); return ((int(*)(int(*)(int, const char**), int, const char**))_resolve(_LIBCPPSHARED, "cppsharedlib_run_main"))(mainfcn, argc, argv); } +// DATA_ARRAY +void* get_function_ptr(int fcn) { _checklibs(); return ((void*(*)(int))_resolve(_LIBDATAARRAY, "get_function_ptr"))(fcn); } +// MEX +void* mexGetFunctionImpl() { _checklibs(); return ((void*(*)())_resolve(_LIBMEX, "mexGetFunctionImpl"))(); } +void mexDestroyFunctionImpl(void* impl) { _checklibs(); return ((void(*)(void*))_resolve(_LIBMEX, "mexDestroyFunctionImpl"))(impl); } + diff --git a/src/load_matlab.hpp b/src/load_matlab.hpp new file mode 100644 index 0000000..40c8465 --- /dev/null +++ b/src/load_matlab.hpp @@ -0,0 +1,31 @@ +#ifndef LOAD_MATLAB_HPP +#define LOAD_MATLAB_HPP + +#ifdef _WIN32 +#ifndef __wtypes_h__ +#include +#endif +#ifndef __WINDEF_ +#include +#endif +#endif + +// Imported Matlab functions +#ifdef _WIN32 +#include +#else +#include +#endif + +#include "type_converter.hpp" +#include + +void *_loadlib(std::string path, const char* libname, std::string mlver=""); +void *_resolve(void* lib, const char* sym); +std::string _getMLversion(std::string mlroot); +void _loadlibraries(std::string matlabroot); + +void* mexGetFunctionImpl(); +void mexDestroyFunctionImpl(void* impl); + +#endif diff --git a/src/matlab.cmake b/src/matlab.cmake new file mode 100644 index 0000000..00d22bc --- /dev/null +++ b/src/matlab.cmake @@ -0,0 +1,171 @@ +# You can set a specific Matlab version folder here +#set(Matlab_ROOT_DIR "d:/MATLAB/Matlab Runtime/v910") +#set(MATLAB_FIND_DEBUG 1) +find_package(Matlab) + +if (NOT Matlab_INCLUDE_DIRS) + # Could not find (or completely find) MATLAB or MCR + if (Matlab_ROOT_DIR) + file(GLOB_RECURSE _mlarrayhpp_tmp "${Matlab_ROOT_DIR}/*MatlabDataArray.hpp") + if (_mlarrayhpp_tmp) + get_filename_component(Matlab_DATAARRAY_INCLUDE "${_mlarrayhpp_tmp}" REALPATH) + get_filename_component(Matlab_INCLUDE_DIRS "${Matlab_DATAARRAY_INCLUDE}" DIRECTORY) + # Set root dir to be two up from this (should be /extern/include) + get_filename_component(Matlab_ROOT_DIR "${Matlab_INCLUDE_DIRS}" DIRECTORY) + get_filename_component(Matlab_ROOT_DIR "${Matlab_ROOT_DIR}" DIRECTORY) + else() + message(FATAL_ERROR "MATLAB/MCR not found, cannot compile libpymcr.") + endif() + else() + message(FATAL_ERROR "MATLAB/MCR not found, cannot compile libpymcr.") + endif() +endif() + +message(STATUS "Matlab_ROOT_DIR=${Matlab_ROOT_DIR}") +message(STATUS "Matlab_INCLUDE_DIRS=${Matlab_INCLUDE_DIRS}") + +# On MacOS github runners it can sometimes fail to find the right libraries +if (NOT Matlab_HAS_CPP_API) + if (NOT Matlab_ENGINE_LIBRARY) + file(GLOB_RECURSE Matlab_ENGINE_LIBRARY "${Matlab_ROOT_DIR}/extern/bin/*/libMatlabEngine*") + endif() + if (NOT Matlab_DATAARRAY_LIBRARY) + file(GLOB_RECURSE Matlab_DATAARRAY_LIBRARY "${Matlab_ROOT_DIR}/extern/bin/*/libMatlabDataArray*") + endif() + if (Matlab_ENGINE_LIBRARY AND Matlab_DATAARRAY_LIBRARY) + set(Matlab_HAS_CPP_API 1) + list(APPEND Matlab_LIBRARIES ${Matlab_ENGINE_LIBRARY}) + list(APPEND Matlab_LIBRARIES ${Matlab_DATAARRAY_LIBRARY}) + endif() +endif() + +# Gets the version string from the xml file if it is not defined +if (NOT Matlab_VERSION_STRING OR Matlab_VERSION_STRING STREQUAL "unknown") + if(EXISTS "${Matlab_ROOT_DIR}/VersionInfo.xml") + file(STRINGS "${Matlab_ROOT_DIR}/VersionInfo.xml" versioninfo_string NEWLINE_CONSUME) + if(versioninfo_string) + string(REGEX MATCH "(.*)" + version_reg_match + ${versioninfo_string}) + if(CMAKE_MATCH_1 MATCHES "(([0-9]+)\\.([0-9]+))[\\.0-9]*") + set(Matlab_VERSION_STRING "${CMAKE_MATCH_1}") + message(STATUS "Matlab_VERSION_STRING = ${Matlab_VERSION_STRING}") + endif() + endif() + endif() +endif() + +# # Prints all variables +# get_cmake_property(_variableNames VARIABLES) +# list (SORT _variableNames) +# foreach (_variableName ${_variableNames}) +# message(STATUS "${_variableName}=${${_variableName}}") +# endforeach() + +# Define our own version of matlab_add_mex in order to not link libraries +# and avoid all but the Matlab_INCLUDE_DIRS variables. +# Does not support the MODULE or EXECUTABLE modes (just SHARED) +# Does not support the DOCUMENTATION option +# Forces extensions to be .mexw64, .mexa64 or .mexmaci64 depending on OS +# Forces the option NO_IMPLICIT_LINK_TO_MATLAB_LIBRARIES and ignores LINK_TO +# Forces R2018a mode (so does not support older versions of MATLAB) +# (this is opposite to the default behaviour of matlab_add_mex) +function(mcr_add_mex) + if(Matlab_VERSION_STRING VERSION_LESS "9.4") + message(FATAL_ERROR "[mcr_add_mex] Only Matlab newer than R2018a supported") + endif() + if(NOT WIN32) + if(CMAKE_CXX_COMPILER_LOADED) + check_cxx_compiler_flag(-pthread HAS_MINUS_PTHREAD) + elseif(CMAKE_C_COMPILER_LOADED) + check_c_compiler_flag(-pthread HAS_MINUS_PTHREAD) + endif() + if (APPLE) + set(Matlab_MEX_EXTENSION mexmaci64) + set(Matlab_ARCH maci64) + else() + set(Matlab_MEX_EXTENSION mexa64) + set(Matlab_ARCH glnxa64) + endif() + else() + set(Matlab_MEX_EXTENSION mexw64) + set(Matlab_ARCH win64) + endif() + set(options EXCLUDE_FROM_ALL) + set(oneValueArgs NAME OUTPUT_NAME) + set(multiValueArgs SRC) + set(prefix _matlab_addmex_prefix) + cmake_parse_arguments(${prefix} "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN} ) + if(NOT ${prefix}_NAME) + message(FATAL_ERROR "[MATLAB] The MEX target name cannot be empty") + endif() + if(NOT ${prefix}_OUTPUT_NAME) + set(${prefix}_OUTPUT_NAME ${${prefix}_NAME}) + endif() + set(MEX_API_MACRO "MATLAB_DEFAULT_RELEASE=R2018a") + if (NOT Matlab_EXTERN_LIBRARY_DIR) + set(Matlab_EXTERN_LIBRARY_DIR ${Matlab_ROOT_DIR}/extern/lib/${Matlab_ARCH}) + endif() + if(CMAKE_C_COMPILER_LOADED) + set(MEX_VERSION_FILE "${Matlab_ROOT_DIR}/extern/version/c_mexapi_version.c") + elseif(CMAKE_CXX_COMPILER_LOADED) + set(MEX_VERSION_FILE "${Matlab_ROOT_DIR}/extern/version/cpp_mexapi_version.cpp") + else() + message(WARNING "[MATLAB] matlab_add_mex requires that at least C or CXX are enabled languages") + endif() + set(_option_EXCLUDE_FROM_ALL) + if(${prefix}_EXCLUDE_FROM_ALL) + set(_option_EXCLUDE_FROM_ALL "EXCLUDE_FROM_ALL") + endif() + add_library(${${prefix}_NAME} + SHARED + ${_option_EXCLUDE_FROM_ALL} + ${${prefix}_SRC} + #${MEX_VERSION_FILE} + ${${prefix}_UNPARSED_ARGUMENTS}) + target_include_directories(${${prefix}_NAME} SYSTEM PRIVATE ${Matlab_INCLUDE_DIRS}) + set_target_properties(${${prefix}_NAME} + PROPERTIES + PREFIX "" + OUTPUT_NAME ${${prefix}_OUTPUT_NAME} + SUFFIX ".${Matlab_MEX_EXTENSION}") + target_compile_definitions(${${prefix}_NAME} PRIVATE ${MEX_API_MACRO} MATLAB_MEX_FILE) + + # entry point in the mex file + taking care of visibility and symbol clashes. + if(WIN32) + if (MSVC) + set(_link_flags "${_link_flags} /EXPORT:mexFunction") + #set(_link_flags "${_link_flags} /EXPORT:mexfilerequiredapiversion") + set_property(TARGET ${${prefix}_NAME} APPEND PROPERTY LINK_FLAGS ${_link_flags}) + endif() # No other compiler currently supported on Windows. + set_target_properties(${${prefix}_NAME} + PROPERTIES + DEFINE_SYMBOL "DLL_EXPORT_SYM=__declspec(dllexport)") + else() + #set(_ver_map_files ${Matlab_EXTERN_LIBRARY_DIR}/c_exportsmexfileversion.map) + if(NOT Matlab_VERSION_STRING VERSION_LESS "9.5") # For 9.5 (R2018b) (and newer?) + target_compile_options(${${prefix}_NAME} PRIVATE "-fvisibility=default") + endif() + if(APPLE) + if(Matlab_HAS_CPP_API) + #list(APPEND _ver_map_files ${Matlab_EXTERN_LIBRARY_DIR}/cppMexFunction.map) # This one doesn't exist on Linux + set(_link_flags "${_link_flags} -Wl,-U,_mexCreateMexFunction -Wl,-U,_mexDestroyMexFunction -Wl,-U,_mexFunctionAdapter") + endif() + set(_export_flag_name -exported_symbols_list) + else() # Linux + if(HAS_MINUS_PTHREAD) + target_compile_options(${${prefix}_NAME} PRIVATE "-pthread") + endif() + set(_link_flags "${_link_flags} -Wl,--as-needed") + set(_export_flag_name --version-script) + endif() + #foreach(_file ${_ver_map_files}) + # set(_link_flags "${_link_flags} -Wl,${_export_flag_name},${_file}") + #endforeach() + set_target_properties(${${prefix}_NAME} + PROPERTIES + DEFINE_SYMBOL "DLL_EXPORT_SYM=__attribute__((visibility(\"default\")))" + LINK_FLAGS "${_link_flags}" + ) + endif() +endfunction() diff --git a/src/matlab_mex.hpp b/src/matlab_mex.hpp new file mode 100644 index 0000000..9e9a278 --- /dev/null +++ b/src/matlab_mex.hpp @@ -0,0 +1,194 @@ +/* Own copy of mex.hpp and mexAdapter.hpp with only the functionality we need. + * This enables compiling on github runners without loading Matlab + */ + +// Uncomment to use the official interface +//#include "mex.hpp" +//#include "mexAdapter.hpp" + +#include "load_matlab.hpp" +#include +#include +#include + +#ifndef mex_hpp +#define mex_hpp +#endif + +#ifndef __MEX_CPP_PUBLISHED_API_HPP__ +#define __MEX_CPP_PUBLISHED_API_HPP__ + +#if defined(_WIN32 ) +#define NOEXCEPT throw() +#else +#define NOEXCEPT noexcept +#endif +#if defined(_MSC_VER) && _MSC_VER==1800 +#define NOEXCEPT_FALSE throw(...) +#else +#define NOEXCEPT_FALSE noexcept(false) +#endif + +#define __MEX_CPP_API__ +#define __MEX_IO_ADAPTER_HPP__ +#define __MEX_FUNCTION_CPP_HPP__ +#define __MEX_EXCEPTION_CPP_HPP__ + +namespace matlab { + namespace mex { + template class MexIORange { + iterator_type begin_, end_; + size_t size_; + public: + MexIORange(iterator_type b, iterator_type e, size_t size) : begin_(b), end_(e), size_(size) {} + typename std::iterator_traits::difference_type size() { return size_; } + typename std::iterator_traits::difference_type internal_size() { return std::distance(begin_, end_); } + iterator_type begin() { return begin_; } + iterator_type end() { return end_; } + bool empty() { return size() == 0; } + typename std::iterator_traits::reference operator[](size_t i) { + if (static_cast(i) + 1 > internal_size()) + throw std::runtime_error("ArgumentList index out of range."); + return *(begin_ + i); + } + }; + typedef MexIORange::iterator> ArgumentList; + class Function { + void* functionImpl; + public: + Function() { + const char* mlroot = std::getenv("LIBPYMCR_MATLAB_ROOT"); + _loadlibraries(mlroot); + functionImpl = mexGetFunctionImpl(); + } + virtual ~Function() NOEXCEPT_FALSE { mexDestroyFunctionImpl(functionImpl); } + virtual void operator()(ArgumentList outputs, ArgumentList inputs) {} + }; + } // matlab::mex + namespace engine { + class Exception : public std::exception { + public: + Exception() : std::exception() {} + Exception(const std::string& msg) : message(msg) {} + virtual ~Exception() {} + Exception& operator=(const Exception& rhs) { + message = rhs.message; + return *this; + } + virtual const char* what() const NOEXCEPT { return message.c_str(); } + private: + std::string message; + }; + } // matlab::engine +} +#endif // __MEX_CPP_PUBLISHED_API_HPP__ + +#ifndef __MEX_FILE_ADAPTER_HPP__ +#define __MEX_FILE_ADAPTER_HPP__ + +#define __MEX_FUNCTION_ADAPTER_HPP__ +#define __MEX_EXCEPTION_IMPL_CPP_HPP__ + +#ifdef _MSC_VER +# define DLLEXP __declspec(dllexport) +#elif __GNUC__ >= 4 +# define DLLEXP __attribute__ ((visibility("default"))) +#else +# define DLLEXP +#endif + +void mexHandleException(void (*callbackErrHandler)(const char*, const char*)) { + try { + throw; + } catch(const matlab::engine::Exception& ex) { + callbackErrHandler(ex.what(), ""); + } catch(const matlab::Exception& ex) { + callbackErrHandler(ex.what(), ""); + } catch(const std::exception& ex) { + callbackErrHandler(ex.what(), ""); + } catch(...) { + callbackErrHandler("Unknown exception thrown.", ""); + } +} + +void implToArray(int na, void* va[], std::vector& pa) { + assert(na == static_cast(pa.capacity())); + for(int i = 0; i < na; i++) { + matlab::data::impl::ArrayImpl* impl = reinterpret_cast(va[i]); + pa.push_back(matlab::data::detail::Access::createObj(impl)); + } +} + +void arrayToImpl(int na, void* va[], const std::vector& pa) { + for(int i = 0; i < na; i++) { + va[i] = matlab::data::detail::Access::getImpl(pa[i]); + } +} + +void arrayToImplOutput(int nlhs, std::vector& edi_plhs, void (*callbackOutput)(int, void**)) { + assert(nlhs == static_cast(edi_plhs.size())); + std::unique_ptr + vlhsPtr(new matlab::data::impl::ArrayImpl*[nlhs], + [](matlab::data::impl::ArrayImpl** ptr) { + delete[] ptr; + }); + void** vlhs = (void**)vlhsPtr.get(); + arrayToImpl(nlhs, vlhs, edi_plhs); + callbackOutput(nlhs, vlhs); +} + +template matlab::mex::Function * mexCreatorUtil() { + static_assert(std::is_base_of::value, "MexFunction class must be a subclass of matlab::mex::Function."); + matlab::mex::Function* mexFunction = new T(); + return mexFunction; +} + +class MexFunction; // This is defined by the user +// Define null function here for the old interface, else Win/Mac linker complains +extern "C" void mexFunction() {} + +extern "C" DLLEXP void* mexCreateMexFunction(void (*callbackErrHandler)(const char*, const char*)) { + try { + matlab::mex::Function *mexFunc = mexCreatorUtil(); + return mexFunc; + } catch (...) { + mexHandleException(callbackErrHandler); + return nullptr; + } +} + +extern "C" DLLEXP void mexDestroyMexFunction(void* mexFunc, + void (*callbackErrHandler)(const char*, const char*)) { + matlab::mex::Function* mexFunction = reinterpret_cast(mexFunc); + try { + delete mexFunction; + } catch (...) { + mexHandleException(callbackErrHandler); + } +} + +extern "C" DLLEXP +void mexFunctionAdapter(int nlhs_, + int nlhs, + int nrhs, + void* vrhs[], + void* mFun, + void (*callbackOutput)(int, void**), + void (*callbackErrHandler)(const char*, const char*)) { + matlab::mex::Function* mexFunction = reinterpret_cast(mFun); + std::vector edi_prhs; + edi_prhs.reserve(nrhs); + implToArray(nrhs, vrhs, edi_prhs); + std::vector edi_plhs(nlhs); + matlab::mex::ArgumentList outputs(edi_plhs.begin(), edi_plhs.end(), nlhs_); + matlab::mex::ArgumentList inputs(edi_prhs.begin(), edi_prhs.end(), nrhs); + try { + (*mexFunction)(outputs, inputs); + } catch(...) { + mexHandleException(callbackErrHandler); + return; + } + arrayToImplOutput(nlhs, edi_plhs, callbackOutput); +} + +#endif // __MEX_FILE_ADAPTER_HPP__ diff --git a/src/pythonFunctionWrapper.m b/src/pythonFunctionWrapper.m deleted file mode 100644 index 06a0d70..0000000 --- a/src/pythonFunctionWrapper.m +++ /dev/null @@ -1,27 +0,0 @@ -classdef pythonFunctionWrapper < handle - properties - func_uuid - end - methods - % Constructor - function obj = pythonFunctionWrapper(uuid) - obj.func_uuid = char(uuid); - end - function delete(obj) - pythonRemoveFuncKey(obj.func_uuid); - end - function varargout = subsref(obj, s) - switch s(1).type - case '()' - varargout = call_python_m(obj.func_uuid, s(1).subs{:}); - case '.' - varargout = obj.(s(1).subs); - otherwise - error('Function wrapper does not cell indexing'); - end - if ~iscell(varargout) - varargout = {varargout}; - end - end - end -end diff --git a/src/pythonRemoveFuncKey.cpp b/src/pythonRemoveFuncKey.cpp deleted file mode 100644 index 6f49e02..0000000 --- a/src/pythonRemoveFuncKey.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "mex.hpp" -#include "mexAdapter.hpp" -#include "pybind11/pybind11.h" -#include -#include -#include -#include -#include - -using namespace matlab::data; -using matlab::mex::ArgumentList; -namespace py = pybind11; - -class MexFunction : public matlab::mex::Function { - - public: - void operator()(ArgumentList outputs, ArgumentList inputs) { - std::shared_ptr matlabPtr = getEngine(); - matlab::data::ArrayFactory factory; - if (inputs.size() < 1 || - inputs[0].getType() != matlab::data::ArrayType::CHAR) { - matlabPtr->feval(u"error", 0, - std::vector({ factory.createScalar("First input must a string key to index into a Python function.") })); - } - matlab::data::CharArray key = inputs[0]; - - PyGILState_STATE gstate = PyGILState_Ensure(); // GIL{ - - if (!Py_IsInitialized()) - throw std::runtime_error("Python not initialized."); - - // Imports the wrapper module and check its global dictionary for the function we want - py::module pyHoraceFn; - try { - pyHoraceFn = py::module::import("pace_neutrons.FunctionWrapper"); - } - catch (...) { - PyGILState_Release(gstate); - matlabPtr->feval(u"error", 0, - std::vector({ factory.createScalar("Cannot import Python pace_neutrons module.") })); - } - py::dict fnDict = pyHoraceFn.attr("_globalFunctionDict"); - - try { - if (PyDict_DelItemString(fnDict.ptr(), key.toAscii().c_str()) != 0) - throw std::runtime_error("Cannot delete key from functions dict."); - } - catch (...) { - PyGILState_Release(gstate); - matlabPtr->feval(u"error", 0, - std::vector({ factory.createScalar("Cannot delete key from functions dict.") })); - } - - PyGILState_Release(gstate); // GIL} - - } - -}; diff --git a/src/recfind.m b/src/recfind.m deleted file mode 100644 index 0ed45f5..0000000 --- a/src/recfind.m +++ /dev/null @@ -1,65 +0,0 @@ -function in = recfind(in) - -uncell = false; -if ~iscell(in) - in = {in}; - uncell = true; -end - -% Unsupported MATLAB types in Python (as of R2020b) -% https://www.mathworks.com/help/matlab/matlab_external/limitations-to-python-support.html -% Multidimensional char or cell arrays [Ok, gives error message, no crash] -% Structure arrays -% Complex, scalar integers or arrays [Ok, will wrap it] -% Sparse arrays -% categorical, table, containers.Map, datetime types -% MATLAB objects -% meta.class (py.class) - -for i = 1:numel(in) - class_i = class(in{i}); - if iscell(in{i}) - in{i} = recfind(in{i}); - elseif isstruct(in{i}) - if numel(in{i}) > 1 - % Structure array, convert to cell of structures (auto convert to list) - outcell = {}; - for n = 1:numel(in{i}) - outcell{n} = recfind(in(i)); - end - in{i} = outcell; - else - f = fieldnames(in{i}); - for k = 1:numel(f) - if isobject(in{i}.(f{k})) - UUID = char(randsamp([65:74 97:106], 32, true)); - set_global(UUID, in{i}.(f{k})); - in{i}.(f{k}) = sprintf('!$%s',UUID); - elseif isstruct(in{i}.(f{k})) - in{i}.(f{k}) = recfind(in{i}.(f{k})); - elseif iscell(in{i}.(f{k})) - in{i}.(f{k}) = recfind(in{i}.(f{k})); - end - end - end - elseif strncmp(class_i, 'matlab', 6) || ... % Matlab object - strcmp(class_i, 'categorical') || strcmp(class_i, 'table') || ... - strcmp(class_i, 'containers.Map') || strcmp(class_i, 'datetime') || ... - strcmp(class_i, 'meta.class') || ... - strncmp(class_i, 'py.', 3) || ... - issparse(in{i}) - in{i} = thinwrapper(in{i}); - end -end - -if uncell - in = in{1}; -end - -end - -function out = randsamp(n, k, bv) -% Replacement for randsample from stats toolbox - v = ceil(rand(1, k) * numel(n)); - out = n(v); -end diff --git a/src/set_global.m b/src/set_global.m deleted file mode 100644 index f96e025..0000000 --- a/src/set_global.m +++ /dev/null @@ -1,8 +0,0 @@ -function ack = set_global(name, value) - try - assignin('base', name, value); - ack = true; - catch - ack = false; - end -end \ No newline at end of file diff --git a/src/thinwrapper.m b/src/thinwrapper.m deleted file mode 100644 index b839a9d..0000000 --- a/src/thinwrapper.m +++ /dev/null @@ -1,12 +0,0 @@ -classdef thinwrapper < handle - properties - ObjectString - end - methods - % Constructor - function obj = thinwrapper(input_obj) - obj.ObjectString = ['obj' replace(char(java.util.UUID.randomUUID), '-', '')]; - assignin('base', obj.ObjectString, input_obj); - end - end -end diff --git a/src/type_converter.cpp b/src/type_converter.cpp new file mode 100644 index 0000000..72d11ea --- /dev/null +++ b/src/type_converter.cpp @@ -0,0 +1,591 @@ +#include "type_converter.hpp" + +namespace libpymcr { + +// ------------------------------------------------------------------------------------------------------- +// Code for dynamic CPython class to wrap Matlab object without using PyBind +// ------------------------------------------------------------------------------------------------------- +PyObject *matlab_wrapper_str(PyObject *self) { + return PyUnicode_FromString("An opaque container for a Matlab object"); +} + +void matlab_wrapper_del(PyObject* pyself) { + PyObject *error_type, *error_value, *error_traceback; + PyErr_Fetch(&error_type, &error_value, &error_traceback); // Save the current exception, if any. + matlab_wrapper* self = (matlab_wrapper*)pyself; + self->arr_impl_sptr.reset(); + PyErr_Restore(error_type, error_value, error_traceback); // Restore the saved exception. +} + +// Functions to handle Matlab mxArrays +struct mxArray_header_2020a* _get_mxArray(Array arr) { + matlab::data::impl::ArrayImpl* imp = reinterpret_cast(&arr)->get_ptr(); + struct impl_header_col_major* m0 = reinterpret_cast(imp); + struct impl_header_col_major* m1 = reinterpret_cast(m0->data_ptr); +#if defined __APPLE__ + return reinterpret_cast(m1->data_ptr); +#else + return reinterpret_cast(m1->mxArray); +#endif +} + +// ------------------------------------------------------------------------------------------------------- +// Code to translate Matlab types to Python types +// ------------------------------------------------------------------------------------------------------- + +PyObject* pymat_converter::is_wrapped_np_data(void *addr) { + // Checks if addressed belongs to a wrapped numpy array + for (auto it = m_py_cache.begin(); it != m_py_cache.end(); it++) { + py::detail::PyArray_Proxy *arr = py::detail::array_proxy(it->second); + if (addr == arr->data) + return reinterpret_cast(it->second); + } + return nullptr; +} + +void* _get_data_pointer(matlab::data::Array arr) { + if (arr.getMemoryLayout() == matlab::data::MemoryLayout::COLUMN_MAJOR) { + struct mxArray_header_2020a* mx = _get_mxArray(arr); + return mx->pr; + } else { + matlab::data::impl::ArrayImpl* imp = reinterpret_cast(&arr)->get_ptr(); + struct impl_header_row_major* m = static_cast(static_cast(imp)); + return m->buffer; + } +} + +// Wraps a Matlab array in a numpy array without copying (should work with all numeric types) +template PyObject* pymat_converter::matlab_to_python_t (matlab::data::Array arr, dt) { + // First checks if the array is not constructed from numpy data in the first place + PyObject* wrapper = is_wrapped_np_data(_get_data_pointer(arr)); + if (wrapper != nullptr) { + // If so, just return the original numpy array, but need to INCREF it as returning new reference + if (!m_mex_flag) { + // For case where an np array is created in a mex file, its REFCNT was INC in the cache + Py_INCREF(wrapper); + } + return wrapper; + } + std::vector strides = {sizeof(T)}; + std::vector dims = arr.getDimensions(); + if (arr.getMemoryLayout() == matlab::data::MemoryLayout::COLUMN_MAJOR) { + for (size_t ii=0; ii<(dims.size()-1); ii++) { + strides.push_back(dims[ii] * strides[ii]); + } + } + else { + strides.resize(dims.size(), sizeof(T)); + for (size_t ii=dims.size()-2; ii>=0; ii--) { + strides[ii] = dims[ii+1] * strides[ii+1]; + } + } + // Needs to be const to avoid copying to a new (mutable) array + const matlab::data::TypedArray arr_t = matlab::data::TypedArray(arr); + const T &tmp = *arr_t.begin(); + // The API recommends to set a PyCapsule with a custom deleter, which also ensures that PyBind + // will not copy the data (see: https://github.com/pybind/pybind11/issues/323) + // https://numpy.org/devdocs/reference/c-api/data_memory.html + // Since we have our own matlab_wrapper Python object we use that instead of a PyCapsule + // (which only has a normal pointer) so we can use the shared_ptr directly. + matlab_wrapper* owner = (matlab_wrapper*) m_py_matlab_wrapper_t->tp_alloc(m_py_matlab_wrapper_t, 0); + owner->arr_impl_sptr = reinterpret_cast(&arr)->get_pImpl(); + py::array_t retval(dims, strides, (T*)(&tmp), reinterpret_cast(owner)); + // PyBind auto increfs the base because PyArray_SetBaseObject steals the ref - but we want this + Py_DECREF(owner); + return retval.release().ptr(); +} +// Specialisations for other types to generate the appropriate Python type +PyObject* pymat_converter::matlab_to_python_t(matlab::data::Array input, dt) { + const matlab::data::TypedArray str(input); + return PyUnicode_FromKindAndData(2, (void*)(&(*str.begin())), str.getNumberOfElements()); +} +PyObject* pymat_converter::matlab_to_python_t(matlab::data::Array input, dt>) { + const matlab::data::TypedArray str(input); + if (input.getNumberOfElements() == 1) { + const std::basic_string cstr(str[0]); + return PyUnicode_FromKindAndData(2, (void*)cstr.c_str(), cstr.size()); + } else { + PyObject* retval = PyList_New(0); + for (auto mstr: str) { + const std::basic_string cstr(mstr); + if (PyList_Append(retval, PyUnicode_FromKindAndData(2, (void*)cstr.c_str(), cstr.size()))) { + throw std::runtime_error("Error constructing python list from string array"); + } + } + return retval; + } +} +PyObject* pymat_converter::matlab_to_python_t(matlab::data::Array input, dt) { + const matlab::data::StructArray in_struct(input); + if (input.getNumberOfElements() == 1) { + PyObject* retval = PyDict_New(); + for (auto ky : in_struct.getFieldNames()) { + PyObject* pyky = PyUnicode_FromString(std::string(ky).c_str()); + PyObject* pyval = to_python(in_struct[0][ky]); + if (PyDict_SetItem(retval, pyky, pyval)) { + throw std::runtime_error("Error constructing python dict from matlab struct"); + } + } + return retval; + } else { + PyObject* retval = PyList_New(0); + for (auto struc : in_struct) { + PyObject* elem = PyDict_New(); + for (auto ky : in_struct.getFieldNames()) { + PyObject* pyky = PyUnicode_FromString(std::string(ky).c_str()); + PyObject* pyval = to_python(struc[ky]); + if (PyDict_SetItem(elem, pyky, pyval)) { + throw std::runtime_error("Error constructing python dict from matlab struct"); + } + } + if (PyList_Append(retval, elem)) { + throw std::runtime_error("Error constructing python list from struct array"); + } + } + return retval; + } +} +PyObject* pymat_converter::matlab_to_python_t(matlab::data::Array input, dt) { + const matlab::data::CellArray in_cell(input); + PyObject* retval = PyList_New(0); + for (auto elem : in_cell) { + PyObject *val = to_python(elem); + int success = PyList_Append(retval, val); + Py_DECREF(val); // Effectively steals the reference to val + if (success == -1) { + throw std::runtime_error("Error constructing python list from cell array"); + } + } + return retval; +} + +PyObject* pymat_converter::matlab_to_python_t(matlab::data::Array input, dt) { + const matlab::data::TypedArray in_arr(input); + size_t n_elem = in_arr.getNumberOfElements(); + if (n_elem == 1) { + return PyBool_FromLong(static_cast(in_arr[0])); + } else { + PyObject* retval = PyList_New(n_elem); + size_t idx = 0; + for (auto elem: in_arr) { + if(PyList_SetItem(retval, idx++, PyBool_FromLong(static_cast(elem))) == -1) { + throw std::runtime_error("Error constructing python bool list from array"); + } + } + return retval; + } +} + +PyObject* pymat_converter::wrap_matlab_object(matlab::data::Array input) { + // Wrap a Matlab class in an opaque Python container which contains the underlying shared_ptr + matlab_wrapper* container = (matlab_wrapper*) m_py_matlab_wrapper_t->tp_alloc(m_py_matlab_wrapper_t, 0); + container->arr_impl_sptr = reinterpret_cast(&input)->get_pImpl(); + return (PyObject*) container; +} + +PyObject* pymat_converter::to_python(matlab::data::Array input) { + matlab::data::ArrayType type = input.getType(); + switch(type) { + case matlab::data::ArrayType::DOUBLE: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::SINGLE: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::COMPLEX_SINGLE: return matlab_to_python_t(input, dt>()); + case matlab::data::ArrayType::COMPLEX_DOUBLE: return matlab_to_python_t(input, dt>()); + case matlab::data::ArrayType::LOGICAL: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::INT8: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::INT16: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::INT32: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::INT64: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::UINT8: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::UINT16: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::UINT32: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::UINT64: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::CHAR: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::MATLAB_STRING: return matlab_to_python_t(input, dt>()); + case matlab::data::ArrayType::STRUCT: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::CELL: return matlab_to_python_t(input, dt()); + case matlab::data::ArrayType::ENUM: + throw std::runtime_error("Matlab enums not supported in Python"); + case matlab::data::ArrayType::SPARSE_LOGICAL: + case matlab::data::ArrayType::SPARSE_DOUBLE: + case matlab::data::ArrayType::SPARSE_COMPLEX_DOUBLE: + throw std::runtime_error("Matlab sparse matrices not supported in Python"); + case matlab::data::ArrayType::VALUE_OBJECT: + case matlab::data::ArrayType::HANDLE_OBJECT_REF: + return wrap_matlab_object(input); + default: + throw std::runtime_error("Unrecognised input type"); + } +} + +// ------------------------------------------------------------------------------------------------------- +// Code to translate Python types to Matlab types +// ------------------------------------------------------------------------------------------------------- + +template Array pymat_converter::raw_to_matlab(char *raw, size_t sz, std::vector dims, + ssize_t *strides, int f_or_c_continuous, + matlab::data::ArrayFactory &factory, PyObject* obj) { + if (f_or_c_continuous == 0) { + // Slower copy methods - follow data strides for non-contiguous arrays + buffer_ptr_t buf = factory.createBuffer(sz); + T* ptr = buf.get(); + std::vector stride; + std::vector k = {dims[0]}; + for (size_t i=1; i -1) + stride.push_back(static_cast(strides[i])); + else + throw std::runtime_error("Invalid stride in numpy array"); + } + for (size_t i=0; i0; d--) { + vi = idx % k[d-1]; + offset += ((idx - vi) / k[d-1]) * stride[d]; + idx = vi; + } + offset += vi * stride[0]; + ptr[i] = *((T*)(raw + offset)); + } + return factory.createArrayFromBuffer(dims, std::move(buf), MemoryLayout::COLUMN_MAJOR); + } else { + // Fast method: wrap or block memory copy for contigous C- or Fortran-style arrays + matlab::data::Array rv; + T* begin = reinterpret_cast(raw); + // Default to try to wrap existing data without copying. We can do this with createArrayFromBuffer + // but (see: https://www.mathworks.com/matlabcentral/answers/514456) this causes an issue + // when Matlab tries to delete the buffer. So we have to use a hack (see release_buffer() below) + buffer_ptr_t buf = buffer_ptr_t(begin, [](void* ptr){}); + if (m_numpy_conv_flag == NumpyConversion::COPY || sz < 1000) { + // But if user specify to copy or for small arrays, then use the prescribed API with createBuffer() + buf = factory.createBuffer(sz); + memcpy(buf.get(), begin, sz * sizeof(T)); + } + if (f_or_c_continuous == -1 || dims.size() == 1) { + rv = factory.createArrayFromBuffer(dims, std::move(buf), MemoryLayout::COLUMN_MAJOR); + } else { + rv = factory.createArrayFromBuffer(dims, std::move(buf), MemoryLayout::ROW_MAJOR); + } + if (m_numpy_conv_flag == NumpyConversion::WRAP && sz >= 1000) { + // For wrapped arrays, we store a shared-data copy in a cache in this object to prevent Matlab + // from deleting it before we are ready to release the buffer. + if (m_mex_flag) { + // This flag indicates the conversion was called from the call_python mex file. + // In this case the Python obj will be DECREF when exiting the mex so we must INCREF here + Py_INCREF(obj); + } + m_py_cache.push_back(std::make_pair(rv, obj)); + } + return rv; + } +} + +bool pymat_converter::release_buffer(matlab::data::Array arr) { + // Hack to safely release a buffer for a no-copy Matlab array converted from numpy + if (m_numpy_conv_flag == NumpyConversion::COPY) { + return true; + } + if (arr.getMemoryLayout() == matlab::data::MemoryLayout::ROW_MAJOR) { + // It seems that ROW_MAJOR (C-style) arrays use a new C++ based type which supports custom deleter, + // So we don't need to hack these types of arrays + return true; + } + // For Column-major arrays, which are wrappers around a mxArray type, we have to use a hack + // where we create a small buffer using createBuffer() and overwrite the mxArray->pr pointer + // to point to this instead of the numpy array. Then when this array is deleted Matlab will + // free the newly created buffer instead of the numpy array which causes a heap memory error + matlab::data::ArrayFactory factory; + struct mxArray_header_2020a* mx = _get_mxArray(arr); + long rc = (mx->refcount == nullptr) ? 1 : *(mx->refcount); + if (mx->refcount == nullptr || *(mx->refcount) == 1) { + buffer_ptr_t buf = factory.createBuffer(1); + // Hack - switch the memory for a Matlab created buffer + mx->pr = reinterpret_cast(buf.release()); + return true; + } else { + return false; + } +} + +matlab::data::Array pymat_converter::python_array_to_matlab(PyObject *result, matlab::data::ArrayFactory &factory) { + // Cast the result to the PyArray C struct and its corresponding dtype struct + py::detail::PyArray_Proxy *arr = py::detail::array_proxy(result); + py::detail::PyArrayDescr_Proxy *dtype = py::detail::array_descriptor_proxy(arr->descr); + if (arr->nd == 0) { // 0-dimensional array - return a scalar + if (dtype->kind == 'f') { + if (dtype->elsize == sizeof(double)) return factory.createScalar(*((double*)(arr->data))); + else if (dtype->elsize == sizeof(float)) return factory.createScalar(*((float*)(arr->data))); + } else if (dtype->kind == 'c') { + if (dtype->elsize == sizeof(std::complex)) return factory.createScalar(*((std::complex*)(arr->data))); + else if (dtype->elsize == sizeof(std::complex)) return factory.createScalar(*((std::complex*)(arr->data))); + } + } + if (dtype->elsize == 0) { + throw std::runtime_error("Cannot convert heterogeneous numpy arrays to Matlab"); + } + std::vector dims; + size_t numel = 1; + for (size_t id = 0; id < arr->nd; id++) { + dims.push_back(arr->dimensions[id]); + numel = numel * dims[id]; + } + // If we have 1D vector, force it to be a row vector to be consistent with Matlab + if (dims.size() == 1) { + dims.insert(dims.begin(), 1); } + int fc_cont = 0; + if (py::detail::check_flags(result, py::detail::npy_api::NPY_ARRAY_F_CONTIGUOUS_)) + fc_cont = -1; + else if (py::detail::check_flags(result, py::detail::npy_api::NPY_ARRAY_C_CONTIGUOUS_)) + fc_cont = 1; + + char *d = arr->data; + ssize_t *strd = arr->strides; + switch(dtype->type_num) { + case py::detail::npy_api::NPY_DOUBLE_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_FLOAT_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_CDOUBLE_: return raw_to_matlab>(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_CFLOAT_: return raw_to_matlab>(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_BOOL_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_INT8_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_INT16_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_INT32_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_INT64_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_UINT8_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_UINT16_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_UINT32_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_UINT64_: return raw_to_matlab(d, numel, dims, strd, fc_cont, factory, result); + case py::detail::npy_api::NPY_LONGDOUBLE_: + case py::detail::npy_api::NPY_CLONGDOUBLE_: + throw std::runtime_error("Long double type not supported by Matlab. Cannot convert numpy array"); + case py::detail::npy_api::NPY_STRING_: + case py::detail::npy_api::NPY_UNICODE_: + throw std::runtime_error("Cannot convert numpy string array to Matlab"); + case py::detail::npy_api::NPY_OBJECT_: + throw std::runtime_error("Cannot convert numpy object array to Matlab"); + default: + throw std::runtime_error("Cannot convert unsupported numpy array dtype"); + } +} + +template T convert_py_obj (PyObject *obj) { + throw std::runtime_error("Unrecognised Python type"); } +template <> int64_t convert_py_obj (PyObject *obj) { + return PyLong_AsLong(obj); } +template <> double convert_py_obj (PyObject *obj) { + return PyFloat_AsDouble(obj); } +template <> std::complex convert_py_obj (PyObject *obj) { + return std::complex(PyComplex_RealAsDouble(obj), PyComplex_ImagAsDouble(obj)); } + +template Array pymat_converter::fill_vec_from_pyobj(std::vector &objs, matlab::data::ArrayFactory &factory) { + std::vector vec; + vec.resize(objs.size()); + std::transform (objs.begin(), objs.end(), vec.begin(), convert_py_obj); + return factory.createArray::iterator, T>({1, vec.size()}, vec.begin(), vec.end()); +} + +CharArray pymat_converter::python_string_to_matlab(PyObject *result, matlab::data::ArrayFactory &factory) { + Py_ssize_t str_sz; + const char *str = PyUnicode_AsUTF8AndSize(result, &str_sz); + if (!str) { + PyErr_Print(); + throw std::runtime_error("Cannot create string from pyobject"); + } + return factory.createCharArray(std::string(str, str_sz)); +} + +StructArray pymat_converter::python_dict_to_matlab(PyObject *result, matlab::data::ArrayFactory &factory) { + Py_ssize_t pos = 0; + PyObject *key, *val; + std::vector keys; + std::vector vals; + while (PyDict_Next(result, &pos, &key, &val)) { + Py_ssize_t str_sz; + const char *str = PyUnicode_AsUTF8AndSize(key, &str_sz); + if (!str) { + throw std::runtime_error("Can only convert python dict with string keys to Matlab struct"); + } + keys.push_back(std::string(str, str_sz)); + vals.push_back(val); + } + StructArray retval = factory.createStructArray({1,1}, keys); + for (size_t ii=0; ii &data, std::vector &dims, bool is_first=false) { + size_t obj_size = PyTuple_Check(result) ? (size_t)PyTuple_Size(result) : (size_t)PyList_Size(result); + bool is_tuple = false; + int dim, dim0; + if (is_first) { + dims.push_back(obj_size); } + for(size_t ii=0; ii _to_colmajor(std::vector inp, std::vector dims) { + std::vector out(inp.size(), 0.); + std::vector strides = {1}; + size_t sz = dims.size(); + for (size_t i=1; i0; d--) { + // Adapted from np code unravel_index_loop() and ravel_multi_index() in compiled_base.c + size_t tmp = val / dims[d-1]; // Uses a local to enable single-divide optimisation + size_t coord = val % dims[d-1]; + val = tmp; + f_idx += coord * strides[d-1]; + } + out[f_idx] = inp[i]; + } + return out; +} + +Array pymat_converter::listtuple_to_cell(PyObject *result, matlab::data::ArrayFactory &factory) { + // Try to see if we have a nested list/tuple of numeric types: construct a Matlab N-D array + std::vector arr_dim; + std::vector arr_data; + bool is_tuple = PyTuple_Check(result); + if (!is_tuple && _list_array_data(result, arr_data, arr_dim, true) > 0) { + // Only convert nested lists to Matlab arrays, leave tuples as cells + if (arr_dim.size() > 1) { + arr_data = _to_colmajor(arr_data, arr_dim); // Convert to column-major (req by Matlab) + } else { + arr_dim.insert(arr_dim.begin(), 1); } // Force row vector for consistency ([1 2 3] is row vector in ml) + return factory.createArray::iterator, double>(arr_dim, arr_data.begin(), arr_data.end()); + } + size_t obj_size = is_tuple ? (size_t)PyTuple_Size(result) : (size_t)PyList_Size(result); + CellArray cell_out = factory.createCellArray({1, obj_size}); + std::vector objs; + int typeflags = is_tuple ? MYOTHER : 0; // Only create vector from lists not tuples + for(size_t ii=0; ii(objs, factory); + } else if (typeflags == MYFLOAT) { + return fill_vec_from_pyobj(objs, factory); + } else if (typeflags == MYCOMPLEX) { + return fill_vec_from_pyobj>(objs, factory); + } else { + // We've got mixed or nonnumeric types - return a cell array of the elements + return cell_out; + } +} + +matlab::data::Array pymat_converter::wrap_python_function(PyObject *input, matlab::data::ArrayFactory &factory) { + // Wraps a Python function so it can be called using a mex function + matlab::data::Array rv; + std::uintptr_t addr = reinterpret_cast(input); + rv = factory.createStructArray({1, 1}, std::vector({"libpymcr_func_ptr"})); + rv[0][std::string("libpymcr_func_ptr")] = factory.createScalar(addr); + return rv; +} + +matlab::data::Array pymat_converter::python_to_matlab_single(PyObject *input, matlab::data::ArrayFactory &factory) { + matlab::data::Array output; + auto npy_api = py::detail::npy_api::get(); + bool is_arr = npy_api.PyArray_Check_(input); + if (is_arr) { + output = python_array_to_matlab(input, factory); + } else if (PyTuple_Check(input) || PyList_Check(input)) { + output = listtuple_to_cell(input, factory); + } else if (PyUnicode_Check(input)) { + output = python_string_to_matlab(input, factory); + } else if (PyDict_Check(input)) { + output = python_dict_to_matlab(input, factory); + } else if (PyBool_Check(input)) { // Must be before long (True and False also evaluate to integers) + output = factory.createScalar(static_cast(PyObject_IsTrue(input))); + } else if (PyLong_Check(input)) { + // Force conversion to double because Matlab defaults to this and many routines error with int64 + output = factory.createScalar(PyLong_AsDouble(input)); + } else if (PyFloat_Check(input)) { + output = factory.createScalar(PyFloat_AsDouble(input)); + } else if (PyComplex_Check(input)) { + output = factory.createScalar(std::complex(PyComplex_RealAsDouble(input), PyComplex_ImagAsDouble(input))); + } else if (input == Py_None) { + output = factory.createArray({}); + } else if (PyCallable_Check(input)) { + output = wrap_python_function(input, factory); + } else if (PyObject_TypeCheck(input, m_py_matlab_wrapper_t)) { + output = mArray(reinterpret_cast(input)->arr_impl_sptr); + } else { + throw std::runtime_error("This Python type cannot be converted to Matlab"); + } + return output; +} + +void pymat_converter::clear_py_cache() { + if (m_numpy_conv_flag == NumpyConversion::COPY) { + return; + } + for (auto it = m_py_cache.begin(); it != m_py_cache.end();) { + if (release_buffer(it->first)) { + it = m_py_cache.erase(it); + } else { + it++; + } + } +} + +matlab::data::Array pymat_converter::to_matlab(PyObject *input, bool mex_flag) { + matlab::data::ArrayFactory factory; + m_mex_flag = mex_flag; + return python_to_matlab_single(input, factory); +} + +pymat_converter::pymat_converter(NumpyConversion np_behaviour) : m_numpy_conv_flag(np_behaviour) { + m_py_matlab_wrapper_t = (PyTypeObject*) PyType_FromSpec(&spec_matlab_wrapper); +} + +pymat_converter::~pymat_converter() { + clear_py_cache(); +} + +} // namespace libpymcr diff --git a/src/type_converter.hpp b/src/type_converter.hpp new file mode 100644 index 0000000..a3e4488 --- /dev/null +++ b/src/type_converter.hpp @@ -0,0 +1,176 @@ +#ifndef TYPECONVERTER_H +#define TYPECONVERTER_H + +#include "load_matlab.hpp" +#include +using ssize_t = std::ptrdiff_t; + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MYINTEGER 1 +#define MYFLOAT 2 +#define MYCOMPLEX 4 +#define MYOTHER 8 + +using namespace matlab::data; +namespace py = pybind11; + +namespace matlab { + namespace data { + class mArray : public Array { + // Subclass the Array to be able to access and expose its protected member + public: + mArray(std::shared_ptr rhs_pImpl) MW_NOEXCEPT { + this->pImpl = rhs_pImpl; + } + const std::shared_ptr get_pImpl() { + return this->pImpl; + } + impl::ArrayImpl* get_ptr() { + return this->pImpl.get(); + } + protected: + }; + } +} + +namespace libpymcr { + + // Headers for hacking a mxArray + struct mxArray_header_2020a { // 96 bytes long + std::int32_t *refcount; // Pointer to the number of shared copies + void *unknown1; // Seems to be zero + std::int64_t ClassID; // https://mathworks.com/help/matlab/apiref/mxclassid.html + std::int64_t flags; // ??? + union { + std::int64_t M; // Row size for 2D matrices, or + std::int64_t *dims; // Pointer to dims array for nD > 2 arrays + } Mdims; + union { + std::int64_t N; // Column size for 2D matrices, or + std::int64_t ndims; // Number of dimemsions for nD > 2 arrays + } Nndim; + void *unknown_addr1; // Something related to structs and cells + void *pr; // Pointer to the data + void *unknown_addr2; // Something related to structs or sparse + void *unknown_addr3; // Something related to sparse + void *unknown2; // Seems to be zero + void *unknown3; // Seems to be zero + }; + + struct impl_header_col_major { + void *ad1; // Virtual pointer table? + std::int64_t *unity; // Seems to be always 1 + void *data_ptr; // Pointer to another struct that points to a mxArray + std::int64_t *flags; // Some kind of flags? + std::int64_t *dims; // Pointer to dimensions array +#if defined _WIN32 + // For some reason windows (or VS?) has a 32-byte spacer between these fields + void *unknown1; + void *unknown2; + void *unknown3; + void *unknown4; +#endif + void *mxArray; // Pointer to mxArray in the *data_ptr struct + }; + + // Header for a (new-style) row-major array + struct impl_header_row_major { + void *unk_addr1; + std::int64_t unk_i1; // seems to be some kind of flags? + std::int64_t *dims; // Pointer to dimensions array + void *unk_addr2; + void *unk_addr3; + std::int64_t n_elem; // Number of elements in array +#if defined _WIN32 + void *unk_addr4; + void *deleter; // Pointer to deleter function + std::int64_t junk[5]; // 40 bytes of junk (doesn't look like pointers) + void *unk_addr5; +#else + void *deleter; // Pointer to deleter function + void *unk1; // Pointer to a struct of metadata? + void *unk2; // Pointer to some kind of function? + void *unk3; // Pointer to some kind of function? +#endif + void *buffer; // Pointer to buffer (data) + std::int64_t flags; // More flags? + }; + + // Headers for a CPython class to wrap Matlab objects which we construct dynamically without Pybind11 + typedef struct { + PyObject_HEAD + std::shared_ptr arr_impl_sptr; + } matlab_wrapper; + + PyObject *matlab_wrapper_str(PyObject *self); + void matlab_wrapper_del(PyObject *self); + + static PyType_Slot matlab_wrapper_slots[] = { + {Py_tp_str, (void*)matlab_wrapper_str}, + {Py_tp_finalize, (void*)matlab_wrapper_del}, + {0, 0} + }; + + static PyType_Spec spec_matlab_wrapper = { + "libpymcr.matlab_wrapper", // tp_name + sizeof(matlab_wrapper), // tp_basicsize + 0, // tp_itemsize + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE, + matlab_wrapper_slots + }; + + template struct dt { typedef T type; }; + + // Now define the converter classes, first from Matlab to Python, then vice versa + class pymat_converter { + public: + enum class NumpyConversion { COPY, WRAP }; + protected: + NumpyConversion m_numpy_conv_flag; + std::vector< std::pair > m_py_cache; + PyTypeObject* m_py_matlab_wrapper_t; + bool m_mex_flag; + // Methods to convert from Matlab to Python + PyObject* is_wrapped_np_data(void* addr); + template PyObject* matlab_to_python_t (matlab::data::Array arr, dt); + PyObject* matlab_to_python_t(matlab::data::Array input, dt); + PyObject* matlab_to_python_t(matlab::data::Array input, dt>); + PyObject* matlab_to_python_t(matlab::data::Array input, dt); + PyObject* matlab_to_python_t(matlab::data::Array input, dt); + PyObject* matlab_to_python_t(matlab::data::Array input, dt); + PyObject* wrap_matlab_object(matlab::data::Array input); + // Methods to convert from Python to Matlab + template Array raw_to_matlab(char *raw, size_t sz, std::vector dims, + ssize_t *strides, int f_or_c_continuous, + matlab::data::ArrayFactory &factory, PyObject* obj); + bool release_buffer(matlab::data::Array arr); + matlab::data::Array python_array_to_matlab(PyObject *result, matlab::data::ArrayFactory &factory); + template Array fill_vec_from_pyobj(std::vector &objs, matlab::data::ArrayFactory &factory); + CharArray python_string_to_matlab(PyObject *result, matlab::data::ArrayFactory &factory); + Array listtuple_to_cell(PyObject *result, matlab::data::ArrayFactory &factory); + StructArray python_dict_to_matlab(PyObject *result, matlab::data::ArrayFactory &factory); + matlab::data::Array wrap_python_function(PyObject *input, matlab::data::ArrayFactory &factory); + matlab::data::Array python_to_matlab_single(PyObject *input, matlab::data::ArrayFactory &factory); + public: + void clear_py_cache(); + pymat_converter(NumpyConversion np_behaviour=NumpyConversion::COPY); + ~pymat_converter(); + matlab::data::Array to_matlab(PyObject *input, bool mex_flag=false); + PyObject* to_python(matlab::data::Array input); + }; + +} // namespace libpymcr + +#endif diff --git a/src/waitforgui.m b/src/waitforgui.m deleted file mode 100644 index 03df756..0000000 --- a/src/waitforgui.m +++ /dev/null @@ -1,43 +0,0 @@ -function waitforgui() -% wait for GUI -% -% WAITFORGUI() -% -% The function produces a window with a "Resume" button and waits until -% either the figure is closed or the button is pressed. -% - -sX = 150; -sY = 60; - -hFigure = figure(... - 'menuBar','none',... - 'toolBar','none',... - 'position',[0 0 sX sY],... - 'resize','off',... - 'name','Wait for GUI',... - 'numbertitle','off',... - 'visible','off',... - 'Tag','waitforgui'... - ); -movegui(hFigure,'northwest') -set(hFigure,'visible','on') - -% add resume button -hButton = uicontrol(... - 'Parent',hFigure,... - 'Style','pushbutton',... - 'String','Return',... - 'Units','normalized',... - 'Callback','uiresume',... - 'Visible','on'... - ); - -set(hButton,'Position',[0.1 0.1 0.8 0.8]); -% wait until button pressed -uiwait(hFigure) -if isvalid(hFigure) - close(hFigure) -end - -end \ No newline at end of file diff --git a/src/wrap_obj.m b/src/wrap_obj.m deleted file mode 100644 index e367dab..0000000 --- a/src/wrap_obj.m +++ /dev/null @@ -1,20 +0,0 @@ -function out = wrap_obj(obj) -% Wraps a given (old style) object in a thin wrapper so it does not get converted -% to a dict when transfered to Python. -% -% For a true struct (not old style class), it will keep it a struct but wrap any -% fields which are old-style classes (e.g. struct returned by multifit) - if isstruct(obj) - fn = fieldnames(obj); - for ifn = 1:numel(fn) - memb = obj.(fn{ifn}); - if (isempty(metaclass(memb)) && ~isjava(memb)) || has_thin_members(memb) - out.(fn{ifn}) = thinwrapper(memb); - else - out.(fn{ifn}) = memb; - end - end - else - out = thinwrapper(obj); - end -end From 6447c7e4a5cb0df23278758357cf7875eeb2272e Mon Sep 17 00:00:00 2001 From: Duc Le Date: Sun, 24 Sep 2023 18:53:21 +0100 Subject: [PATCH 2/5] Fix euphonic+tobyfit test. Update to run py3.11 --- CMakeLists.txt | 8 +++++++- src/CMakeLists.txt | 10 ---------- src/_stub.cpp | 16 ---------------- src/call.m | 9 +-------- src/call_python.cpp | 11 ++++++----- src/type_converter.cpp | 6 +++++- src/type_converter.hpp | 1 + test/run_test.py | 3 +-- 8 files changed, 21 insertions(+), 43 deletions(-) delete mode 100644 src/_stub.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 54009c5..9a522ed 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,7 +12,7 @@ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) -set(MINIMUM_PYBIND11_VERSION 2.5.0) +set(MINIMUM_PYBIND11_VERSION 2.10.1) set(FETCH_PYBIND11_REPO https://github.com/pybind/pybind11) # The latest VS needs an extra library VCRUNTIME140_1.dll which is not in @@ -60,6 +60,12 @@ else() endif() set(pybind11_FOUND ON) endif() +if (NOT PYTHON_INCLUDE_DIRS) + set(PYTHON_INCLUDE_DIRS ${Python3_INCLUDE_DIRS}) +endif() +if (NOT PYTHON_LIBRARIES) + set(PYTHON_LIBRARIES ${Python3_LIBRARIES}) +endif() # You can set a specific Matlab version folder here #set(Matlab_ROOT_DIR "c:/Program Files/MATLAB/R2020a") diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index efa32ed..43ab974 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -45,13 +45,3 @@ add_custom_command( "${CMAKE_CURRENT_SOURCE_DIR}/pyhorace_init.m" ) add_dependencies(compile_ctf call_python) - -if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") - pybind11_add_module(_stub _stub.cpp) - add_dependencies(_stub compile_ctf) - add_custom_command( - TARGET _stub POST_BUILD - COMMAND ${BASH_COMMAND} cp -f "$/_stub.*" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/pace_neutrons/pace/" - ) -endif() - diff --git a/src/_stub.cpp b/src/_stub.cpp deleted file mode 100644 index 9cff9ba..0000000 --- a/src/_stub.cpp +++ /dev/null @@ -1,16 +0,0 @@ -//#include "mex.h" -#include "pybind11/pybind11.h" -#include - -namespace py = pybind11; - -void call_matlab(std::string command) { - //mexEvalString(command.c_str()); - //mexCallMATLAB(0, NULL, 0, NULL, command.c_str()); - std::cout << command << std::endl; -} - -PYBIND11_MODULE(call_matlab, m) { - m.def("call_matlab", &call_matlab, "A function to call matlab with an arbitrary string", - py::arg("command")); -} diff --git a/src/call.m b/src/call.m index c4eb16c..60f69f2 100644 --- a/src/call.m +++ b/src/call.m @@ -1,11 +1,4 @@ function [varargout] = call(name, varargin) - disp('[*] call.m: ') - disp(name) - disp(' ; ') - disp(evalc('disp(varargin)')) - if strcmp(name, 'set_fun') - disp(evalc('disp(varargin{3})')) - end if strcmp(name, '_call_python') varargout = call_python_m(varargin{:}); return @@ -54,7 +47,7 @@ function out = unwrap(in_obj) out = in_obj; if isstruct(in_obj) && isfield(in_obj, 'libpymcr_func_ptr') - out = @(varargin) call('_call_python', [in_obj.libpymcr_func_ptr], varargin{:}); + out = @(varargin) call('_call_python', in_obj.libpymcr_func_ptr, varargin{:}); elseif isa(in_obj, 'containers.Map') && in_obj.isKey('wrapped_oldstyle_class') out = in_obj('wrapped_oldstyle_class'); elseif iscell(in_obj) diff --git a/src/call_python.cpp b/src/call_python.cpp index 6ff3f47..46fc6c8 100644 --- a/src/call_python.cpp +++ b/src/call_python.cpp @@ -26,11 +26,10 @@ class MexFunction : public matlab::mex::Function { public: void operator()(ArgumentList outputs, ArgumentList inputs) { matlab::data::ArrayFactory factory; - if (inputs.size() < 1 || inputs[0].getNumberOfElements() != 1 || - inputs[0].getType() != matlab::data::ArrayType::UINT64) { // Matlab only supports 64-bit - throw std::runtime_error("Input must be pointer to a Python function."); + if (inputs.size() < 1 || inputs[0].getType() != matlab::data::ArrayType::CHAR) { + throw std::runtime_error("Input must be reference to a Python function."); } - uintptr_t key = inputs[0][0]; + matlab::data::CharArray key = inputs[0]; PyGILState_STATE gstate = PyGILState_Ensure(); // GIL{ @@ -38,7 +37,9 @@ class MexFunction : public matlab::mex::Function { _converter = new libpymcr::pymat_converter(); } - PyObject* fn_ptr = reinterpret_cast(key); + py::module pyHoraceFn = py::module::import("libpymcr"); + py::dict fnDict = pyHoraceFn.attr("_globalFunctionDict"); + PyObject *fn_ptr = PyDict_GetItemString(fnDict.ptr(), key.toAscii().c_str()); if (PyCallable_Check(fn_ptr)) { PyObject *result; diff --git a/src/type_converter.cpp b/src/type_converter.cpp index 72d11ea..7a570f8 100644 --- a/src/type_converter.cpp +++ b/src/type_converter.cpp @@ -524,7 +524,11 @@ matlab::data::Array pymat_converter::wrap_python_function(PyObject *input, matla matlab::data::Array rv; std::uintptr_t addr = reinterpret_cast(input); rv = factory.createStructArray({1, 1}, std::vector({"libpymcr_func_ptr"})); - rv[0][std::string("libpymcr_func_ptr")] = factory.createScalar(addr); + const char* addrstr = std::to_string(addr).c_str(); + py::module pyHoraceFn = py::module::import("libpymcr"); + py::dict fnDict = pyHoraceFn.attr("_globalFunctionDict"); + PyDict_SetItemString(fnDict.ptr(), addrstr, input); + rv[0][std::string("libpymcr_func_ptr")] = factory.createCharArray(addrstr); return rv; } diff --git a/src/type_converter.hpp b/src/type_converter.hpp index a3e4488..3f04ac6 100644 --- a/src/type_converter.hpp +++ b/src/type_converter.hpp @@ -16,6 +16,7 @@ using ssize_t = std::ptrdiff_t; #include #include #include +#include #include #define MYINTEGER 1 diff --git a/test/run_test.py b/test/run_test.py index 614fac9..6e7d518 100644 --- a/test/run_test.py +++ b/test/run_test.py @@ -169,12 +169,11 @@ def test2_EuphonicCalc(self): def test3_EuphonicResolution(self): # Calculate spectra with full instrument resolution convolution - is_crystal = True; xgeom = [0,0,1]; ygeom = [0,1,0]; shape = 'cuboid'; shape_pars = [0.01,0.05,0.01]; - sample = self.m.IX_sample(is_crystal, xgeom, ygeom, shape, shape_pars) + sample = self.m.IX_sample(xgeom, ygeom, shape, shape_pars, '-single_crystal', True) wsc = self.m.set_sample(self.wsc, sample); ei = 40; freq = 400; chopper = 'g'; wsc = self.m.set_instrument(wsc, self.m.merlin_instrument(ei, freq, chopper)); From 3fb81dc3fca460fa6fce73ddba015aae5e058854 Mon Sep 17 00:00:00 2001 From: Duc Le Date: Mon, 25 Sep 2023 04:11:07 +0100 Subject: [PATCH 3/5] Fix brille integration. But segfaults at end --- pace_neutrons/FunctionWrapper.py | 62 ++++++++++++++++++++++ src/CMakeLists.txt | 1 + src/call.m | 22 +++++++- src/call_python.cpp | 2 +- src/matlab_overrides/+brille/create_bz.m | 2 +- src/matlab_overrides/+brille/create_grid.m | 8 ++- src/pyclasswrapper.m | 6 +-- 7 files changed, 92 insertions(+), 11 deletions(-) create mode 100644 pace_neutrons/FunctionWrapper.py diff --git a/pace_neutrons/FunctionWrapper.py b/pace_neutrons/FunctionWrapper.py new file mode 100644 index 0000000..0ea8d57 --- /dev/null +++ b/pace_neutrons/FunctionWrapper.py @@ -0,0 +1,62 @@ +import uuid +import numpy as np +import libpymcr + +_globalObjectsDict = {} + +def remove_object(object_string): + _globalObjectsDict.pop(object_string, None) + +def get_obj_prop(object_string, prop_name): + return getattr(_globalObjectsDict[object_string], prop_name) + +def call_obj_method(object_string, method_name, *args, **kwargs): + return getattr(_globalObjectsDict[object_string], method_name)(*args, **kwargs) + +libpymcr._globalFunctionDict['remove_object'] = remove_object +libpymcr._globalFunctionDict['get_obj_prop'] = get_obj_prop +libpymcr._globalFunctionDict['call_obj_method'] = call_obj_method + + +class WrappedPythonClass(object): + def __init__(self, input_class, typename='pyobj'): + self.target_class = input_class + self.typename = typename + + def __call__(self, *args, **kwargs): + args = [_globalObjectsDict[arg] if (isinstance(arg, str) and arg.startswith('pyobj')) else arg for arg in args] + kwargs = {ky:(_globalObjectsDict[val] if (isinstance(val, str) and val.startswith('pyobj')) else val) for ky, val in kwargs.items()} + input_object = self.target_class(*args, **kwargs) + obj_uuid = str(uuid.uuid4()) + key_string = self.typename + obj_uuid + _globalObjectsDict[key_string] = input_object + return key_string + +try: + from brille.utils import create_bz, create_grid +except ImportError: + pass +else: + wrapped_create_bz = WrappedPythonClass(create_bz, 'pyobj_bz') + wrapped_create_grid = WrappedPythonClass(create_grid, 'pyobj_grid') + libpymcr._globalFunctionDict['create_bz'] = wrapped_create_bz + libpymcr._globalFunctionDict['create_grid'] = wrapped_create_grid + def brille_grid_fill(objstr, *args): + # We have to do the reshape here because Matlab swallows singleton dims + args = list(args) + for idx in ([0, 2, 3, 5] if len(args) > 5 else [0, 2]): + shp = np.shape(args[idx]) + if len(shp) < 3: + args[idx] = np.reshape(args[idx], (shp[0], shp[1], 1)) + for idx in ([1, 4] if len(args) > 5 else [1, 3]): + args[idx] = np.reshape(args[idx], (np.prod(np.shape(args[idx])),)).astype('int32') + if len(args) % 2 == 1: + args[-1] = args[-1][0] + return getattr(_globalObjectsDict[objstr], 'fill')(*args) + libpymcr._globalFunctionDict['brille_grid_fill'] = brille_grid_fill + def brille_ir_interpolate_at(objstr, *args): + # Again we can't transpose in Matlab because brille needs a C-style array + hkl = args[0] if np.shape(args[0])[1] == 3 else np.transpose(args[0]) + kwargs = {args[idx]:args[idx+1] for idx in range(1, len(args), 2)} if len(args) > 1 else {} + return getattr(_globalObjectsDict[objstr], 'ir_interpolate_at')(hkl, **kwargs) + libpymcr._globalFunctionDict['brille_ir_interpolate_at'] = brille_ir_interpolate_at diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 43ab974..cc0884c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -41,6 +41,7 @@ add_custom_command( -a "${CMAKE_CURRENT_BINARY_DIR}/CTF" -a "${CMAKE_CURRENT_SOURCE_DIR}/matlab_overrides" "${CMAKE_CURRENT_SOURCE_DIR}/call.m" + "${CMAKE_CURRENT_SOURCE_DIR}/pyclasswrapper.m" "$/call_python.${Matlab_MEX_EXTENSION}" "${CMAKE_CURRENT_SOURCE_DIR}/pyhorace_init.m" ) diff --git a/src/call.m b/src/call.m index 60f69f2..c6a0239 100644 --- a/src/call.m +++ b/src/call.m @@ -131,7 +131,15 @@ end end fun_name = varargin{1}; - [kw_args, remaining_args] = get_kw_args(varargin(2:end)); + + if strncmp(varargin{2}, 'pyobj', 5) + [kw_args, remaining_args] = get_kw_args(varargin(3:end)); + remaining_args = [varargin(2) remaining_args]; + else + [kw_args, remaining_args] = get_kw_args(varargin(2:end)); + end + kw_args = unwrap_pyclass(kw_args); + remaining_args = unwrap_pyclass(remaining_args); if ~isempty(kw_args) remaining_args = [remaining_args {struct('pyHorace_pyKwArgs', 1, kw_args{:})}]; end @@ -141,6 +149,18 @@ end end +function input = unwrap_pyclass(input) + if iscell(input) + for ii = 1:numel(input) + input{ii} = unwrap_pyclass(input{ii}); + end + else + if isa(input, 'pyclasswrapper') + input = input.pyObjectString; + end + end +end + function [kw_args, remaining_args] = get_kw_args(args) % Finds the keyword arguments (string, val) pairs, assuming that they always at the end (last 2n items) first_kwarg_id = numel(args) + 1; diff --git a/src/call_python.cpp b/src/call_python.cpp index 46fc6c8..10ef7b2 100644 --- a/src/call_python.cpp +++ b/src/call_python.cpp @@ -34,7 +34,7 @@ class MexFunction : public matlab::mex::Function { PyGILState_STATE gstate = PyGILState_Ensure(); // GIL{ if (_converter == nullptr) { - _converter = new libpymcr::pymat_converter(); + _converter = new libpymcr::pymat_converter(libpymcr::pymat_converter::NumpyConversion::WRAP); } py::module pyHoraceFn = py::module::import("libpymcr"); diff --git a/src/matlab_overrides/+brille/create_bz.m b/src/matlab_overrides/+brille/create_bz.m index 72469ae..8118dea 100644 --- a/src/matlab_overrides/+brille/create_bz.m +++ b/src/matlab_overrides/+brille/create_bz.m @@ -3,7 +3,7 @@ methods % Constructor function obj = create_bz(varargin) - obj.pyObjectString = call_python_m('create_bz', varargin{:}); + obj.pyObjectString = call('_call_python', 'create_bz', varargin{:}); end end end diff --git a/src/matlab_overrides/+brille/create_grid.m b/src/matlab_overrides/+brille/create_grid.m index 80ffd9c..f125342 100644 --- a/src/matlab_overrides/+brille/create_grid.m +++ b/src/matlab_overrides/+brille/create_grid.m @@ -3,18 +3,16 @@ methods % Constructor function obj = create_grid(varargin) - obj.pyObjectString = call_python_m('create_grid', varargin{:}); + obj.pyObjectString = call('_call_python', 'create_grid', varargin{:}); obj.overrides = [obj.overrides {'fill', 'ir_interpolate_at'}]; end function out = fill(obj, varargin) % Ensures inputs are the correct type and shape. - call_python('brille_grid_fill', obj.pyObjectString, varargin{:}); + call('_call_python', 'brille_grid_fill', obj.pyObjectString, varargin{:}); out = []; end function [eigval, eigvec] = ir_interpolate_at(obj, varargin) - out = call_python('brille_ir_interpolate_at', obj.pyObjectString, varargin{:}); - eigval = out{1}{1}; - eigvec = out{2}{1}; + [eigval, eigvec] = call('_call_python', 'brille_ir_interpolate_at', obj.pyObjectString, varargin{:}); end end end diff --git a/src/pyclasswrapper.m b/src/pyclasswrapper.m index b1c0686..517964b 100644 --- a/src/pyclasswrapper.m +++ b/src/pyclasswrapper.m @@ -9,7 +9,7 @@ function delete(obj) if ~isempty(obj.pyObjectString) try %#ok - call_python('remove_object', obj.pyObjectString); + call('_call_python', 'remove_object', obj.pyObjectString); end end end @@ -23,9 +23,9 @@ function delete(obj) varargout = obj.(s(1).subs); end elseif numel(s) == 1 - varargout = call_python_m('get_obj_prop', obj.pyObjectString, s(1).subs); + varargout = call('_call_python', 'get_obj_prop', obj.pyObjectString, s(1).subs); elseif s(2).type == '()' - varargout = call_python_m('call_obj_method', obj.pyObjectString, s(1).subs, s(2).subs{:}); + varargout = call('_call_python', 'call_obj_method', obj.pyObjectString, s(1).subs, s(2).subs{:}); else error('Python class wrapper only supports calling direct methods'); end From 2ae0d5d1d134eeb44c3d699d7cf85e48eb440db1 Mon Sep 17 00:00:00 2001 From: Duc Le Date: Tue, 3 Oct 2023 13:51:41 +0100 Subject: [PATCH 4/5] Clean up unneeded files --- .gitignore | 1 + manylinux/README.md | 37 ------------------ manylinux/build_script.sh | 5 --- manylinux/install_script.sh | 31 --------------- manylinux/installation_key | 1 - manylinux/jenkins_build_script.sh | 5 --- manylinux/license.lic | 1 - manylinux/mac_address | 1 - pace_neutrons/__init__.py | 64 +++++++++++++++++++++++++++++++ setup.cfg | 3 ++ setup.py | 38 +++++++----------- src/type_converter.cpp | 9 ++--- 12 files changed, 86 insertions(+), 110 deletions(-) delete mode 100644 manylinux/README.md delete mode 100644 manylinux/build_script.sh delete mode 100755 manylinux/install_script.sh delete mode 100644 manylinux/installation_key delete mode 100755 manylinux/jenkins_build_script.sh delete mode 100644 manylinux/license.lic delete mode 100644 manylinux/mac_address create mode 100644 pace_neutrons/__init__.py diff --git a/.gitignore b/.gitignore index c484baf..8e4a16b 100644 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,7 @@ extern-pybind11 src/CTF build +buildctf dist wheelhouse diff --git a/manylinux/README.md b/manylinux/README.md deleted file mode 100644 index c48bc39..0000000 --- a/manylinux/README.md +++ /dev/null @@ -1,37 +0,0 @@ -# manylinux scripts - -[manylinux](https://github.com/pypa/manylinux) is a set of old docker containers based on CentOS -with modern compilers and Python installed whose aim is to allow to construction of binary wheels -which would be compatible across the widest range of linux system because they use system library -ABIs which are available for most systems in use. - -Because we need to use the Matlab compiler `mcc` in our builds we cannot use the stock -manylinux container images. -Also, Matlab activations are locked (on Linux) to particular MAC addresses so we need to be able -to set the MAC address of the image. -This cannot be done in a `Dockerfile` so instead we just run the container, install Matlab and -then do the build in one script (which unfortunately takes longer than if there was a -manylinux container with Matlab pre-installed). - -# Usage - -To use this you must first have a Matlab installable in the `install_dir` folder (currently empty). -You must first download a Matlab installation executable from your Mathworks account. -Then run it on a system with a GUI, and select "I want to download without installing" from the -"Advance options" menu on the top left. -Set the `install_dir` as the download folder and download the installation files. -Then return to your Mathworks webpage / account and select to "Activate to Retrieve License File" -putting in the Matlab version you had downloaded, and a MAC address. -This could be randomly generated or you can use a Docker standard address -(often `02:42:AC:11:00:02` is used if you've only run one container). -Put this MAC address in the file `mac_address`. -Put `root` as the user. -Then copy the file installation key to the file `installation_key` and the license file to `license.lic`. - -Then run this container with: - -``` -docker run --mac-address=$(cat mac_address) -v /mnt/hdd/docker/:/mnt quay.io/pypa/manylinux2010_x86_64 /mnt/installscript.sh -``` - -You can replace `manylinux2010_x86_64` with which other image you like. diff --git a/manylinux/build_script.sh b/manylinux/build_script.sh deleted file mode 100644 index dfbfd78..0000000 --- a/manylinux/build_script.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash - -git clone https://github.com/pace-neutrons/pace-python -cd pace-python -/opt/python/cp36-cp36m/bin/pip wheel . --no-deps diff --git a/manylinux/install_script.sh b/manylinux/install_script.sh deleted file mode 100755 index 89daf14..0000000 --- a/manylinux/install_script.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash - -MATLAB_VER=R2020a - -# Needed for mcc for some reason -yum install -y libXt - -cp -rpa install_dir tmp_install_dir -cp license.lic tmp_install_dir - -cat << EOF > tmp_install_dir/installer_input.txt -destinationFolder=/usr/local/MATLAB/${MATLAB_VER} -fileInstallationKey=$(cat installation_key) -agreeToLicense=yes -outputFile=`pwd`/install.log -licensePath=license.lic -product.MATLAB -product.MATLAB_Compiler -product.MATLAB_Compiler_SDK -EOF - -cd tmp_install_dir -./install -inputFile installer_input.txt -ln -s /usr/local/MATLAB/${MATLAB_VER}/bin/matlab /usr/local/bin/ -ln -s /usr/local/MATLAB/${MATLAB_VER}/bin/mcc /usr/local/bin/ - -# If you want to build an image from this container uncomment here -#tail -f /dev/null - -# If you want to build a set of wheels, uncomment here -./build_script.sh diff --git a/manylinux/installation_key b/manylinux/installation_key deleted file mode 100644 index 1ac7b5c..0000000 --- a/manylinux/installation_key +++ /dev/null @@ -1 +0,0 @@ -Please put your file installation key here diff --git a/manylinux/jenkins_build_script.sh b/manylinux/jenkins_build_script.sh deleted file mode 100755 index ce783cf..0000000 --- a/manylinux/jenkins_build_script.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -cd /mnt -/opt/python/cp37-cp37m/bin/pip wheel . --no-deps -/opt/python/cp36-cp36m/bin/pip wheel . --no-deps -find . -type f -iname "*-linux*.whl" -exec auditwheel repair '{}' \; diff --git a/manylinux/license.lic b/manylinux/license.lic deleted file mode 100644 index 4fcc714..0000000 --- a/manylinux/license.lic +++ /dev/null @@ -1 +0,0 @@ -Replace this file with your license file diff --git a/manylinux/mac_address b/manylinux/mac_address deleted file mode 100644 index 7855bed..0000000 --- a/manylinux/mac_address +++ /dev/null @@ -1 +0,0 @@ -02:42:AC:11:00:02 diff --git a/pace_neutrons/__init__.py b/pace_neutrons/__init__.py new file mode 100644 index 0000000..b33c31a --- /dev/null +++ b/pace_neutrons/__init__.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +from . import _version +__version__ = _version.get_versions()['version'] + +import os +import sys +import libpymcr + +from . import FunctionWrapper + +# Generate a list of all the MATLAB versions available +_VERSION_DIR = os.path.join(os.path.dirname(__file__), 'ctfs') +_VERSIONS = [] +for file in os.scandir(_VERSION_DIR): + if file.is_file() and file.name.endswith('.ctf'): + _VERSIONS.append({'file': os.path.join(_VERSION_DIR, file.name), + 'version': file.name.split('.')[0].split('_')[1] + }) + +_CALLPYTHON = None + +class Matlab(libpymcr.Matlab): + def __init__(self, matlab_path: Optional[str] = None, matlab_version: Optional[str] = None): + """ + Create a MATLAB instance with the correct compiled library for the MATLAB version specified. If no version is + specified, the first version found will be used. If no MATLAB versions are found, a RuntimeError will be + raised. If a version is specified, but not found, a RuntimeError will be raised. + + :param matlab_path: Path to the root directory of the MATLAB installation or MCR installation. + :param matlab_version: Used to specify the version of MATLAB if the matlab_path is given or if there is more + than 1 MATLAB installation. + """ + + initialized = False + if matlab_version is None: + for version in _VERSIONS: + if initialized: + break + try: + print(f"Trying MATLAB version: {version['version']} ({version['file']}))") + super().__init__(version['file'], mlPath=matlab_path) + initialized = True + except RuntimeError: + continue + else: + ctf = [version['file'] for version in _VERSIONS if version['version'].lower() == matlab_version.lower()] + if len(ctf) == 0: + raise RuntimeError( + f"Compiled library for MATLAB version {matlab_version} not found. Please use: [{', '.join([version['version'] for version in _VERSIONS])}]\n ") + else: + ctf = ctf[0] + try: + super().__init__(ctf, mlPath=matlab_path) + initialized = True + except RuntimeError: + pass + if not initialized: + raise RuntimeError( + f"No MATLAB versions found. Please use: [{', '.join([version['version'] for version in _VERSIONS])}]\n " + f"If installed, please specify the root directory (`matlab_path` and `matlab_version`) of the MATLAB " + f"installation.") + else: + self._interface.call('pyhorace_init', nargout=0) diff --git a/setup.cfg b/setup.cfg index 1e282ed..43753c1 100644 --- a/setup.cfg +++ b/setup.cfg @@ -4,3 +4,6 @@ style = pep440 versionfile_source = pace_neutrons/_version.py versionfile_build = pace_neutrons/_version.py tag_prefix = v + +[bdist_wheel] +universal = 1 diff --git a/setup.py b/setup.py index 73d3316..4034d08 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,7 @@ import os import re import sys +import glob import subprocess import pkgutil import shutil @@ -67,6 +68,7 @@ def __init__(self, name, sourcedir=''): if not os.path.isfile(os.path.join('euphonic_sqw_models', '__init__.py')): copy_euphonic_sqw_models() +CTFFILES = [] class CMakeBuild(build_ext): def run(self): @@ -82,6 +84,9 @@ def run(self): if cmake_version < '3.13.0': raise RuntimeError("CMake >= 3.13.0 is required") + if not os.path.isfile(os.path.join('euphonic_sqw_models', '__init__.py')): + copy_euphonic_sqw_models() + for ext in self.extensions: self.build_extension(ext) @@ -132,26 +137,13 @@ def build_extension(self, ext): check_call( [get_cmake(), '--build', '.'] + build_args, cwd=self.build_temp) - # shutil.copytree expects destination to not exist - outpath = os.path.join(self.build_lib, 'pace_neutrons', 'pace') - if os.path.isdir(outpath): - shutil.rmtree(outpath) - shutil.copytree(os.path.join(self.build_temp, 'bin', 'pace_neutrons', 'pace'), outpath) - for ff in ['requiredMCRProducts.txt', 'setup.py', 'readme.txt']: - shutil.copyfile(os.path.join(self.build_temp, 'bin', 'pace_neutrons', ff), - os.path.join(self.build_lib, 'pace_neutrons', ff)) - # Write the Matlab version - matlab_version = None - with open(os.path.join(self.build_temp, 'bin', 'pace_neutrons', - 'pace', '__init__.py'), 'r') as pace_init: - for line in pace_init: - if 'RUNTIME_VERSION_W_DOTS' in line: - matlab_version = line.split('=')[1].strip() - break - if matlab_version: - with open(os.path.join(self.build_lib, 'pace_neutrons_cli', - '_matlab_version.py'), 'w') as m_ver: - m_ver.write(f'RUNTIME_VERSION_W_DOTS = {matlab_version}\n') + outpath = os.path.join(self.build_lib, 'pace_neutrons', 'ctfs') + if not os.path.isdir(outpath): + os.mkdir(outpath) + inpath = os.path.join(self.build_temp, 'bin', 'pace_neutrons') + for ctffile in glob.glob(f'{inpath}/*ctf'): + shutil.copy(ctffile, outpath) + CTFFILES.append(os.path.join('ctfs', os.path.basename(ctffile))) with open("README.md", "r") as fh: @@ -172,10 +164,9 @@ def build_extension(self, ext): long_description_content_type="text/markdown", ext_modules=[CMakeExtension('pace_neutrons')], packages=['pace_neutrons', 'pace_neutrons_cli', 'euphonic_sqw_models'], - package_data={'pace_neutrons':['MCR_license.txt', 'requiredMCRProducts.txt', 'setup.py', - 'readme.txt', 'pace/__init__.py', 'pace/pace.ctf']}, + package_data={'pace_neutrons':CTFFILES}, install_requires = ['six>=1.12.0', 'numpy>=1.7.1', 'appdirs>=1.4.4', 'ipython>=3.2.1', 'requests', - 'matplotlib>=2.0.0', 'euphonic[phonopy_reader]>=0.6.2', 'brille>=0.5.4'], + 'matplotlib>=2.0.0', 'euphonic[phonopy_reader]>=0.6.2', 'brille>=0.5.4', 'libpymcr>=0.1.5'], extras_require = {'interactive':['matplotlib>=2.2.0',],}, cmdclass=cmdclass, entry_points={'console_scripts': [ @@ -189,7 +180,6 @@ def build_extension(self, ext): "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Operating System :: Microsoft :: Windows :: Windows 10", "Operating System :: POSIX :: Linux", - "Programming Language :: C++", "Programming Language :: Python :: 3", "Topic :: Scientific/Engineering :: Physics", ] diff --git a/src/type_converter.cpp b/src/type_converter.cpp index 7a570f8..4a9a65b 100644 --- a/src/type_converter.cpp +++ b/src/type_converter.cpp @@ -522,13 +522,12 @@ Array pymat_converter::listtuple_to_cell(PyObject *result, matlab::data::ArrayFa matlab::data::Array pymat_converter::wrap_python_function(PyObject *input, matlab::data::ArrayFactory &factory) { // Wraps a Python function so it can be called using a mex function matlab::data::Array rv; - std::uintptr_t addr = reinterpret_cast(input); + std::string addrstr = std::to_string(reinterpret_cast(input)); rv = factory.createStructArray({1, 1}, std::vector({"libpymcr_func_ptr"})); - const char* addrstr = std::to_string(addr).c_str(); py::module pyHoraceFn = py::module::import("libpymcr"); py::dict fnDict = pyHoraceFn.attr("_globalFunctionDict"); - PyDict_SetItemString(fnDict.ptr(), addrstr, input); - rv[0][std::string("libpymcr_func_ptr")] = factory.createCharArray(addrstr); + PyDict_SetItemString(fnDict.ptr(), addrstr.c_str(), input); + rv[0][std::string("libpymcr_func_ptr")] = factory.createCharArray(addrstr.c_str()); return rv; } @@ -554,7 +553,7 @@ matlab::data::Array pymat_converter::python_to_matlab_single(PyObject *input, ma } else if (PyComplex_Check(input)) { output = factory.createScalar(std::complex(PyComplex_RealAsDouble(input), PyComplex_ImagAsDouble(input))); } else if (input == Py_None) { - output = factory.createArray({}); + output = factory.createArray({0,0}); } else if (PyCallable_Check(input)) { output = wrap_python_function(input, factory); } else if (PyObject_TypeCheck(input, m_py_matlab_wrapper_t)) { From 4be86d229497506e40adfe1d2917be78bded67a2 Mon Sep 17 00:00:00 2001 From: Duc Le Date: Tue, 27 Feb 2024 23:39:08 +0000 Subject: [PATCH 5/5] Socket callback try 1 --- pace_neutrons/__init__.py | 68 +++++++++++++++++++++++++++++++++++++++ src/call.m | 26 +++++++++++++++ src/call_python.cpp | 7 ++++ 3 files changed, 101 insertions(+) diff --git a/pace_neutrons/__init__.py b/pace_neutrons/__init__.py index b33c31a..1137bc8 100644 --- a/pace_neutrons/__init__.py +++ b/pace_neutrons/__init__.py @@ -62,3 +62,71 @@ def __init__(self, matlab_path: Optional[str] = None, matlab_version: Optional[s f"installation.") else: self._interface.call('pyhorace_init', nargout=0) + if _CALLPYTHON is None: + _CALLPTYHON = CallPython() + self._callpython = _CALLPYTHON + + +import socketserver, threading + +class CallPythonHandler(socketserver.BaseRequestHandler): + def setup(self): + from libpymcr.Matlab import _global_matlab_ref + from libpymcr import _globalFunctionDict + if _global_matlab_ref is None: + raise RuntimeError('This class must be constructed after Matlab has been initialised') + self.interface = _global_matlab_ref.interface + self.fundict = _globalFunctionDict + + def handle(self): + data = self.request.recv(4096).decode() + print(data) + fun_name, idstr, haskw = data.split(',') + print(self.fundict) + #self.interface.call('evalin', 'base', 'whos', nargout=0) + print(f'|{fun_name}|') + try: + #args = self.interface.call('evalin', 'base', f'{idstr}_inp', nargout=1) + #args = self.interface.getvar(f'{idstr}_inp') + self.interface.getvar(f'{idstr}_inp') + #print(args) + #if haskw: + # #kwargs = self.interface.call('evalin', 'base', f'{idstr}_kw', nargout=1) + # kwargs = self.interface.getvar(f'{idstr}_kw') + # print(kwargs) + # out = self.fundict[fun_name](*args, **kwargs) + #else: + # out = self.fundict[fun_name](*args) + out = ('hello') + print(out) + #self.interface.call('assignin', 'base', f'{idstr}_out', out, nargout=0) + pstat = self.interface.putvar(f'{idstr}_out', out) + print(f'pstat = {pstat}') + except Exception as e: + self.request.sendall(e.message.encode()) + else: + self.request.sendall(b'Call completed') + + +class CallPython: + thread = None + server = None + + def __init__(self): + def serverlisten(): + if self.server is None: + self.server = socketserver.TCPServer(('localhost', 19999), CallPythonHandler) + self.server.serve_forever() + self.thread = threading.Thread(target=serverlisten) + self.thread.daemon = True + self.thread.start() + + def __del__(self): + if self.thread is None: + return + if self.server is not None: + self.server.server_close() + self.server = None + if sys.platform.startswith("linux") or sys.platform.startswith("darwin"): + self.thread.join() + self.thread = None diff --git a/src/call.m b/src/call.m index c6a0239..7747208 100644 --- a/src/call.m +++ b/src/call.m @@ -140,13 +140,39 @@ end kw_args = unwrap_pyclass(kw_args); remaining_args = unwrap_pyclass(remaining_args); +%{ if ~isempty(kw_args) remaining_args = [remaining_args {struct('pyHorace_pyKwArgs', 1, kw_args{:})}]; end out = call_python(fun_name, remaining_args{:}); + if ~iscell(out), out = {out}; end +%} + thisid = ['c' replace(char(java.util.UUID.randomUUID), '-', '')]; + assignin('base', [thisid '_inp'], remaining_args); + t = tcpclient('localhost', 19999); + evalc('disp(sprintf("%s,%s,", fun_name, thisid))'); + if ~isempty(kw_args) + assignin('base', [thisid '_kw'], kw_args); + t.write(uint8(sprintf('%s,%s,has_kwargs', fun_name, thisid))); + else + t.write(uint8(sprintf('%s,%s,', fun_name, thisid))); + end + while t.BytesAvailable == 0 + pause(0.2); + end + outstr = char(t.read()); + if ~strcmp(outstr, 'Call completed') + error(outstr); + end + out = evalin('base', [thisid '_out']); if ~iscell(out) out = {out}; end + evalin('base', ['clear ' thisid '_inp ' thisid '_out']); + if ~isempty(kw_args) + evalin('base', ['clear ' thisid '_kw']); + end + evalin('base', 'whos'); end function input = unwrap_pyclass(input) diff --git a/src/call_python.cpp b/src/call_python.cpp index 10ef7b2..8799847 100644 --- a/src/call_python.cpp +++ b/src/call_python.cpp @@ -24,6 +24,13 @@ class MexFunction : public matlab::mex::Function { } public: + ~MexFunction() { + if (_converter != nullptr) { + delete _converter; + _converter = nullptr; + } + } + void operator()(ArgumentList outputs, ArgumentList inputs) { matlab::data::ArrayFactory factory; if (inputs.size() < 1 || inputs[0].getType() != matlab::data::ArrayType::CHAR) {