Mashetti A. answered 03/23/25
Expert Coding Tutor
import socket
import json
from pathlib import Path
import matlab.engine
def get_next_job() -> Path:
host = '127.0.0.1'
port = 2000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
s.sendall(json.dumps({"task_name": "next_simulation_file", "host_name": socket.gethostname()}).encode())
received = s.recv(1024)
message = json.loads(received.decode())
return Path(message["next_simulation_file"])
def run_matlab_simulation(matlab_file: Path, result_dir: Path):
# Start MATLAB engine
eng = matlab.engine.start_matlab()
# Change directory to the MATLAB file location
eng.cd(str(matlab_file.parent))
# Get the MATLAB file name without the extension
matlab_filename = matlab_file.stem
# Run the MATLAB file and save results
result_path = result_dir / f"{matlab_filename}_results.mat"
eng.eval(f"{matlab_filename}; save('{result_path}')", nargout=0)
print(f"Simulation completed. Results saved at: {result_path}")
# Stop MATLAB engine
eng.quit()
if __name__ == "__main__":
# Get the next MATLAB job file
matlab_file_path = get_next_job()
# Define the result storage directory
results_directory = Path("path/to/results") # Update this path accordingly
results_directory.mkdir(parents=True, exist_ok=True)
# Run MATLAB simulation
run_matlab_simulation(matlab_file_path, results_directory)