Update app.py
Browse files
app.py
CHANGED
@@ -2,15 +2,49 @@ 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 |
-
from io import BytesIO
|
7 |
|
8 |
# --- НАСТРОЙКИ ---
|
9 |
seqlen = 60
|
10 |
-
steps =
|
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 |
def find_local_min_runs(profile, min_run=1, max_run=2):
|
@@ -27,6 +61,18 @@ def find_local_min_runs(profile, min_run=1, max_run=2):
|
|
27 |
i += run_length
|
28 |
return result
|
29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
def bio_mutate(seq):
|
31 |
r = random.random()
|
32 |
if r < 0.70:
|
@@ -40,102 +86,64 @@ def bio_mutate(seq):
|
|
40 |
else:
|
41 |
newbase = random.choice([b for b in bases if b != orig])
|
42 |
seq = seq[:idx] + newbase + seq[idx+1:]
|
43 |
-
|
44 |
elif r < 0.80:
|
45 |
idx = random.randint(0, len(seq)-1)
|
46 |
ins = ''.join(random.choices(bases, k=random.randint(1, 3)))
|
47 |
seq = seq[:idx] + ins + seq[idx:]
|
48 |
-
seq
|
49 |
-
|
50 |
elif r < 0.90:
|
51 |
if len(seq) > 4:
|
52 |
idx = random.randint(0, len(seq)-2)
|
53 |
dell = random.randint(1, min(3, len(seq)-idx))
|
54 |
seq = seq[:idx] + seq[idx+dell:]
|
55 |
-
|
56 |
else:
|
57 |
if len(seq) > 10:
|
58 |
start = random.randint(0, len(seq)-6)
|
59 |
end = start + random.randint(3,6)
|
60 |
-
subseq = seq[start:end]
|
|
|
61 |
seq = seq[:start] + subseq + seq[end:]
|
62 |
-
|
63 |
while len(seq) < seqlen:
|
64 |
seq += random.choice(bases)
|
65 |
if len(seq) > seqlen:
|
66 |
seq = seq[:seqlen]
|
67 |
return seq
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
norm = np.max(result) if np.max(result)!=0 else 1
|
74 |
-
return result[:10]/norm
|
75 |
-
|
76 |
-
def compute_entropy(profile):
|
77 |
-
vals, counts = np.unique(profile, return_counts=True)
|
78 |
-
p = counts / counts.sum()
|
79 |
-
return scipy_entropy(p, base=2)
|
80 |
|
81 |
-
|
82 |
-
|
|
|
|
|
83 |
runs = find_local_min_runs(torsion_profile, min_run, max_run)
|
84 |
-
|
85 |
-
|
86 |
|
87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
for start, end, val in runs:
|
89 |
axs[0].axvspan(start, end, color="red", alpha=0.3)
|
90 |
-
axs[0].plot(range(start, end+1), torsion_profile[start:end+1], 'ro', markersize=
|
91 |
axs[0].set_ylim(-200, 200)
|
92 |
-
axs[0].
|
93 |
-
axs[0].set_ylabel("Торсионный угол (град.)")
|
94 |
-
axs[0].set_title(f"Шаг {step}: {seq}\nЧисло машин: {len(runs)}, энтропия: {ent_hist[-1]:.2f}")
|
95 |
-
axs[0].legend()
|
96 |
-
|
97 |
-
axs[1].plot(cnt_hist, '-o', color='crimson', markersize=4)
|
98 |
-
axs[1].set_xlabel("Шаг")
|
99 |
-
axs[1].set_ylabel("Число машин")
|
100 |
-
axs[1].set_ylim(0, max(10, max(cnt_hist)+1))
|
101 |
-
axs[1].set_title("Динамика: число 'биомашин'")
|
102 |
-
|
103 |
-
axs[2].bar(np.arange(6), ac_hist[-1][:6], color='teal', alpha=0.7)
|
104 |
-
axs[2].set_xlabel("Лаг")
|
105 |
-
axs[2].set_ylabel("Автокорреляция")
|
106 |
-
axs[2].set_title("Автокорреляция углового профиля и энтропия")
|
107 |
-
axs[2].text(0.70,0.70, f"Энтропия: {ent_hist[-1]:.2f}", transform=axs[2].transAxes)
|
108 |
-
|
109 |
-
return fig
|
110 |
-
|
111 |
-
# --- STREAMLIT ---
|
112 |
-
st.set_page_config(layout="wide")
|
113 |
-
st.title("\U0001F9EA Торсионное пространство биомашин")
|
114 |
|
115 |
-
|
116 |
-
|
117 |
-
st.session_state.cnt_hist = []
|
118 |
-
st.session_state.ent_hist = []
|
119 |
-
st.session_state.ac_hist = []
|
120 |
-
st.session_state.step = 0
|
121 |
|
122 |
-
|
123 |
-
|
124 |
-
profile = np.array([ANGLE_MAP.get(nt, 0.0) for nt in st.session_state.seq])
|
125 |
-
runs = find_local_min_runs(profile, min_run, max_run)
|
126 |
-
st.session_state.cnt_hist.append(len(runs))
|
127 |
-
st.session_state.ent_hist.append(compute_entropy(profile))
|
128 |
-
st.session_state.ac_hist.append(compute_autocorr(profile))
|
129 |
-
st.session_state.step += 1
|
130 |
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
st.session_state.step,
|
135 |
-
st.session_state.cnt_hist,
|
136 |
-
st.session_state.ent_hist,
|
137 |
-
st.session_state.ac_hist
|
138 |
-
)
|
139 |
-
st.pyplot(fig)
|
140 |
-
else:
|
141 |
-
st.info("Нажмите кнопку, чтобы начать мутацию цепи и наблюдение за торсионными биомашинами.")
|
|
|
2 |
import numpy as np
|
3 |
import matplotlib.pyplot as plt
|
4 |
import random
|
5 |
+
import time
|
6 |
from scipy.stats import entropy as scipy_entropy
|
|
|
7 |
|
8 |
# --- НАСТРОЙКИ ---
|
9 |
seqlen = 60
|
10 |
+
steps = 10000
|
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 |
+
lags_shown = 6
|
15 |
+
|
16 |
+
st.set_page_config(layout="wide")
|
17 |
+
st.title("🌌 Визуализация торсионных биомашин")
|
18 |
+
|
19 |
+
# --- ИНТЕРФЕЙС ---
|
20 |
+
col1, col2, col3 = st.columns([1,1,2])
|
21 |
+
with col1:
|
22 |
+
if 'running' not in st.session_state:
|
23 |
+
st.session_state.running = False
|
24 |
+
if st.button("▶️ Старт / ⏸ Стоп"):
|
25 |
+
st.session_state.running = not st.session_state.running
|
26 |
+
|
27 |
+
with col2:
|
28 |
+
if st.button("🔄 Сброс"):
|
29 |
+
st.session_state.running = False
|
30 |
+
st.session_state.step = 0
|
31 |
+
st.session_state.seq = ''.join(random.choices(bases, k=seqlen))
|
32 |
+
st.session_state.stat_bist_counts = []
|
33 |
+
st.session_state.stat_entropy = []
|
34 |
+
st.session_state.stat_autocorr = []
|
35 |
+
|
36 |
+
with col3:
|
37 |
+
speed = st.slider("⏱ Скорость обновления (мс)", 10, 1000, 200, step=10)
|
38 |
+
|
39 |
+
# --- ИНИЦИАЛИЗАЦИЯ ---
|
40 |
+
if 'seq' not in st.session_state:
|
41 |
+
st.session_state.seq = ''.join(random.choices(bases, k=seqlen))
|
42 |
+
if 'step' not in st.session_state:
|
43 |
+
st.session_state.step = 0
|
44 |
+
if 'stat_bist_counts' not in st.session_state:
|
45 |
+
st.session_state.stat_bist_counts = []
|
46 |
+
st.session_state.stat_entropy = []
|
47 |
+
st.session_state.stat_autocorr = []
|
48 |
|
49 |
# --- ФУНКЦИИ ---
|
50 |
def find_local_min_runs(profile, min_run=1, max_run=2):
|
|
|
61 |
i += run_length
|
62 |
return result
|
63 |
|
64 |
+
def compute_autocorr(profile):
|
65 |
+
profile = profile - np.mean(profile)
|
66 |
+
result = np.correlate(profile, profile, mode='full')
|
67 |
+
result = result[result.size // 2:]
|
68 |
+
norm = np.max(result) if np.max(result) != 0 else 1
|
69 |
+
return result[:10] / norm
|
70 |
+
|
71 |
+
def compute_entropy(profile):
|
72 |
+
vals, counts = np.unique(profile, return_counts=True)
|
73 |
+
p = counts / counts.sum()
|
74 |
+
return scipy_entropy(p, base=2)
|
75 |
+
|
76 |
def bio_mutate(seq):
|
77 |
r = random.random()
|
78 |
if r < 0.70:
|
|
|
86 |
else:
|
87 |
newbase = random.choice([b for b in bases if b != orig])
|
88 |
seq = seq[:idx] + newbase + seq[idx+1:]
|
|
|
89 |
elif r < 0.80:
|
90 |
idx = random.randint(0, len(seq)-1)
|
91 |
ins = ''.join(random.choices(bases, k=random.randint(1, 3)))
|
92 |
seq = seq[:idx] + ins + seq[idx:]
|
93 |
+
if len(seq) > seqlen:
|
94 |
+
seq = seq[:seqlen]
|
95 |
elif r < 0.90:
|
96 |
if len(seq) > 4:
|
97 |
idx = random.randint(0, len(seq)-2)
|
98 |
dell = random.randint(1, min(3, len(seq)-idx))
|
99 |
seq = seq[:idx] + seq[idx+dell:]
|
|
|
100 |
else:
|
101 |
if len(seq) > 10:
|
102 |
start = random.randint(0, len(seq)-6)
|
103 |
end = start + random.randint(3,6)
|
104 |
+
subseq = seq[start:end]
|
105 |
+
subseq = subseq[::-1]
|
106 |
seq = seq[:start] + subseq + seq[end:]
|
|
|
107 |
while len(seq) < seqlen:
|
108 |
seq += random.choice(bases)
|
109 |
if len(seq) > seqlen:
|
110 |
seq = seq[:seqlen]
|
111 |
return seq
|
112 |
|
113 |
+
# --- ВИЗУАЛИЗАЦИЯ ---
|
114 |
+
plot_area = st.empty()
|
115 |
+
fig, axs = plt.subplots(3, 1, figsize=(10, 8))
|
116 |
+
plt.subplots_adjust(hspace=0.5)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
117 |
|
118 |
+
# --- ЦИКЛ ВИЗУАЛИЗАЦИИ ---
|
119 |
+
while st.session_state.running:
|
120 |
+
st.session_state.seq = bio_mutate(st.session_state.seq)
|
121 |
+
torsion_profile = np.array([ANGLE_MAP.get(nt, 0.0) for nt in st.session_state.seq])
|
122 |
runs = find_local_min_runs(torsion_profile, min_run, max_run)
|
123 |
+
ent = compute_entropy(torsion_profile)
|
124 |
+
acorr = compute_autocorr(torsion_profile)
|
125 |
|
126 |
+
st.session_state.stat_bist_counts = st.session_state.stat_bist_counts[-50:] + [len(runs)]
|
127 |
+
st.session_state.stat_entropy = st.session_state.stat_entropy[-50:] + [ent]
|
128 |
+
st.session_state.stat_autocorr = st.session_state.stat_autocorr[-50:] + [acorr]
|
129 |
+
|
130 |
+
axs[0].cla()
|
131 |
+
axs[1].cla()
|
132 |
+
axs[2].cla()
|
133 |
+
|
134 |
+
axs[0].plot(torsion_profile, color='royalblue')
|
135 |
for start, end, val in runs:
|
136 |
axs[0].axvspan(start, end, color="red", alpha=0.3)
|
137 |
+
axs[0].plot(range(start, end+1), torsion_profile[start:end+1], 'ro', markersize=4)
|
138 |
axs[0].set_ylim(-200, 200)
|
139 |
+
axs[0].set_title(f"Шаг {st.session_state.step}: {st.session_state.seq}\nМашин: {len(runs)}, Энтропия: {ent:.2f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
+
axs[1].plot(st.session_state.stat_bist_counts, '-o', color='crimson', markersize=4)
|
142 |
+
axs[1].set_title("Число 'биомашин'")
|
|
|
|
|
|
|
|
|
143 |
|
144 |
+
axs[2].bar(np.arange(lags_shown), acorr[:lags_shown], color='teal')
|
145 |
+
axs[2].set_title("Автокорреляция углового профиля")
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
|
147 |
+
plot_area.pyplot(fig, clear_figure=True)
|
148 |
+
st.session_state.step += 1
|
149 |
+
time.sleep(speed / 1000.0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|