Skip to content

Commit 3a5095f

Browse files
Handle Matlab engine to remain open
1 parent f9161f2 commit 3a5095f

File tree

1 file changed

+24
-4
lines changed

1 file changed

+24
-4
lines changed

src/standardized/ASD_MemorialSloanKettering_QAMPER_IVIM.py

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,17 +44,17 @@ def __init__(self, bvalues=None, thresholds=None, bounds=None, initial_guess=Non
4444
#super(OGC_AmsterdamUMC_biexp, self).__init__(bvalues, bounds, initial_guess, fitS0)
4545
super(ASD_MemorialSloanKettering_QAMPER_IVIM, self).__init__(bvalues=bvalues, bounds=bounds, initial_guess=initial_guess)
4646
self.initialize(bounds, initial_guess)
47+
self.eng=matlab.engine.start_matlab()
48+
4749

4850
def algorithm(self,dwi_arr, bval_arr, LB0, UB0, x0in):
49-
eng = matlab.engine.start_matlab()
5051
dwi_arr = matlab.double(dwi_arr.tolist())
5152
bval_arr = matlab.double(bval_arr.tolist())
5253
LB0 = matlab.double(LB0.tolist())
5354
UB0 = matlab.double(UB0.tolist())
5455
x0in = matlab.double(x0in.tolist())
55-
f_arr, D_arr, Dx_arr, s0_arr, fitted_dwi_arr, RSS, rms_val, chi, AIC, BIC, R_sq = eng.IVIM_standard_bcin(
56+
f_arr, D_arr, Dx_arr, s0_arr, fitted_dwi_arr, RSS, rms_val, chi, AIC, BIC, R_sq = self.eng.IVIM_standard_bcin(
5657
dwi_arr, bval_arr, 0.0, LB0, UB0, x0in, False, 0, 0)
57-
eng.quit()
5858
return D_arr, f_arr, Dx_arr, s0_arr
5959

6060
def initialize(self, bounds, initial_guess):
@@ -94,4 +94,24 @@ def ivim_fit(self, signals, bvalues, **kwargs):
9494
results["f"] = fit_results[1]
9595
results["Dp"] = fit_results[2]
9696

97-
return results
97+
return results
98+
99+
100+
def __del__(self):
101+
if hasattr(self, "eng") and self.eng:
102+
try:
103+
self.eng.quit()
104+
except Exception as e:
105+
print(f"Warning: Failed to quit MATLAB engine cleanly: {e}")
106+
107+
108+
def __enter__(self):
109+
return self
110+
111+
112+
def __exit__(self, exc_type, exc_val, exc_tb):
113+
if hasattr(self, "eng") and self.eng:
114+
try:
115+
self.eng.quit()
116+
except Exception as e:
117+
print(f"Warning: Failed to quit MATLAB engine cleanly: {e}")

0 commit comments

Comments
 (0)