Dmtlant commited on
Commit
ab731e4
·
verified ·
1 Parent(s): 455c7bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -74
app.py CHANGED
@@ -1,33 +1,33 @@
1
- import streamlit as st
2
  import numpy as np
3
  import matplotlib.pyplot as plt
4
  import random
5
- from scipy.stats import entropy as scipy_entropy
6
- import time
7
- from datetime import datetime
8
 
9
- # --- ПАРАМЕТРЫ ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  seqlen = 60
11
- min_run, max_run = 1, 2
12
- ANGLE_MAP = {'A': 60.0, 'C': 180.0, 'G': -60.0, 'T': -180.0, 'N': 0.0}
13
  bases = ['A', 'C', 'G', 'T']
14
 
15
- # --- ФУНКЦИИ ---
16
-
17
- def find_local_min_runs(profile, min_run=1, max_run=2):
18
- result = []
19
- N = len(profile)
20
- i = 0
21
- while i < N:
22
- run_val = profile[i]
23
- run_length = 1
24
- while i + run_length < N and profile[i + run_length] == run_val:
25
- run_length += 1
26
- if min_run <= run_length <= max_run:
27
- result.append((i, i + run_length - 1, run_val))
28
- i += run_length
29
- return result
30
-
31
  def bio_mutate(seq):
32
  r = random.random()
33
  if r < 0.70:
@@ -62,29 +62,13 @@ def bio_mutate(seq):
62
  seq += random.choice(bases)
63
  return seq[:seqlen]
64
 
65
- def compute_autocorr(profile):
66
- profile = profile - np.mean(profile)
67
- result = np.correlate(profile, profile, mode='full')
68
- result = result[result.size // 2:]
69
- norm = np.max(result) if np.max(result) != 0 else 1
70
- return result[:10]/norm
71
-
72
- def compute_entropy(profile):
73
- vals, counts = np.unique(profile, return_counts=True)
74
- p = counts / counts.sum()
75
- return scipy_entropy(p, base=2)
76
-
77
- def compute_global_entropy(seq_history):
78
- """
79
- Вычисление глобальной энтропии на основе исторических последовательностей.
80
- """
81
- all_torsions = np.concatenate([np.array([ANGLE_MAP.get(nt, 0.0) for nt in seq]) for seq in seq_history])
82
- vals, counts = np.unique(all_torsions, return_counts=True)
83
- p = counts / counts.sum()
84
- return scipy_entropy(p, base=2)
85
-
86
  # --- UI ---
87
- st.title("🔴 Живой эфир мутаций ДНК")
 
 
 
 
 
88
  start = st.button("▶️ Старт эфира")
89
  stop = st.checkbox("⏹️ Остановить")
90
 
@@ -92,11 +76,9 @@ plot_placeholder = st.empty()
92
 
93
  if start:
94
  seq = ''.join(random.choices(bases, k=seqlen))
95
- seq_history = [seq] # История последовательностей для расчета глобальной энтропии
96
- stat_bist_counts = []
97
- stat_entropy = []
98
-
99
  step = 0
 
 
100
  while True:
101
  if stop:
102
  st.warning("⏹️ Эфир остановлен пользователем.")
@@ -104,39 +86,22 @@ if start:
104
 
105
  if step != 0:
106
  seq = bio_mutate(seq)
107
- seq_history.append(seq) # Добавляем в историю
108
 
109
- torsion_profile = np.array([ANGLE_MAP.get(nt, 0.0) for nt in seq])
110
- runs = find_local_min_runs(torsion_profile, min_run, max_run)
111
- stat_bist_counts.append(len(runs))
112
- ent = compute_entropy(torsion_profile)
113
- stat_entropy.append(ent)
114
- acorr = compute_autocorr(torsion_profile)
115
 
116
- # Вычисляем глобальную энтропию
117
- global_ent = compute_global_entropy(seq_history)
118
-
119
- fig, axs = plt.subplots(4, 1, figsize=(10, 10))
120
  plt.subplots_adjust(hspace=0.45)
121
 
122
  axs[0].plot(torsion_profile, color='royalblue')
123
- for start_, end_, val in runs:
124
- axs[0].axvspan(start_, end_, color="red", alpha=0.3)
125
- axs[0].set_ylim(-200, 200)
126
  axs[0].set_title(f"Шаг {step}: {seq}")
127
  axs[0].set_ylabel("Торсионный угол")
128
 
129
- axs[1].plot(stat_bist_counts, '-o', color='crimson', markersize=4)
130
- axs[1].set_ylabel("Биомашины")
131
- axs[1].set_title("Количество машин")
132
-
133
- axs[2].bar(np.arange(6), acorr[:6], color='teal')
134
- axs[2].set_title(f"Автокорреляция / Энтропия: {ent:.2f}")
135
- axs[2].set_xlabel("Лаг")
136
-
137
- axs[3].plot(stat_entropy, '-o', color='green', markersize=4)
138
- axs[3].set_title(f"Глобальная Энтропия: {global_ent:.2f}")
139
- axs[3].set_ylabel("Глобальная энтропия")
140
 
141
  plot_placeholder.pyplot(fig)
142
  plt.close(fig)
 
 
1
  import numpy as np
2
  import matplotlib.pyplot as plt
3
  import random
 
 
 
4
 
5
+ # Преобразование последовательности в фрактальные точки на основе торсионных углов
6
+ def sequence_to_torsion(seq):
7
+ ANGLE_MAP = {'A': 60.0, 'C': 180.0, 'G': -60.0, 'T': -180.0, 'N': 0.0}
8
+ return np.array([ANGLE_MAP.get(nt, 0.0) for nt in seq])
9
+
10
+ # Вычисление корреляционной размерности
11
+ def correlation_dimension(data, max_radius=20, min_points=5):
12
+ N = len(data)
13
+ dimensions = []
14
+ for radius in range(1, max_radius):
15
+ count = 0
16
+ for i in range(N):
17
+ for j in range(i + 1, N):
18
+ if np.abs(data[i] - data[j]) < radius:
19
+ count += 1
20
+ if count > min_points:
21
+ dimension = np.log(count) / np.log(radius)
22
+ dimensions.append(dimension)
23
+
24
+ return np.mean(dimensions) if dimensions else 0
25
+
26
+ # --- Основной код ---
27
+
28
  seqlen = 60
 
 
29
  bases = ['A', 'C', 'G', 'T']
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  def bio_mutate(seq):
32
  r = random.random()
33
  if r < 0.70:
 
62
  seq += random.choice(bases)
63
  return seq[:seqlen]
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  # --- UI ---
66
+
67
+ import streamlit as st
68
+ import time
69
+
70
+ st.title("🔴 Живой эфир мутаций ДНК с фрактальной размерностью")
71
+
72
  start = st.button("▶️ Старт эфира")
73
  stop = st.checkbox("⏹️ Остановить")
74
 
 
76
 
77
  if start:
78
  seq = ''.join(random.choices(bases, k=seqlen))
 
 
 
 
79
  step = 0
80
+ stat_fractal_dimension = []
81
+
82
  while True:
83
  if stop:
84
  st.warning("⏹️ Эфир остановлен пользователем.")
 
86
 
87
  if step != 0:
88
  seq = bio_mutate(seq)
 
89
 
90
+ torsion_profile = sequence_to_torsion(seq)
91
+ fractal_dim = correlation_dimension(torsion_profile)
92
+ stat_fractal_dimension.append(fractal_dim)
 
 
 
93
 
94
+ # Визуализация
95
+ fig, axs = plt.subplots(2, 1, figsize=(10, 8))
 
 
96
  plt.subplots_adjust(hspace=0.45)
97
 
98
  axs[0].plot(torsion_profile, color='royalblue')
 
 
 
99
  axs[0].set_title(f"Шаг {step}: {seq}")
100
  axs[0].set_ylabel("Торсионный угол")
101
 
102
+ axs[1].plot(stat_fractal_dimension, '-o', color='green', markersize=4)
103
+ axs[1].set_title(f"Фрактальная размерность: {fractal_dim:.3f}")
104
+ axs[1].set_xlabel("Шаг")
 
 
 
 
 
 
 
 
105
 
106
  plot_placeholder.pyplot(fig)
107
  plt.close(fig)