Skip to content

Add setup_matlab -- not working yet #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions .github/workflows/test-setup-matlab.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: Test Setup Matlab

on:
workflow_dispatch:

jobs:
unit-tests:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: False
matrix:
os: [ubuntu-latest, macos-13, macos-latest, windows-latest]
python-version: ["3.9", "3.10", "3.11", "3.12"]
include:
- os: ubuntu-latest
os_name: Linux
platform: Linux
- os: macos-13
os_name: macOS_Intel
platform: Mac
- os: macos-latest
os_name: macOS_Apple_Silicon
platform: Mac
- os: windows-latest
os_name: Windows
platform: Windows
steps:
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}

- name: Check out SPM Python
uses: actions/checkout@v4

- name: Try to setup Matlab
shell: bash
run: |
cd scripts
python -m setup_matlab -d
200 changes: 200 additions & 0 deletions scripts/setup_matlab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import os
import os.path as op
import platform
import subprocess
import sys
import urllib.request
import zipfile
from itertools import product
import tempfile
import argparse


def add_matlab_to_path(matlab_version) -> bool:
"""Detect default MATLAB installation path based on the platform."""
system = platform.system().lower()

paths = [
'runtime',
'bin',
'sys/os',
'extern/bin',
]

if system == "windows":
variable = 'PATH'
bases = [
f"C:/Program Files/MATLAB/{matlab_version}",
f"C:/Program Files (x86)/MATLAB/{matlab_version}",
f"C:/Program Files/MATLAB/MATLAB Runtime/{matlab_version}",
f"C:/Program Files (x86)/MATLAB/MATLAB Runtime/{matlab_version}",
]
archs = ['win32', 'win64']

elif system == "darwin": # macOS
variable = 'DYLD_LIBRARY_PATH'
bases = [
f"/Applications/MATLAB_{matlab_version}",
f"/Applications/MATLAB_Runtime/{matlab_version}"
]

if platform.processor() == 'i386':
archs = ['maci64']
else:
archs = ['maca64']

elif system == "linux":
variable = 'LD_LIBRARY_PATH'
bases = [
f"/usr/local/MATLAB/{matlab_version}",
f"/usr/local/MATLAB/MATLAB_Runtime/{matlab_version}",
]
archs = ['glnxa64']

envpath = os.environ.get(variable, "")
found = False
for base, path in product(bases, paths):
# Check path existence
check_path = op.join(base, path)
if op.exists(check_path):
print(f"Found MATLAB Runtime at {check_path}.")
found = True
else:
continue

# Add to the environment variables
for arch in archs:
fullpath = op.join(check_path, arch)
if fullpath not in envpath:
envpath = f"{fullpath}{os.pathsep}{envpath}"

# Break
if found:
break


os.environ[variable] = envpath

return found


def try_import(module_name):
"""Try importing a module and return success status."""
try:
__import__(module_name)
return True
except ImportError:
return False

def download_matlab_runtime(system):
base_url = "https://github.com/spm/spm/releases/latest/download"

if system == "windows":
zip_name = 'spm_standalone_25.01.alpha42_Windows_matlab_runtime_installer.zip'

elif system == "darwin": # macOS

if platform.processor() == 'i386':
zip_name = 'spm_standalone_25.01.alpha42_macOS_Intel_matlab_runtime_installer.zip'
else:
zip_name = 'spm_standalone_25.01.alpha42_macOS_Apple_Silicon_matlab_runtime_installer.zip'

elif system == "linux":
zip_name = 'spm_standalone_25.01.alpha42_Linux_matlab_runtime_installer.zip'

runtime_url = op.join(base_url, zip_name)

dest_folder = tempfile.mkdtemp()

zip_file_path = op.join(dest_folder, zip_name)
print(f"Downloading MATLAB Runtime from {url}...")
urllib.request.urlretrieve(url, zip_file_path)

print("Extracting MATLAB Runtime...")
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
zip_ref.extractall(dest_folder)

installer_path = op.join(dest_folder, "runtime_installer")

return installer_path, dest_folder

def download_and_install_matlab_runtime(url, dest_folder):
"""Download and install MATLAB Runtime."""

system = platform.system().lower()

installer_path, dest_folder = download_matlab_runtime(system)

installer_file = os.listdir(installer_path)[0]

if system == "windows":
command = ['setup -agreeToLicense yes']
elif system == "darwin":
commands = [
f'open ./{installer_file} --args -agreeToLicense yes',
f'open ./{installer_file}'
]

elif system == "linux":
command = [f'sudo ./{installer_file} -agreeToLicense yes']

success = False
for command in commands:
try:
subprocess.check_call(command)
success = True
break

except PermissionError as e:
print(f"Permission error during installation: {e}")

except Exception as e:
print(f'Command {command} raised:\n')
print(e)

finally:
zip_file_path.unlink() # Clean up

return success

def setup_matlab_environment(download):
"""Main function to set up MATLAB or MATLAB Runtime."""
module_name = "spm"

# Try importing the module
if try_import(module_name):
return True

runtime_found = add_matlab_to_path('R2024b')

if runtime_found and try_import(module_name):
return True

if not download:
ans = input("MATLAB Runtime not found, do you want to download it? (y/n) ")

if ans.lower() != 'y':
raise ImportError(f"Failed to import {module_name}. Please check your setup.")

runtime_installed = download_and_install_matlab_runtime()

if not runtime_installed:
raise SystemError(f'Failed to install Matlab Runtime. Please try manually.')

runtime_found = add_matlab_to_path()

if runtime_found and try_import(module_name):
return True
else:
raise ImportError(f"Failed to import {module_name}. Please check your setup.")

if __name__ == "__main__":
parser = argparse.ArgumentParser(prog='setup_matlab')
parser.add_argument('-d', '--download-if-not-found', dest='download', action='store_true')
args = parser.parse_args()

result = setup_matlab_environment(args.download)
if result:
exit(0)
else:
exit(-1)
Loading