Naredi utezi.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import os
  4. import json
  5. import cModel
  6. import runSolver
  7. import importlib
  8. importlib.reload(cModel)
  9. importlib.reload(runSolver)
  10. # Load data
  11. def load_data(modelName, jobDir):
  12. Q = runSolver.loadSolutionFromDir(jobDir, True)
  13. return Q
  14. def print_lut_keys(Q):
  15. lut = Q['lut']
  16. # Debug information - removed print statements
  17. # print("Available keys in lut:")
  18. # for key in lut:
  19. # print(f"Key: {key}, Index: {lut[key]}")
  20. def plot_rbc_to_plasma_ratio(Q):
  21. lut = Q['lut']
  22. # Debug information - removed print statements
  23. # print("Available keys in lut:", lut.keys())
  24. # Example keys based on available compartments
  25. red_blood_cells_key = 'arterial'
  26. plasma_key = 'venous'
  27. if red_blood_cells_key not in lut or plasma_key not in lut:
  28. raise KeyError(f"Expected keys '{red_blood_cells_key}' or '{plasma_key}' are missing in 'lut'.")
  29. fy1 = Q['sol'][:, lut[red_blood_cells_key]]
  30. fy = Q['sol'][:, lut[plasma_key]]
  31. qy = fy1[1:] / fy[1:]
  32. t = Q['t']
  33. plt.plot(t[1:], qy)
  34. plt.xlabel('Time')
  35. plt.ylabel('RBC/Plasma Ratio')
  36. plt.title('RBC to Plasma Ratio Over Time')
  37. plt.show()
  38. # Parse model and retrieve parameters
  39. def parse_and_retrieve_parameters(modelFile, parameterFile):
  40. model = cModel.model()
  41. model.parse(modelFile, parameterFile)
  42. # Debug information - removed print statement
  43. # print('w(oI) {}'.format(model.getWeight('oralIngestion')))
  44. return model
  45. def calculate_derivatives_weights(model, sOut, lut, compartment):
  46. """
  47. Calculate derivatives and weights for a specific compartment and print sorted results.
  48. Parameters:
  49. - model: An instance of the model object
  50. - sOut: Simulation output data
  51. - lut: Look-up table (LUT) of compartments
  52. - compartment: The compartment for which to calculate derivatives and weights
  53. """
  54. try:
  55. # Compute derivatives for the specified compartment
  56. d = model.getDerivatives(sOut, lut[compartment])
  57. print(sOut)
  58. print(lut[compartment])
  59. # Retrieve the LUT for parameter indices and weights
  60. lutSE = model.lutSE # Accessing lutSE as an attribute
  61. w = model.getWeights(lutSE)
  62. print(lutSE)
  63. print(w)
  64. print(d)
  65. # Ensure the lengths of arrays match
  66. if len(lutSE) != len(d) or len(lutSE) != len(w):
  67. raise ValueError("Mismatch in lengths of LUT, derivatives, or weights.")
  68. # Calculate weighted derivatives
  69. s = {x: d[lutSE[x]] * w[lutSE[x]] for x in lutSE}
  70. s = dict(sorted(s.items(), key=lambda item: item[1], reverse=True))
  71. # Print the results
  72. print(f"Top 10 derivatives and weights for compartment '{compartment}':")
  73. for p in list(s)[:10]:
  74. j = lutSE[p]
  75. print(f'{p}: Weighted Derivative = {d[j] * w[j]:.2g} (Derivative = {d[j]:.2g}, Weight = {w[j]:.2g})')
  76. except AttributeError as e:
  77. print(f"Error accessing model methods or attributes: {e}")
  78. except ValueError as e:
  79. print(f"Value error: {e}")
  80. def retrieve_and_calculate_total_mass(model, setup):
  81. tscale = runSolver.getScale(setup)
  82. # Attempt to retrieve parameters with attribute checking
  83. blood_to_plasma_pc_scale = getattr(model, 'bloodToPlasmaPCscale', None)
  84. blood_volume = getattr(model, 'bloodVolume', None)
  85. # Print debug information
  86. if blood_to_plasma_pc_scale is not None:
  87. print(f'Blood to Plasma PC Scale: {blood_to_plasma_pc_scale}')
  88. else:
  89. print('Blood to Plasma PC Scale parameter is missing.')
  90. if blood_volume is not None:
  91. print(f'Blood Volume: {blood_volume}')
  92. else:
  93. print('Blood Volume parameter is missing.')
  94. return blood_to_plasma_pc_scale, blood_volume
  95. def main(): #PAZI MODEL in PArameter File morta bit ista!!!
  96. # Define job directory and model files
  97. jobDir = os.path.join(os.path.expanduser('~'), 'Documents', 'Sola', 'IJS', 'PBPK_public', 'cDiazepam1_IVP')
  98. modelFile = os.path.join(os.path.expanduser('~'), 'Documents', 'Sola', 'IJS', 'PBPK_public', 'models', 'cDiazepam.json')
  99. parameterFile = os.path.join(os.path.expanduser('~'), 'Documents', 'Sola', 'IJS', 'PBPK_public', 'models', 'cDiazepam_parameters.json')
  100. # Load data
  101. Q = load_data('cDiazepam1_IVP', jobDir)
  102. # Plot RBC to Plasma Ratio
  103. plot_rbc_to_plasma_ratio(Q)
  104. # Parse model and retrieve parameters
  105. model = parse_and_retrieve_parameters(modelFile, parameterFile)
  106. # Calculate derivatives and weights for 'kidney'
  107. compartment = 'kidney'
  108. calculate_derivatives_weights(model, Q['sOut'], Q['lut'], compartment)
  109. # Retrieve model and calculate total mass
  110. setup = Q['setup']
  111. retrieve_and_calculate_total_mass(model, setup)
  112. if __name__ == "__main__":
  113. main()