primerjava modela IVP z modelom Matrix solve.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import os
  4. import cModel
  5. import time
  6. import pdfkit
  7. import tempfile
  8. import runSolver
  9. import io
  10. import importlib
  11. # Primerjava obeh modelov in razlika obeh modelov
  12. # Če je venousInput":{"function":"venousInput"}, potem modela IVP pa Matrix_solve ne bosta enaka, ker je fora v A = P**T D P in to če je D= D(t) ne bo delovalo
  13. #run solver
  14. fh=os.path.expanduser('~') #Nastavitev poti in konfiguracijskih datotek
  15. importlib.reload(cModel)
  16. importlib.reload(runSolver)
  17. def getModel(solution, modelName):
  18. """
  19. Load and parse the model from the given solution dictionary using the modelName.
  20. """
  21. Q = solution[modelName] # Retrieve the solution dictionary for the specified model
  22. model = cModel.model() # Create an instance of the cModel class
  23. setupFile = Q['setup'] # Get the setup file path from the solution
  24. modelFile = Q['model'] # Get the model file path from the solution
  25. parameterFile = Q['parameters'] # Get the parameter file path from the solution
  26. print('modelFile: {} {}'.format(modelFile, os.path.isfile(modelFile))) # Print the model file path and its existence status
  27. print('parameterFile: {} {}'.format(parameterFile, os.path.isfile(parameterFile))) # Print the parameter file path and its existence status
  28. model.parse(modelFile, parameterFile) # Parse the model file with the given parameters
  29. return model # Return the loaded model
  30. def mergeSolutions(seq):
  31. """
  32. Merge multiple solution dictionaries into a single dictionary.
  33. """
  34. out = {}
  35. for v in ['t', 'sol', 'se', 'qt', 'sOut']: # Merge arrays from each solution
  36. out[v] = np.concatenate([x[v] for x in seq])
  37. for v in ['lut', 'lutSE', 'setup', 'model', 'parameters', 'qt', 'sOut']: # Use data from the last solution for these keys
  38. out[v] = seq[-1][v]
  39. return out # Return the merged dictionary
  40. def plot_results(solution, ivp_model_name, matrix_model_name, epsilon=1e-10):
  41. """
  42. Plot results for the specified IVP and matrix models, including their difference.
  43. """
  44. ivp_model = getModel(solution, ivp_model_name)
  45. matrix_model = getModel(solution, matrix_model_name)
  46. ivp_setup = solution[ivp_model_name]['setup']
  47. matrix_setup = solution[matrix_model_name]['setup']
  48. ivp_tscale = runSolver.getScale(ivp_setup)
  49. matrix_tscale = runSolver.getScale(matrix_setup)
  50. print(f'IVP tscale={ivp_tscale}')
  51. print(f'Matrix tscale={matrix_tscale}')
  52. name = ['venous', 'adipose', 'brain', 'heart', 'kidney', 'liver', 'lung', 'muscle', 'skin', 'stomach', 'splanchnic', 'excrement']
  53. tmax = solution[ivp_model_name]['t'][-1]
  54. compartment_max = [-1] * len(name) # Renamed variable to avoid conflict with built-in max function
  55. models = {
  56. ivp_model_name: {'color': 'yellow', 'shadeColor': 'gold'},
  57. matrix_model_name: {'color': 'blue', 'shadeColor': 'lightgreen', 'linestyle': '--'},
  58. 'Matrix-IVP': {'color': 'red', 'shadeColor': 'pink'}
  59. }
  60. fig, axs = plt.subplots(4, 3, figsize=(15, 20))
  61. for i in range(len(name)):
  62. row = i // 3
  63. col = i % 3
  64. ax = axs[row, col]
  65. for model_name in [ivp_model_name, matrix_model_name]:
  66. model = solution[model_name]
  67. v = name[i]
  68. try:
  69. j = model['lut'][v]
  70. except KeyError:
  71. try:
  72. v1 = alias[v]
  73. j = model['lut'][v1]
  74. except KeyError:
  75. print(f'No data for {v}/{v1}')
  76. continue
  77. fy = model['sol'][:, j]
  78. fe = model['se'][:, j]
  79. t = model['t']
  80. ax.plot(
  81. t / (ivp_tscale if model_name == ivp_model_name else matrix_tscale),
  82. fy,
  83. color=models[model_name]['color'],
  84. linestyle=models[model_name].get('linestyle', '-'), # Dodajmo slog črte za matriko
  85. label=f'{model_name} Mean'
  86. )
  87. ax.fill_between(
  88. t / (ivp_tscale if model_name == ivp_model_name else matrix_tscale),
  89. fy - fe, fy + fe,
  90. color=models[model_name]['shadeColor'],
  91. alpha=0.1
  92. )
  93. ax.plot(
  94. t / (ivp_tscale if model_name == ivp_model_name else matrix_tscale),
  95. fy - fe,
  96. color=models[model_name]['shadeColor'],
  97. linewidth=1,
  98. alpha=0.2
  99. )
  100. ax.plot(
  101. t / (ivp_tscale if model_name == ivp_model_name else matrix_tscale),
  102. fy + fe,
  103. color=models[model_name]['shadeColor'],
  104. linewidth=1,
  105. alpha=0.2
  106. )
  107. # Calculate and plot the difference of matrix and IVP
  108. try:
  109. ivp_fy = solution[ivp_model_name]['sol'][:, j]
  110. matrix_fy = solution[matrix_model_name]['sol'][:, j]
  111. difference = matrix_fy - ivp_fy
  112. difference_fe = np.sqrt(solution[matrix_model_name]['se'][:, j]**2 + solution[ivp_model_name]['se'][:, j]**2)
  113. ax.plot(
  114. t / ivp_tscale,
  115. difference,
  116. color=models['Matrix-IVP']['color'],
  117. label='Matrix - IVP Difference'
  118. )
  119. ax.fill_between(
  120. t / ivp_tscale,
  121. difference - difference_fe,
  122. difference + difference_fe,
  123. color=models['Matrix-IVP']['shadeColor'],
  124. alpha=0.1
  125. )
  126. ax.plot(
  127. t / ivp_tscale,
  128. difference - difference_fe,
  129. color=models['Matrix-IVP']['shadeColor'],
  130. linewidth=1,
  131. alpha=0.2
  132. )
  133. ax.plot(
  134. t / ivp_tscale,
  135. difference + difference_fe,
  136. color=models['Matrix-IVP']['shadeColor'],
  137. linewidth=1,
  138. alpha=0.2
  139. )
  140. except KeyError:
  141. print(f'No difference data for {name[i]}')
  142. if compartment_max[i] > 0:
  143. ax.set_ylim([0, compartment_max[i]])
  144. ax.set_xlim([0, 1.1 * tmax / ivp_tscale])
  145. ax.set_xlabel(ivp_setup['tUnit'])
  146. ax.set_title(name[i])
  147. ax.legend()
  148. output_file = os.path.join(fh, 'Documents', 'Sola', 'IJS', 'PBPK_public', 'results', 'combined_plot_matrix_ivp.png')
  149. plt.savefig(output_file)
  150. plt.show()
  151. def main():
  152. """
  153. Main function to load data, analyze model, and plot results.
  154. """
  155. fh = os.path.expanduser('~')
  156. # Define job configurations for loading
  157. job_configs = {
  158. 'cDiazepam_IVP': {
  159. 'jobDir': os.path.join(fh, 'Documents', 'Sola', 'IJS', 'PBPK_public', 'cDiazepam_IVP')
  160. },
  161. 'cDiazepam1_IVP': {
  162. 'jobDir': os.path.join(fh, 'Documents', 'Sola', 'IJS', 'PBPK_public', 'cDiazepam1_IVP')
  163. },
  164. 'cDiazepamF_IVP': {
  165. 'jobDir': os.path.join(fh, 'Documents', 'Sola', 'IJS', 'PBPK_public', 'cDiazepamF_IVP')
  166. },
  167. 'cDiazepamB_IVP': {
  168. 'jobDir': os.path.join(fh, 'Documents', 'Sola', 'IJS', 'PBPK_public', 'cDiazepamB_IVP')
  169. },
  170. 'cDiazepam_Matrix': {
  171. 'jobDir': os.path.join(fh, 'Documents', 'Sola', 'IJS', 'PBPK_public', 'cDiazepam_Matrix')
  172. },
  173. 'cDiazepam1_Matrix': {
  174. 'jobDir': os.path.join(fh, 'Documents', 'Sola', 'IJS', 'PBPK_public', 'cDiazepam1_Matrix')
  175. },
  176. 'cDiazepamF_Matrix': {
  177. 'jobDir': os.path.join(fh, 'Documents', 'Sola', 'IJS', 'PBPK_public', 'cDiazepamF_Matrix')
  178. },
  179. 'cDiazepamB_Matrix': {
  180. 'jobDir': os.path.join(fh, 'Documents', 'Sola', 'IJS', 'PBPK_public', 'cDiazepamB_Matrix')
  181. }
  182. }
  183. # Load and merge solutions
  184. solution = {}
  185. for modelName, job in job_configs.items():
  186. seq = [runSolver.loadSolutionFromDir(job['jobDir'], True)]
  187. solution[modelName] = mergeSolutions(seq)
  188. # Analyze and plot results
  189. for ivp_model_name in [name for name in job_configs if 'IVP' in name]:
  190. matrix_model_name = ivp_model_name.replace('IVP', 'Matrix')
  191. if matrix_model_name in job_configs:
  192. plot_results(solution,ivp_model_name, matrix_model_name)
  193. if __name__ == "__main__":
  194. main()