Dmtlant commited on
Commit
5c5ce8c
·
verified ·
1 Parent(s): bfca1f5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -32
app.py CHANGED
@@ -4,6 +4,7 @@ import matplotlib.pyplot as plt
4
  import random
5
  from scipy.stats import entropy as scipy_entropy
6
  import time
 
7
 
8
  # --- НАСТРОЙКИ ---
9
  seqlen = 60
@@ -79,6 +80,69 @@ def compute_entropy(profile):
79
  st.title("🧬 Эволюция ДНК-подобной последовательности")
80
  st.markdown("Модель визуализирует мутации и анализирует структуру последовательности во времени.")
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  # Кнопка запуска симуляции
83
  if st.button("▶️ Запустить симуляцию"):
84
  seq = ''.join(random.choices(bases, k=seqlen))
@@ -98,36 +162,6 @@ if st.button("▶️ Запустить симуляцию"):
98
  stat_entropy.append(ent)
99
  acorr = compute_autocorr(torsion_profile)
100
 
101
- # Визуализация
102
- fig, axs = plt.subplots(3, 1, figsize=(10, 8))
103
- plt.subplots_adjust(hspace=0.45)
104
- lags_shown = 6
105
-
106
- axs[0].cla()
107
- axs[1].cla()
108
- axs[2].cla()
109
-
110
- axs[0].plot(torsion_profile, color='royalblue', label="Торсионный угол")
111
- for start, end, val in runs:
112
- axs[0].axvspan(start, end, color="red", alpha=0.3)
113
- axs[0].plot(range(start, end+1), torsion_profile[start:end+1], 'ro', markersize=5)
114
- axs[0].set_ylim(-200, 200)
115
- axs[0].set_xlabel("Позиция")
116
- axs[0].set_ylabel("Торсионный угол (град.)")
117
- axs[0].set_title(f"Шаг {step}: {seq}\nЧисло машин: {len(runs)}, энтропия: {ent:.2f}")
118
- axs[0].legend()
119
-
120
- axs[1].plot(stat_bist_counts, '-o', color='crimson', markersize=4)
121
- axs[1].set_xlabel("Шаг")
122
- axs[1].set_ylabel("Число машин")
123
- axs[1].set_ylim(0, max(10, max(stat_bist_counts)+1))
124
- axs[1].set_title("Динамика: число 'биомашин'")
125
-
126
- axs[2].bar(np.arange(lags_shown), acorr[:lags_shown], color='teal', alpha=0.7)
127
- axs[2].set_xlabel("Лаг")
128
- axs[2].set_ylabel("Автокорреляция")
129
- axs[2].set_title("Автокорреляция углового профиля (структурность) и энтропия")
130
- axs[2].text(0.70,0.70, f"Энтропия: {ent:.2f}", transform=axs[2].transAxes)
131
-
132
- plot_placeholder.pyplot(fig)
133
  time.sleep(0.5)
 
4
  import random
5
  from scipy.stats import entropy as scipy_entropy
6
  import time
7
+ import seaborn as sns
8
 
9
  # --- НАСТРОЙКИ ---
10
  seqlen = 60
 
80
  st.title("🧬 Эволюция ДНК-подобной последовательности")
81
  st.markdown("Модель визуализирует мутации и анализирует структуру последовательности во времени.")
82
 
83
+ # Функции для улучшения визуализации
84
+
85
+ def plot_density(runs, ax, steps):
86
+ machine_starts = [start for start, _, _ in runs]
87
+ machine_ends = [end for _, end, _ in runs]
88
+ timeline = np.zeros(steps)
89
+
90
+ for start, end, _ in runs:
91
+ timeline[start:end+1] = 1
92
+
93
+ sns.lineplot(x=np.arange(steps), y=timeline, ax=ax, color='darkgreen')
94
+ ax.set_title("Плотность биомашин по шагам")
95
+ ax.set_xlabel("Шаг")
96
+ ax.set_ylabel("Плотность биомашин")
97
+
98
+ def plot_heatmap(runs, ax, steps):
99
+ heatmap_matrix = np.zeros((steps, len(runs)))
100
+
101
+ for idx, (start, end, _) in enumerate(runs):
102
+ heatmap_matrix[start:end+1, idx] = 1
103
+
104
+ sns.heatmap(heatmap_matrix, ax=ax, cmap="YlGnBu", cbar=True)
105
+ ax.set_title("Тепловая карта: Распределение биомашин по времени")
106
+ ax.set_xlabel("Номер биомашины")
107
+ ax.set_ylabel("Шаг")
108
+
109
+ def update_visualization(step, seq, runs, torsion_profile, stat_bist_counts, acorr, steps, lags_shown, ent):
110
+ fig, axs = plt.subplots(5, 1, figsize=(10, 12))
111
+ plt.subplots_adjust(hspace=0.45)
112
+
113
+ axs[0].cla()
114
+ axs[1].cla()
115
+ axs[2].cla()
116
+ axs[3].cla()
117
+ axs[4].cla()
118
+
119
+ axs[0].plot(torsion_profile, color='royalblue', label="Торсионный угол")
120
+ for start, end, val in runs:
121
+ axs[0].axvspan(start, end, color="red", alpha=0.3)
122
+ axs[0].plot(range(start, end+1), torsion_profile[start:end+1], 'ro', markersize=5)
123
+ axs[0].set_ylim(-200, 200)
124
+ axs[0].set_xlabel("Позиция")
125
+ axs[0].set_ylabel("Торсионный угол (град.)")
126
+ axs[0].set_title(f"Шаг {step}: {seq}\nЧисло машин: {len(runs)}, энтропия: {ent:.2f}")
127
+ axs[0].legend()
128
+
129
+ plot_density(runs, axs[3], steps)
130
+ plot_heatmap(runs, axs[4], steps)
131
+
132
+ axs[1].plot(stat_bist_counts, '-o', color='crimson', markersize=4)
133
+ axs[1].set_xlabel("Шаг")
134
+ axs[1].set_ylabel("Число машин")
135
+ axs[1].set_ylim(0, max(10, max(stat_bist_counts)+1))
136
+ axs[1].set_title("Динамика: число 'биомашин'")
137
+
138
+ axs[2].bar(np.arange(lags_shown), acorr[:lags_shown], color='teal', alpha=0.7)
139
+ axs[2].set_xlabel("Лаг")
140
+ axs[2].set_ylabel("Автокорреляция")
141
+ axs[2].set_title("Автокорреляция углового профиля (структурность) и энтропия")
142
+ axs[2].text(0.70, 0.70, f"Энтропия: {ent:.2f}", transform=axs[2].transAxes)
143
+
144
+ plot_placeholder.pyplot(fig)
145
+
146
  # Кнопка запуска симуляции
147
  if st.button("▶️ Запустить симуляцию"):
148
  seq = ''.join(random.choices(bases, k=seqlen))
 
162
  stat_entropy.append(ent)
163
  acorr = compute_autocorr(torsion_profile)
164
 
165
+ # Обновление визуализаций
166
+ update_visualization(step, seq, runs, torsion_profile, stat_bist_counts, acorr, steps, 6, ent)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  time.sleep(0.5)