Update app.py
Browse files
app.py
CHANGED
@@ -1,109 +1,112 @@
|
|
1 |
import streamlit as st
|
2 |
-
|
3 |
-
import
|
4 |
-
|
5 |
-
import
|
6 |
-
import gc # Import garbage collection
|
7 |
|
8 |
-
#
|
9 |
-
|
10 |
-
|
|
|
|
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
"Guidance Scale:",
|
27 |
-
min_value=1.0,
|
28 |
-
max_value=15.0,
|
29 |
-
value=8.0,
|
30 |
-
step=0.5,
|
31 |
-
help="Насколько строго модель следует промпту"
|
32 |
-
)
|
33 |
-
|
34 |
-
lcm_origin_steps = st.slider(
|
35 |
-
"LCM Origin Steps:",
|
36 |
-
min_value=1,
|
37 |
-
max_value=50,
|
38 |
-
value=35
|
39 |
-
)
|
40 |
-
|
41 |
-
generate_button = st.button("Сгенерировать изображение")
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
num_inference_steps=steps,
|
62 |
-
guidance_scale=guidance,
|
63 |
-
lcm_origin_steps=lcm_steps,
|
64 |
-
output_type="pil"
|
65 |
-
).images
|
66 |
-
return images[0]
|
67 |
-
except Exception as e:
|
68 |
-
st.error(f"Error generating image: {e}")
|
69 |
-
return None
|
70 |
|
71 |
-
|
72 |
-
|
|
|
|
|
73 |
|
74 |
-
#
|
75 |
-
|
76 |
-
|
77 |
-
# Создаем место для вывода изображения
|
78 |
-
result_container = st.empty()
|
79 |
-
|
80 |
-
# Генерируем изображение
|
81 |
-
image = generate_image(
|
82 |
-
pipe,
|
83 |
-
prompt,
|
84 |
-
num_inference_steps,
|
85 |
-
guidance_scale,
|
86 |
-
lcm_origin_steps
|
87 |
-
)
|
88 |
-
|
89 |
-
# Показываем результат
|
90 |
-
if image: # Only display if image generation was successful
|
91 |
-
result_container.image(image, caption=f"Результат для: {prompt}", use_container_width=True) # Use use_container_width
|
92 |
-
|
93 |
-
# Предлагаем скачать
|
94 |
-
buf = io.BytesIO()
|
95 |
-
image.save(buf, format="PNG")
|
96 |
-
byte_im = buf.getvalue()
|
97 |
-
|
98 |
-
st.download_button(
|
99 |
-
label="Скачать изображение",
|
100 |
-
data=byte_im,
|
101 |
-
file_name="generated_image.png",
|
102 |
-
mime="image/png"
|
103 |
-
)
|
104 |
-
|
105 |
-
gc.collect() # Garbage collection after image generation
|
106 |
|
107 |
-
|
108 |
-
|
109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|
7 |
+
# Настройки
|
8 |
+
seqlen = 60
|
9 |
+
min_run, max_run = 1, 2
|
10 |
+
ANGLE_MAP = {'A': 60.0, 'C': 180.0, 'G': -60.0, 'T': -180.0, 'N': 0.0}
|
11 |
+
bases = ['A', 'C', 'G', 'T']
|
12 |
|
13 |
+
# --- Логика ---
|
14 |
+
def find_local_min_runs(profile, min_run=1, max_run=2):
|
15 |
+
result = []
|
16 |
+
N = len(profile)
|
17 |
+
i = 0
|
18 |
+
while i < N:
|
19 |
+
run_val = profile[i]
|
20 |
+
run_length = 1
|
21 |
+
while i + run_length < N and profile[i + run_length] == run_val:
|
22 |
+
run_length += 1
|
23 |
+
if min_run <= run_length <= max_run:
|
24 |
+
result.append((i, i + run_length - 1, run_val))
|
25 |
+
i += run_length
|
26 |
+
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
+
def bio_mutate(seq):
|
29 |
+
r = random.random()
|
30 |
+
if r < 0.70:
|
31 |
+
idx = random.randint(0, len(seq)-1)
|
32 |
+
orig = seq[idx]
|
33 |
+
prob = random.random()
|
34 |
+
if orig in 'AG':
|
35 |
+
newbase = 'C' if prob < 0.65 else random.choice(['T', 'C'])
|
36 |
+
elif orig in 'CT':
|
37 |
+
newbase = 'G' if prob < 0.65 else random.choice(['A', 'G'])
|
38 |
+
else:
|
39 |
+
newbase = random.choice([b for b in bases if b != orig])
|
40 |
+
seq = seq[:idx] + newbase + seq[idx+1:]
|
41 |
+
elif r < 0.80:
|
42 |
+
idx = random.randint(0, len(seq)-1)
|
43 |
+
ins = ''.join(random.choices(bases, k=random.randint(1, 3)))
|
44 |
+
seq = seq[:idx] + ins + seq[idx:]
|
45 |
+
seq = seq[:seqlen]
|
46 |
+
elif r < 0.90:
|
47 |
+
if len(seq) > 4:
|
48 |
+
idx = random.randint(0, len(seq)-2)
|
49 |
+
dell = random.randint(1, min(3, len(seq)-idx))
|
50 |
+
seq = seq[:idx] + seq[idx+dell:]
|
51 |
+
else:
|
52 |
+
if len(seq) > 10:
|
53 |
+
start = random.randint(0, len(seq)-6)
|
54 |
+
end = start + random.randint(3,6)
|
55 |
+
subseq = seq[start:end][::-1]
|
56 |
+
seq = seq[:start] + subseq + seq[end:]
|
57 |
+
while len(seq) < seqlen:
|
58 |
+
seq += random.choice(bases)
|
59 |
+
if len(seq) > seqlen:
|
60 |
+
seq = seq[:seqlen]
|
61 |
+
return seq
|
62 |
|
63 |
+
def compute_autocorr(profile):
|
64 |
+
profile = profile - np.mean(profile)
|
65 |
+
result = np.correlate(profile, profile, mode='full')
|
66 |
+
result = result[result.size // 2:]
|
67 |
+
norm = np.max(result) if np.max(result)!=0 else 1
|
68 |
+
return result[:10]/norm
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
+
def compute_entropy(profile):
|
71 |
+
vals, counts = np.unique(profile, return_counts=True)
|
72 |
+
p = counts / counts.sum()
|
73 |
+
return scipy_entropy(p, base=2)
|
74 |
|
75 |
+
# --- Streamlit UI ---
|
76 |
+
st.title("🧬 Эволюция ДНК-подобной цепи с мутациями")
|
77 |
+
steps = st.slider("Число шагов симуляции", 1, 200, 60)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
+
if st.button("▶️ Запустить симуляцию"):
|
80 |
+
seq = ''.join(random.choices(bases, k=seqlen))
|
81 |
+
stat_bist_counts = []
|
82 |
+
stat_entropy = []
|
83 |
+
stat_autocorr = []
|
84 |
+
|
85 |
+
fig, axs = plt.subplots(3, 1, figsize=(10, 8))
|
86 |
+
plt.subplots_adjust(hspace=0.45)
|
87 |
+
|
88 |
+
for i in range(steps):
|
89 |
+
torsion_profile = np.array([ANGLE_MAP.get(nt, 0.0) for nt in seq])
|
90 |
+
runs = find_local_min_runs(torsion_profile, min_run, max_run)
|
91 |
+
stat_bist_counts.append(len(runs))
|
92 |
+
stat_entropy.append(compute_entropy(torsion_profile))
|
93 |
+
stat_autocorr.append(compute_autocorr(torsion_profile))
|
94 |
+
seq = bio_mutate(seq)
|
95 |
+
|
96 |
+
# Отрисовка последнего состояния
|
97 |
+
axs[0].plot(torsion_profile, color='royalblue', label="Торсионный угол")
|
98 |
+
for start, end, val in runs:
|
99 |
+
axs[0].axvspan(start, end, color="red", alpha=0.3)
|
100 |
+
axs[0].plot(range(start, end+1), torsion_profile[start:end+1], 'ro', markersize=5)
|
101 |
+
axs[0].set_ylim(-200, 200)
|
102 |
+
axs[0].set_title(f"Шаг {steps}: {seq}\nЧисло машин: {len(runs)}, энтропия: {stat_entropy[-1]:.2f}")
|
103 |
+
axs[0].legend()
|
104 |
+
|
105 |
+
axs[1].plot(stat_bist_counts, '-o', color='crimson', markersize=4)
|
106 |
+
axs[1].set_title("Динамика: число 'биомашин'")
|
107 |
+
|
108 |
+
axs[2].bar(np.arange(6), stat_autocorr[-1][:6], color='teal', alpha=0.7)
|
109 |
+
axs[2].set_title("Автокорреляция и энтропия")
|
110 |
+
axs[2].text(0.7, 0.7, f"Энтропия: {stat_entropy[-1]:.2f}", transform=axs[2].transAxes)
|
111 |
+
|
112 |
+
st.pyplot(fig)
|