pypharm 1.2.9__py3-none-any.whl → 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@ import random
2
2
  import numpy as np
3
3
  from operator import attrgetter
4
4
  from math import ceil, cos, sin
5
+ from multiprocessing import shared_memory
5
6
 
6
7
 
7
8
  class Individual:
@@ -350,7 +351,7 @@ class Country:
350
351
 
351
352
  class CountriesAlgorithm:
352
353
 
353
- def __init__(self, f, Xmin, Xmax, M, N, n, p, m, k, l, ep, tmax, printing=False):
354
+ def __init__(self, f, Xmin, Xmax, M, N, n, p, m, k, l, ep, tmax, printing=False, memory_list=None):
354
355
  self.f = f
355
356
  self.Xmin = Xmin
356
357
  self.Xmax = Xmax
@@ -363,6 +364,7 @@ class CountriesAlgorithm:
363
364
  self.tmax = tmax
364
365
  self.countries = []
365
366
  self.printing = printing
367
+ self.memory_list = memory_list
366
368
  for i in range(M):
367
369
  self.countries.append(Country(self.Xmin, self.Xmax, N, self.f))
368
370
 
@@ -372,6 +374,8 @@ class CountriesAlgorithm:
372
374
  trade = 0
373
375
  war = 0
374
376
  epedemic = 0
377
+ if self.memory_list is not None:
378
+ self.memory_list[0] = False
375
379
  while ti <= self.tmax:
376
380
  ti += 1
377
381
  for country in self.countries:
@@ -457,6 +461,12 @@ class CountriesAlgorithm:
457
461
  if self.printing:
458
462
  print(f"{ti}) Лучшее решение: {result.x} - {result.f}, Стран осталось: {len(self.countries)}, Движение/Обмен/Войны/Эпидемии: {motion}/{trade}/{war}/{epedemic}")
459
463
  print(f"Общее количество особей: {sum([len(country.population) for country in self.countries])}")
464
+
465
+ if self.memory_list is not None:
466
+ self.memory_list[0] = ti
467
+ for i in range(len(result.x)):
468
+ self.memory_list[i + 1] = float(result.x[i])
469
+ self.memory_list[-1] = float(result.f)
460
470
  return (result.x, result.f, False, ti)
461
471
 
462
472
 
PyPharm/models.py CHANGED
@@ -1,3 +1,5 @@
1
+ from multiprocessing import shared_memory
2
+
1
3
  import numpy as np
2
4
  from scipy.integrate import solve_ivp, RK45
3
5
  from scipy.integrate._ivp.rk import rk_step, SAFETY, MAX_FACTOR, MIN_FACTOR
@@ -16,7 +18,7 @@ class BaseCompartmentModel:
16
18
  _optim = False
17
19
  numba_option = False
18
20
 
19
- def __init__(self, configuration_matrix, outputs, volumes=None, numba_option=False):
21
+ def __init__(self, configuration_matrix, outputs, volumes=None, numba_option=False, use_shared_memory=False):
20
22
  """
21
23
  Базовая камерная модель для описания фармакокинетики системы
22
24
 
@@ -48,8 +50,18 @@ class BaseCompartmentModel:
48
50
  self.volumes_target_count = np.sum(self.volumes == None)
49
51
  self.last_result = None
50
52
  self.numba_option = numba_option
51
-
52
- def _сompartment_model(self, t, c):
53
+ self.use_shared_memory = use_shared_memory
54
+ if self.use_shared_memory:
55
+ self.memory_size = 2 + self.configuration_matrix_target_count + self.outputs_target_count + self.volumes_target_count
56
+ self.memory = shared_memory.ShareableList(self.memory_size * [None])
57
+ self.memory_name = self.memory.shm.name
58
+
59
+ def __del__(self):
60
+ if getattr(self, 'memory', None):
61
+ self.memory.shm.close()
62
+ self.memory.shm.unlink()
63
+
64
+ def _compartment_model(self, t, c):
53
65
  """
54
66
  Функция для расчета камерной модели
55
67
 
@@ -67,7 +79,7 @@ class BaseCompartmentModel:
67
79
 
68
80
  @staticmethod
69
81
  @njit
70
- def _numba_сompartment_model(t, c, configuration_matrix, outputs, volumes):
82
+ def _numba_compartment_model(t, c, configuration_matrix, outputs, volumes):
71
83
  """
72
84
  Функция для расчета камерной модели
73
85
 
@@ -110,7 +122,7 @@ class BaseCompartmentModel:
110
122
  c0 = np.array(c0)
111
123
  ts = [0, t_max]
112
124
  self.last_result = solve_ivp(
113
- fun=self._сompartment_model if not self.numba_option else lambda t, c: self._numba_сompartment_model(t, c, self.configuration_matrix.astype(np.float64), self.outputs.astype(np.float64), self.volumes.astype(np.float64)),
125
+ fun=self._compartment_model if not self.numba_option else lambda t, c: self._numba_compartment_model(t, c, self.configuration_matrix.astype(np.float64), self.outputs.astype(np.float64), self.volumes.astype(np.float64)),
114
126
  t_span=ts,
115
127
  y0=c0,
116
128
  max_step=max_step,
@@ -206,6 +218,7 @@ class BaseCompartmentModel:
206
218
  if method == 'country_optimization':
207
219
  CA = CountriesAlgorithm(
208
220
  f=f,
221
+ memory_list=getattr(self, 'memory', None),
209
222
  **kwargs
210
223
  )
211
224
  CA.start()
@@ -237,7 +250,7 @@ class BaseCompartmentModel:
237
250
  self._optim = False
238
251
  return x
239
252
 
240
- def plot_model(self, compartment_numbers=None, compartment_names={}, left=None, right=None, **kwargs):
253
+ def plot_model(self, compartment_numbers=None, compartment_names={}, left=None, right=None, y_lims={}, **kwargs):
241
254
  """
242
255
  Функция для построения графиков модели
243
256
 
@@ -252,10 +265,12 @@ class BaseCompartmentModel:
252
265
  self(**kwargs)
253
266
  for i in compartment_numbers:
254
267
  if hasattr(self, "teoretic_x") and hasattr(self, "teoretic_y") and i in self.know_compartments:
255
- plt.plot(self.teoretic_x, self.teoretic_y[i], "*r")
268
+ plt.plot(self.teoretic_x, self.teoretic_y[self.know_compartments.index(i)], "*r")
256
269
  plt.plot(self.last_result.t, self.last_result.y[i])
257
270
  plt.title(compartment_names.get(i, i))
258
271
  plt.xlim(left=left, right=right)
272
+ if y_lims.get(i):
273
+ plt.ylim(y_lims.get(i))
259
274
  plt.grid()
260
275
  plt.show()
261
276
 
@@ -264,11 +279,19 @@ class MagicCompartmentModel(BaseCompartmentModel):
264
279
 
265
280
  need_magic_optimization = False
266
281
 
267
- def __init__(self, configuration_matrix, outputs, volumes=None, magic_coefficient=1, exclude_compartments=[], numba_option=False):
268
- super().__init__(configuration_matrix, outputs, volumes, numba_option)
282
+ def __init__(self, configuration_matrix, outputs, volumes=None, magic_coefficient=1, exclude_compartments=[], numba_option=False, use_shared_memory=False):
283
+ super().__init__(configuration_matrix, outputs, volumes, numba_option, use_shared_memory)
269
284
  self.magic_coefficient = magic_coefficient
270
285
  self.exclude_compartments = np.array(exclude_compartments)
271
286
  self.need_magic_optimization = self.magic_coefficient is None
287
+ if getattr(self, "memory", None):
288
+ self.memory.shm.close()
289
+ self.memory.shm.unlink()
290
+ self.memory_size += int(self.need_magic_optimization)
291
+ self.memory = shared_memory.ShareableList(
292
+ sequence=self.memory_size * [None]
293
+ )
294
+ self.memory_name = self.memory.shm.name
272
295
 
273
296
  def __call__(self, t_max, c0=None, d=None, compartment_number=None, max_step=0.01, t_eval=None):
274
297
  if not self._optim and not self.magic_coefficient:
@@ -348,6 +371,15 @@ class ReleaseCompartmentModel(BaseCompartmentModel):
348
371
  self.release_compartment = release_compartment
349
372
  self.release_function = release_function
350
373
 
374
+ if getattr(self, "memory", None):
375
+ self.memory.shm.close()
376
+ self.memory.shm.unlink()
377
+ self.memory_size += self.release_parameters_target_count + int(self.need_v_release_optimization)
378
+ self.memory = shared_memory.ShareableList(
379
+ sequence=self.memory_size * [None]
380
+ )
381
+ self.memory_name = self.memory.shm.name
382
+
351
383
  def load_data_from_list(self, x):
352
384
  super().load_data_from_list(x)
353
385
  s = self.configuration_matrix_target_count + self.outputs_target_count + self.volumes_target_count
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pypharm
3
- Version: 1.2.9
3
+ Version: 1.3.0
4
4
  Summary: Module for solving pharmacokinetic problems
5
5
  Home-page: https://github.com/Krash13/PyPharm
6
6
  Author: Krash13
@@ -207,6 +207,22 @@ plt.show()
207
207
  в таком случае, искомое нужно просто задать как None. Тогда вектор неизвестных это
208
208
  x = [configuration_matrix (неизвестные), outputs(неизвестные), volumes(неизвестные), release_parameters(неизвестные), v_release]
209
209
 
210
+
211
+ **6) Использование shared_memory**
212
+
213
+ Начиная с версии 1.3.0, вы можете использовать **shared_memory** для получения текущих данных
214
+ оптимизации. Имя нужного вам участка памяти хранится в поле **memory_name**.
215
+
216
+ ```python
217
+ from multiprocessing import shared_memory
218
+
219
+ c = shared_memory.ShareableList(name='<your model.memory_name>')
220
+ print(c)
221
+ # ShareableList([4, 3.5192100752465563, 1.4158559227257506, 1.7264077213115414, 0.008336751860551, 0.2549196311342251, 0.5160375718404234, 6.915499993374695, 2.944744649331201, 0.5, 1.907294741996761], name='wnsm_0c50aa90')
222
+ ```
223
+
224
+ Данные хранятся в формате списка [текущая_итерация, x0, ... , xn, f], работает только для алгоритма country_optimization.
225
+
210
226
  **ENG documentation**
211
227
  ----------
212
228
 
@@ -397,3 +413,17 @@ The release_parameters and v_release parameters can be optimized
397
413
  in this case, you just need to set the desired value as None. Then the vector of unknowns is
398
414
  x = [configuration_matrix (unknown), outputs(unknown), volumes(unknown), release_parameters(unknown), v_release]
399
415
 
416
+ **6) Using shared_memory**
417
+
418
+ Since version 1.3.0, you can use **shared_memory** to get current data
419
+ optimization. The name of the memory location you need is stored in the **memory_name** field.
420
+ ```python
421
+ from multiprocessing import shared_memory
422
+
423
+ c = shared_memory.ShareableList(name='<your model.memory_name>')
424
+ print(c)
425
+ # ShareableList([4, 3.5192100752465563, 1.4158559227257506, 1.7264077213115414, 0.008336751860551, 0.2549196311342251, 0.5160375718404234, 6.915499993374695, 2.944744649331201, 0.5, 1.907294741996761], name='wnsm_0c50aa90')
426
+ ```
427
+
428
+ The data is stored in list format [current_iteration, x0, ... , xn, f], works only for the country_optimization algorithm.
429
+
@@ -0,0 +1,8 @@
1
+ PyPharm/__init__.py,sha256=hxhMRlWpLMARQV-ZNYkmvhQ9gCYI18an75vlySWjA6s,90
2
+ PyPharm/country_optimization.py,sha256=WsjfAWAWbxRnUUfBiMi1VatCSVbru7F1_G6kQBRVyA0,20452
3
+ PyPharm/country_optimization_v2.py,sha256=3d2mt15DXdr1V3soIJS51xuCv6uzH8pirah1RnI5--8,13156
4
+ PyPharm/models.py,sha256=Lhd_2EUtGQUrratvlqZ115zLeF9fFLDPI1gi-mzjv_o,25663
5
+ pypharm-1.3.0.dist-info/METADATA,sha256=cUh197fi8fP5x7Do-6Is-RpC2X-z6j8ZLo-ZkJOSTrU,14464
6
+ pypharm-1.3.0.dist-info/WHEEL,sha256=OqRkF0eY5GHssMorFjlbTIq072vpHpF60fIQA6lS9xA,92
7
+ pypharm-1.3.0.dist-info/top_level.txt,sha256=yybfSkKw8q1G3aEcnlfVL7_L9ufGFSAYZnpc7q6oYJk,8
8
+ pypharm-1.3.0.dist-info/RECORD,,
@@ -1,8 +0,0 @@
1
- PyPharm/__init__.py,sha256=hxhMRlWpLMARQV-ZNYkmvhQ9gCYI18an75vlySWjA6s,90
2
- PyPharm/country_optimization.py,sha256=nbg5kuJcOhMMfPR0_1O8KUzyqHApUcnqgs_I2I0Z1Gs,20008
3
- PyPharm/country_optimization_v2.py,sha256=3d2mt15DXdr1V3soIJS51xuCv6uzH8pirah1RnI5--8,13156
4
- PyPharm/models.py,sha256=6SRscPbPrIyKDlQk8WdtQW35GWWwk8rfm0V_QEVSs7c,24115
5
- pypharm-1.2.9.dist-info/METADATA,sha256=uOrCVB8X3Z8lw9DTGpn51D8lBLAyjbgQ0lz6umRiqZY,12910
6
- pypharm-1.2.9.dist-info/WHEEL,sha256=OqRkF0eY5GHssMorFjlbTIq072vpHpF60fIQA6lS9xA,92
7
- pypharm-1.2.9.dist-info/top_level.txt,sha256=yybfSkKw8q1G3aEcnlfVL7_L9ufGFSAYZnpc7q6oYJk,8
8
- pypharm-1.2.9.dist-info/RECORD,,