Dmtlant commited on
Commit
161a31c
·
verified ·
1 Parent(s): 411f3df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +127 -113
app.py CHANGED
@@ -1,127 +1,141 @@
 
1
  import numpy as np
2
  import matplotlib.pyplot as plt
3
- import streamlit as st
4
-
5
- # === Параметры модели ===
6
- SEQ_LEN = 100 # длина последовательности
7
- HISTORY_LEN = 200 # сколько шагов хранить в статистике
8
- JUMP = 10 # максимальный шаг изменения угла
9
- ENTROPY_BINS = 36 # шаг 10 градусов
10
-
11
- # === Инициализация состояния ===
12
- if "seq" not in st.session_state:
13
- st.session_state.seq = np.random.randint(-180, 180, size=SEQ_LEN)
14
- st.session_state.history = []
15
- st.session_state.bist_counts = []
16
- st.session_state.entropy = []
17
- st.session_state.autocorr = []
18
- st.session_state.step = 0
19
-
20
- # === Функции анализа ===
21
- def find_local_min_runs(profile, threshold=10):
22
- """Находит устойчивые участки ("машины"), где значения углов почти не меняются."""
23
- runs = []
24
- start = 0
25
- for i in range(1, len(profile)):
26
- if abs(profile[i] - profile[i - 1]) > threshold:
27
- if i - start > 2:
28
- runs.append((start, i - 1))
29
- start = i
30
- if len(profile) - start > 2:
31
- runs.append((start, len(profile) - 1))
32
- return runs
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
  def compute_autocorr(profile):
35
- """Автокорреляция – структурность, насколько повторяется рисунок"""
36
  profile = profile - np.mean(profile)
37
  result = np.correlate(profile, profile, mode='full')
38
- mid = len(result) // 2
39
- return result[mid + 1] / result[mid]
 
40
 
41
  def compute_entropy(profile):
42
- """Энтропия мера хаотичности, насколько случайна структура"""
43
- hist, _ = np.histogram(profile, bins=ENTROPY_BINS, range=(-180, 180), density=True)
44
- hist = hist[hist > 0]
45
- return -np.sum(hist * np.log2(hist))
46
-
47
- # === Функция отрисовки ===
48
- def draw_world(seq, axs, step, stat_bist_counts, stat_entropy, stat_autocorr):
49
- axs[0].cla()
50
- axs[1].cla()
51
- axs[2].cla()
52
- axs[3].cla()
53
-
54
- # Отображение профиля
55
- axs[0].plot(seq, label=f"Шаг {step}", color='skyblue')
56
- axs[0].set_title("Торсионный профиль (углы)")
57
- axs[0].set_ylim(-180, 180)
58
-
59
- # Визуальное выделение устойчивых "машин"
60
- stable_zones = find_local_min_runs(seq)
61
- for start, end in stable_zones:
62
- axs[0].axvspan(start, end, color='yellow', alpha=0.3)
63
- axs[0].text((start + end) // 2, 160, f'▲{end - start}', ha='center', va='center', fontsize=8, color='darkgreen')
64
-
65
- # График количества "стромбистов"
66
- axs[1].plot(stat_bist_counts, color='orchid')
67
- axs[1].set_title("Кол-во устойчивых машин (стромбистов)")
68
-
69
- # Энтропия
70
- axs[2].plot(stat_entropy, color='crimson')
71
- axs[2].set_title("Энтропия торсионного поля")
72
-
73
- # Автокорреляция
74
- axs[3].plot(stat_autocorr, color='seagreen')
75
- axs[3].set_title("Автокорреляция (память)")
76
-
77
- for ax in axs:
78
- ax.legend()
79
-
80
- # === Функция обновления ===
81
- def update_step():
82
- seq = st.session_state.seq
83
- history = st.session_state.history
84
- stat_bist_counts = st.session_state.bist_counts
85
- stat_entropy = st.session_state.entropy
86
- stat_autocorr = st.session_state.autocorr
87
- step = st.session_state.step
88
-
89
- # Случайная мутация
90
- i = np.random.randint(0, len(seq))
91
- delta = np.random.randint(-JUMP, JUMP + 1)
92
- seq[i] = (seq[i] + delta + 180) % 360 - 180
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
- # === Интерфейс Streamlit ===
105
- st.set_page_config(layout="wide")
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.bist_counts,
124
- st.session_state.entropy,
125
- st.session_state.autocorr
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("Нажмите кнопку, чтобы начать мутацию цепи и наблюдение за торсионными биомашинами.")