|
| 1 | +#Copyright 2015-2018 MathWorks, Inc. |
| 2 | + |
| 3 | +# This template is used to generate an __init__.py file for a particular deployable package. |
| 4 | + |
| 5 | +""" Package for executing deployed MATLAB functions """ |
| 6 | + |
| 7 | +from __future__ import print_function |
| 8 | +import atexit |
| 9 | +import glob |
| 10 | +import importlib |
| 11 | +import os |
| 12 | +import os.path |
| 13 | +import pdb |
| 14 | +import platform |
| 15 | +import re |
| 16 | +import sys |
| 17 | +import weakref |
| 18 | + |
| 19 | +class _PathInitializer(object): |
| 20 | + PLATFORM_DICT = {'Windows': ['PATH','dll',''], 'Linux': ['LD_LIBRARY_PATH','so','libmw'], 'Darwin': ['DYLD_LIBRARY_PATH','dylib','libmw']} |
| 21 | + SUPPORTED_PYTHON_VERSIONS = ['2_7', '3_5', '3_6', '3_7'] |
| 22 | + RUNTIME_VERSION_W_DOTS = '9.6' |
| 23 | + RUNTIME_VERSION_W_UNDERSCORES = '9_6' |
| 24 | + PACKAGE_NAME = 'full_bayesian' |
| 25 | + |
| 26 | + def set_interpreter_version(self): |
| 27 | + """Make sure the interpreter version is supported.""" |
| 28 | + ver = sys.version_info |
| 29 | + version = '{0}_{1}'.format(ver[0], ver[1]) |
| 30 | + |
| 31 | + if version in _PathInitializer.SUPPORTED_PYTHON_VERSIONS: |
| 32 | + self.interpreter_version = version |
| 33 | + else: |
| 34 | + version_with_dot = version.replace("_", ".") |
| 35 | + raise EnvironmentError("Python {0} is not supported.".format(version_with_dot)) |
| 36 | + |
| 37 | + def __init__(self): |
| 38 | + """Initialize the variables.""" |
| 39 | + self.arch = '' |
| 40 | + self.is_linux = False |
| 41 | + self.is_mac = False |
| 42 | + self.is_windows = False |
| 43 | + self.mr_handle = None |
| 44 | + self.ml_handle = None |
| 45 | + self.system = '' |
| 46 | + self.cppext_handle = None |
| 47 | + |
| 48 | + # path to the folder that stores Python extensions and shared libraries |
| 49 | + self.bin_dir = '' |
| 50 | + |
| 51 | + # path to the folder that stores pure Python matlab_pysdk.runtime code (_runtime_dir) |
| 52 | + self.runtime_dir = '' |
| 53 | + |
| 54 | + # path to the folder that stores the pure Python matlab mlarray code used for type conversion |
| 55 | + self.ml_dir = '' |
| 56 | + |
| 57 | + self.set_interpreter_version() |
| 58 | + self.get_platform_info() |
| 59 | + |
| 60 | + this_folder = os.path.dirname(os.path.realpath(__file__)) |
| 61 | + self.path_file_name = os.path.join(this_folder, 'paths.{0}.txt'.format(self.arch)) |
| 62 | + |
| 63 | + self.instances_of_this_package = set([]) |
| 64 | + |
| 65 | + |
| 66 | + def read_path_file(self): |
| 67 | + """Look for a file that lists items to add to path. If present, read it and add the paths.""" |
| 68 | + filtered_lines = [] |
| 69 | + if os.path.isfile(self.path_file_name): |
| 70 | + pth_file = open(self.path_file_name, 'r') |
| 71 | + lines = pth_file.readlines() |
| 72 | + for line in lines: |
| 73 | + stripped_line = line.strip() |
| 74 | + if stripped_line and stripped_line[0] != '#': |
| 75 | + filtered_lines.append(stripped_line) |
| 76 | + length = len(filtered_lines) |
| 77 | + if length == 3: |
| 78 | + (bin_dir, runtime_dir, ml_dir) = filtered_lines |
| 79 | + if (not os.path.isdir(bin_dir)) or (not os.path.isdir(runtime_dir)) or (not os.path.isdir(ml_dir)): |
| 80 | + return False |
| 81 | + else: |
| 82 | + (self.bin_dir, self.runtime_dir, self.ml_dir) = (bin_dir, runtime_dir, ml_dir) |
| 83 | + return True |
| 84 | + else: |
| 85 | + return False |
| 86 | + |
| 87 | + def write_path_file(self): |
| 88 | + """Write a file that lists items to add to path. If present, it will be overwritten.""" |
| 89 | + existing_contents = '' |
| 90 | + if os.path.isfile(self.path_file_name): |
| 91 | + path_file = open(self.path_file_name, 'r') |
| 92 | + existing_contents = path_file.readlines() |
| 93 | + path_file.close() |
| 94 | + |
| 95 | + path_file = open(self.path_file_name, 'w') |
| 96 | + if self.system == 'Windows': |
| 97 | + print('# bin dir: added to both OS path and system path', file=path_file) |
| 98 | + else: |
| 99 | + print('# bin dir: added to system path', file=path_file) |
| 100 | + print(self.bin_dir, file=path_file) |
| 101 | + print('', file=path_file) |
| 102 | + |
| 103 | + print('# runtime dir: added to system path', file=path_file) |
| 104 | + print(self.runtime_dir, file=path_file) |
| 105 | + print('', file=path_file) |
| 106 | + |
| 107 | + print('# matlab (mlarray) dir: added to system path', file=path_file) |
| 108 | + print(self.ml_dir, file=path_file) |
| 109 | + print('', file=path_file) |
| 110 | + |
| 111 | + if existing_contents: |
| 112 | + print(existing_contents, file=path_file) |
| 113 | + path_file.close() |
| 114 | + |
| 115 | + def get_platform_info(self): |
| 116 | + """Ask Python for the platform and architecture.""" |
| 117 | + |
| 118 | + # This will return 'Windows', 'Linux', or 'Darwin' (for Mac). |
| 119 | + self.system = platform.system() |
| 120 | + if not self.system in _PathInitializer.PLATFORM_DICT: |
| 121 | + raise RuntimeError('{0} is not a supported platform.'.format(self.system)) |
| 122 | + else: |
| 123 | + # path_var is the OS-dependent name of the path variable ('PATH', 'LD_LIBRARY_PATH', "DYLD_LIBRARY_PATH') |
| 124 | + (self.path_var, self.ext, self.lib_prefix) = _PathInitializer.PLATFORM_DICT[self.system] |
| 125 | + |
| 126 | + if self.system == 'Windows': |
| 127 | + self.is_windows = True |
| 128 | + bit_str = platform.architecture()[0] |
| 129 | + if bit_str == '64bit': |
| 130 | + self.arch = 'win64' |
| 131 | + elif bit_str == '32bit': |
| 132 | + self.arch = 'win32' |
| 133 | + else: |
| 134 | + raise RuntimeError('{0} is not supported.'.format(bit_str)) |
| 135 | + elif self.system == 'Linux': |
| 136 | + self.is_linux = True |
| 137 | + self.arch = 'glnxa64' |
| 138 | + elif self.system == 'Darwin': |
| 139 | + self.is_mac = True |
| 140 | + self.arch = 'maci64' |
| 141 | + else: |
| 142 | + raise RuntimeError('Operating system {0} is not supported.'.format(self.system)) |
| 143 | + |
| 144 | + def get_paths_from_os(self): |
| 145 | + """ |
| 146 | + Look through the system path for a file whose name contains a runtime version |
| 147 | + corresponding to the one with which this package was produced. |
| 148 | + """ |
| 149 | + |
| 150 | + # Concatenates the pieces into a string. The double parentheses are necessary. |
| 151 | + if self.system == 'Windows': |
| 152 | + file_to_find = ''.join((self.lib_prefix, 'mclmcrrt', |
| 153 | + _PathInitializer.RUNTIME_VERSION_W_UNDERSCORES, '.', self.ext)) |
| 154 | + elif self.system == 'Linux': |
| 155 | + file_to_find = ''.join((self.lib_prefix, 'mclmcrrt', '.', self.ext, '.', |
| 156 | + _PathInitializer.RUNTIME_VERSION_W_DOTS)) |
| 157 | + elif self.system == 'Darwin': |
| 158 | + file_to_find = ''.join((self.lib_prefix, 'mclmcrrt', '.', |
| 159 | + _PathInitializer.RUNTIME_VERSION_W_DOTS, |
| 160 | + '.', self.ext)) |
| 161 | + else: |
| 162 | + raise RuntimeError('Operating system {0} is not supported.'.format(self.system)) |
| 163 | + |
| 164 | + path_elements = [] |
| 165 | + if self.path_var in os.environ: |
| 166 | + path_elements = os.environ[self.path_var].split(os.pathsep) |
| 167 | + if not path_elements: |
| 168 | + friendly_os_name = self.system |
| 169 | + if friendly_os_name == 'Darwin': |
| 170 | + friendly_os_name = 'Mac' |
| 171 | + raise RuntimeError('On {0}, you must set the environment variable "{1}" to a non-empty string. {2}'.format( |
| 172 | + friendly_os_name, self.path_var, 'For more details, see the package documentation.')) |
| 173 | + |
| 174 | + path_found = '' |
| 175 | + for elem in path_elements: |
| 176 | + filename = os.path.join(elem, file_to_find) |
| 177 | + if (os.path.isfile(filename)): |
| 178 | + path_found = elem |
| 179 | + break |
| 180 | + if not path_found: |
| 181 | + raise RuntimeError('Could not find an appropriate directory for MATLAB or the MATLAB runtime in {0}. Details: {1}'.format( |
| 182 | + self.path_var, file_to_find)) |
| 183 | + |
| 184 | + path_components = re.split(r'\\|/', path_found) |
| 185 | + |
| 186 | + if path_components[-1]: |
| 187 | + last_path_component = path_components[-1] |
| 188 | + else: |
| 189 | + # The directory name ended with a slash, so the last item in the list was an empty string. Go back one more. |
| 190 | + last_path_component = path_components[-2] |
| 191 | + |
| 192 | + if last_path_component != self.arch: |
| 193 | + output_str = ''.join(('To call deployed MATLAB code on a {0} machine, you must run a {0} version of Python, ', |
| 194 | + 'and your {1} variable must contain an element pointing to "<MR>{2}runtime{2}{0}", ', |
| 195 | + 'where "<MR>" indicates a MATLAB or MATLAB Runtime root. ', |
| 196 | + 'Instead, the value found was as follows: {3}')) |
| 197 | + raise RuntimeError(output_str.format(self.arch, self.path_var, os.sep, path_found)) |
| 198 | + |
| 199 | + matlabroot = os.path.dirname(os.path.dirname(os.path.normpath(path_found))) |
| 200 | + bin_dir = os.path.join(matlabroot, 'bin', self.arch) |
| 201 | + runtime_dir = os.path.join(matlabroot, 'toolbox', 'compiler_sdk', 'pysdk_py') |
| 202 | + ml_dir = os.path.join(runtime_dir, 'mlarray_dist') |
| 203 | + if not os.path.isdir(bin_dir): |
| 204 | + raise RuntimeError('Could not find the directory {0}'.format(bin_dir)) |
| 205 | + if not os.path.isdir(runtime_dir): |
| 206 | + raise RuntimeError('Could not find the directory {0}'.format(runtime_dir)) |
| 207 | + if not os.path.isdir(ml_dir): |
| 208 | + raise RuntimeError('Could not find the directory {0}'.format(ml_dir)) |
| 209 | + (self.bin_dir, self.runtime_dir, self.ml_dir) = (bin_dir, runtime_dir, ml_dir) |
| 210 | + |
| 211 | + def update_paths(self): |
| 212 | + """Update the OS and Python paths.""" |
| 213 | + |
| 214 | + #For Windows, add the bin_dir to the OS path. This is unnecessary |
| 215 | + #for Linux and Mac, where the OS can find this information via rpath. |
| 216 | + if self.is_windows: |
| 217 | + os.environ[self.path_var] = self.bin_dir + os.pathsep + os.environ[self.path_var] |
| 218 | + |
| 219 | + #Add all paths to the Python path. |
| 220 | + sys.path.insert(0, self.bin_dir) |
| 221 | + sys.path.insert(0, self.runtime_dir) |
| 222 | + sys.path.insert(0, self.ml_dir) |
| 223 | + |
| 224 | + def import_matlab_pysdk_runtime(self): |
| 225 | + """Import matlab_pysdk.runtime. Must be done after update_paths() and import_cppext() are called.""" |
| 226 | + try: |
| 227 | + self.mr_handle = importlib.import_module('matlab_pysdk.runtime') |
| 228 | + except Exception as e: |
| 229 | + raise e |
| 230 | + |
| 231 | + if not hasattr(self.mr_handle, '_runtime_version_w_dots'): |
| 232 | + raise RuntimeError('Runtime version of package ({0}) does not match runtime version of previously loaded package'.format( |
| 233 | + _PathInitializer.RUNTIME_VERSION_W_DOTS)) |
| 234 | + elif self.mr_handle._runtime_version_w_dots and (self.mr_handle._runtime_version_w_dots != _PathInitializer.RUNTIME_VERSION_W_DOTS): |
| 235 | + raise RuntimeError('Runtime version of package ({0}) does not match runtime version of previously loaded package ({1})'.format( |
| 236 | + _PathInitializer.RUNTIME_VERSION_W_DOTS, |
| 237 | + self.mr_handle._runtime_version_w_dots)) |
| 238 | + else: |
| 239 | + self.mr_handle._runtime_version_w_dots = _PathInitializer.RUNTIME_VERSION_W_DOTS |
| 240 | + |
| 241 | + self.mr_handle._cppext_handle = self.cppext_handle |
| 242 | + |
| 243 | + def import_matlab(self): |
| 244 | + """Import the matlab package. Must be done after Python system path contains what it needs to.""" |
| 245 | + try: |
| 246 | + self.ml_handle = importlib.import_module('matlab') |
| 247 | + except Exception as e: |
| 248 | + raise e |
| 249 | + |
| 250 | + def initialize_package(self): |
| 251 | + package_handle = self.mr_handle.DeployablePackage(self, self.PACKAGE_NAME, __file__) |
| 252 | + self.instances_of_this_package.add(weakref.ref(package_handle)) |
| 253 | + package_handle.initialize() |
| 254 | + return package_handle |
| 255 | + |
| 256 | + def initialize_runtime(self, option_list): |
| 257 | + if not self.cppext_handle: |
| 258 | + raise RuntimeError('Cannot call initialize_application before import_cppext.') |
| 259 | + if self.is_mac: |
| 260 | + ignored_option_found = False |
| 261 | + for option in option_list: |
| 262 | + if option in ('-nodisplay', '-nojvm'): |
| 263 | + ignored_option_found = True |
| 264 | + break |
| 265 | + if ignored_option_found: |
| 266 | + print('WARNING: Options "-nodisplay" and "-nojvm" are ignored on Mac.') |
| 267 | + print('They must be passed to mwpython in order to take effect.') |
| 268 | + self.cppext_handle.initializeApplication(option_list) |
| 269 | + |
| 270 | + def terminate_runtime(self): |
| 271 | + if not self.cppext_handle: |
| 272 | + raise RuntimeError('Cannot call terminate_application before import_cppext.') |
| 273 | + self.cppext_handle.terminateApplication() |
| 274 | + |
| 275 | + def import_cppext(self): |
| 276 | + self.cppext_handle = importlib.import_module("matlabruntimeforpython" + self.interpreter_version) |
| 277 | + |
| 278 | +try: |
| 279 | + _pir = _PathInitializer() |
| 280 | + _pir.get_paths_from_os() |
| 281 | + |
| 282 | + _pir.update_paths() |
| 283 | + _pir.import_cppext() |
| 284 | + _pir.import_matlab_pysdk_runtime() |
| 285 | + _pir.import_matlab() |
| 286 | +except Exception as e: |
| 287 | + print("Exception caught during initialization of Python interface. Details: {0}".format(e)) |
| 288 | + raise |
| 289 | + # We let the program exit normally. |
| 290 | + |
| 291 | +def initialize(): |
| 292 | + """ |
| 293 | + Initialize package and return a handle. |
| 294 | +
|
| 295 | + Initialize a package consisting of one or more deployed MATLAB functions. The return |
| 296 | + value is used as a handle on which any of the functions can be executed. To wait |
| 297 | + for all graphical figures to close before continuing, call wait_for_figures_to_close() |
| 298 | + on the handle. To close the package, call terminate(), quit() or exit() (which are |
| 299 | + synonymous) on the handle. The terminate() function is executed automatically when the |
| 300 | + script or session ends. |
| 301 | +
|
| 302 | + Returns |
| 303 | + handle - used to execute deployed MATLAB functions and to call terminate() |
| 304 | + """ |
| 305 | + return _pir.initialize_package() |
| 306 | + |
| 307 | +def initialize_runtime(option_list): |
| 308 | + """ |
| 309 | + Initialize runtime with a list of startup options. |
| 310 | +
|
| 311 | + Initialize the MATLAB Runtime with a list of startup options that will affect |
| 312 | + all packages opened within the script or session. If it is not called |
| 313 | + explicitly, it will be executed automatically, with an empty list of options, |
| 314 | + by the first call to initialize(). Do not call initialize_runtime() after |
| 315 | + calling initialize(). |
| 316 | +
|
| 317 | + There is no corresponding terminate_runtime() call. The runtime is terminated |
| 318 | + automatically when the script or session ends. |
| 319 | +
|
| 320 | + Parameters |
| 321 | + option_list - Python list of options; valid options are: |
| 322 | + -nodisplay (suppresses display functionality; Linux only) |
| 323 | + -nojvm (disables the Java Virtual Machine) |
| 324 | + """ |
| 325 | + if option_list: |
| 326 | + if not isinstance(option_list, list) and not isinstance(option_list, tuple): |
| 327 | + raise SyntaxError('initialize_runtime takes a list or tuple of strings.') |
| 328 | + _pir.initialize_runtime(option_list) |
| 329 | + |
| 330 | +# terminate_runtime() is intentionally omitted. Instead, when running interactively, |
| 331 | +# the user should call exit(). When running a script, the runtime will automatically be |
| 332 | +# terminated when the script ends. |
| 333 | + |
| 334 | +@atexit.register |
| 335 | +def __exit_packages(): |
| 336 | + for package in _pir.instances_of_this_package: |
| 337 | + if package() is not None: |
| 338 | + package().terminate() |
0 commit comments