Update app.py
Browse files
app.py
CHANGED
@@ -1,127 +1,141 @@
|
|
|
|
1 |
import numpy as np
|
2 |
import matplotlib.pyplot as plt
|
3 |
-
import
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
def compute_autocorr(profile):
|
35 |
-
"""Автокорреляция – структурность, насколько повторяется рисунок"""
|
36 |
profile = profile - np.mean(profile)
|
37 |
result = np.correlate(profile, profile, mode='full')
|
38 |
-
|
39 |
-
|
|
|
40 |
|
41 |
def compute_entropy(profile):
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
axs
|
50 |
-
|
51 |
-
|
52 |
-
axs[
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
axs[0].
|
57 |
-
axs[0].
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
axs[1].
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
axs[2].
|
71 |
-
axs[2].set_title("
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
history.append(seq.copy())
|
95 |
-
if len(history) > HISTORY_LEN:
|
96 |
-
history.pop(0)
|
97 |
-
|
98 |
-
stable_regions = find_local_min_runs(seq)
|
99 |
-
stat_bist_counts.append(len(stable_regions))
|
100 |
-
stat_entropy.append(compute_entropy(seq))
|
101 |
-
stat_autocorr.append(compute_autocorr(seq))
|
102 |
st.session_state.step += 1
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
st.title("🧬 Стромбистный анализ торсионного поля")
|
107 |
-
col1, col2 = st.columns([1, 2])
|
108 |
-
|
109 |
-
with col1:
|
110 |
-
if st.button("🔁 Следующий шаг"):
|
111 |
-
update_step()
|
112 |
-
st.markdown(f"**Текущий шаг**: {st.session_state.step}")
|
113 |
-
st.markdown("**Стромбисты** — устойчивые участки структуры, подобные памяти или машинам.")
|
114 |
-
st.markdown("**Автокорреляция** — отражает повторяемость паттерна.")
|
115 |
-
st.markdown("**Энтропия** — мера хаоса.")
|
116 |
-
|
117 |
-
with col2:
|
118 |
-
fig, axs = plt.subplots(4, 1, figsize=(10, 10), sharex=True)
|
119 |
-
draw_world(
|
120 |
st.session_state.seq,
|
121 |
-
axs,
|
122 |
st.session_state.step,
|
123 |
-
st.session_state.
|
124 |
-
st.session_state.
|
125 |
-
st.session_state.
|
126 |
)
|
127 |
st.pyplot(fig)
|
|
|
|
|
|
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 |
+
from io import BytesIO
|
7 |
+
|
8 |
+
# --- НАСТРОЙКИ ---
|
9 |
+
seqlen = 60
|
10 |
+
steps = 120
|
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):
|
17 |
+
result = []
|
18 |
+
N = len(profile)
|
19 |
+
i = 0
|
20 |
+
while i < N:
|
21 |
+
run_val = profile[i]
|
22 |
+
run_length = 1
|
23 |
+
while i + run_length < N and profile[i + run_length] == run_val:
|
24 |
+
run_length += 1
|
25 |
+
if min_run <= run_length <= max_run:
|
26 |
+
result.append((i, i + run_length - 1, run_val))
|
27 |
+
i += run_length
|
28 |
+
return result
|
29 |
+
|
30 |
+
def bio_mutate(seq):
|
31 |
+
r = random.random()
|
32 |
+
if r < 0.70:
|
33 |
+
idx = random.randint(0, len(seq)-1)
|
34 |
+
orig = seq[idx]
|
35 |
+
prob = random.random()
|
36 |
+
if orig in 'AG':
|
37 |
+
newbase = 'C' if prob < 0.65 else random.choice(['T', 'C'])
|
38 |
+
elif orig in 'CT':
|
39 |
+
newbase = 'G' if prob < 0.65 else random.choice(['A', 'G'])
|
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 = seq[:seqlen]
|
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][::-1]
|
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 |
def compute_autocorr(profile):
|
|
|
70 |
profile = profile - np.mean(profile)
|
71 |
result = np.correlate(profile, profile, mode='full')
|
72 |
+
result = result[result.size // 2:]
|
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 |
+
def plot_step(seq, step, cnt_hist, ent_hist, ac_hist):
|
82 |
+
torsion_profile = np.array([ANGLE_MAP.get(nt, 0.0) for nt in seq])
|
83 |
+
runs = find_local_min_runs(torsion_profile, min_run, max_run)
|
84 |
+
fig, axs = plt.subplots(3, 1, figsize=(10, 8))
|
85 |
+
plt.subplots_adjust(hspace=0.45)
|
86 |
+
|
87 |
+
axs[0].plot(torsion_profile, color='royalblue', label="Торсионный угол")
|
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=5)
|
91 |
+
axs[0].set_ylim(-200, 200)
|
92 |
+
axs[0].set_xlabel("Позиция")
|
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 |
+
if 'seq' not in st.session_state:
|
116 |
+
st.session_state.seq = ''.join(random.choices(bases, k=seqlen))
|
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 |
+
if st.button("Следующий шаг мутации"):
|
123 |
+
st.session_state.seq = bio_mutate(st.session_state.seq)
|
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 |
+
if st.session_state.step > 0:
|
132 |
+
fig = plot_step(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
st.session_state.seq,
|
|
|
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("Нажмите кнопку, чтобы начать мутацию цепи и наблюдение за торсионными биомашинами.")
|