Dmtlant commited on
Commit
6c5a763
·
verified ·
1 Parent(s): ab731e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -39
app.py CHANGED
@@ -1,33 +1,38 @@
 
1
  import numpy as np
2
  import matplotlib.pyplot as plt
3
  import random
 
 
 
 
4
 
5
- # Преобразование последовательности в фрактальные точки на основе торсионных углов
6
- def sequence_to_torsion(seq):
7
- ANGLE_MAP = {'A': 60.0, 'C': 180.0, 'G': -60.0, 'T': -180.0, 'N': 0.0}
8
- return np.array([ANGLE_MAP.get(nt, 0.0) for nt in seq])
9
-
10
- # Вычисление корреляционной размерности
11
- def correlation_dimension(data, max_radius=20, min_points=5):
12
- N = len(data)
13
- dimensions = []
14
- for radius in range(1, max_radius):
15
- count = 0
16
- for i in range(N):
17
- for j in range(i + 1, N):
18
- if np.abs(data[i] - data[j]) < radius:
19
- count += 1
20
- if count > min_points:
21
- dimension = np.log(count) / np.log(radius)
22
- dimensions.append(dimension)
23
-
24
- return np.mean(dimensions) if dimensions else 0
25
-
26
- # --- Основной код ---
27
 
 
28
  seqlen = 60
 
 
29
  bases = ['A', 'C', 'G', 'T']
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  def bio_mutate(seq):
32
  r = random.random()
33
  if r < 0.70:
@@ -62,13 +67,38 @@ def bio_mutate(seq):
62
  seq += random.choice(bases)
63
  return seq[:seqlen]
64
 
65
- # --- UI ---
66
-
67
- import streamlit as st
68
- import time
69
-
70
- st.title("🔴 Живой эфир мутаций ДНК с фрактальной размерностью")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
 
 
72
  start = st.button("▶️ Старт эфира")
73
  stop = st.checkbox("⏹️ Остановить")
74
 
@@ -76,9 +106,11 @@ plot_placeholder = st.empty()
76
 
77
  if start:
78
  seq = ''.join(random.choices(bases, k=seqlen))
 
 
 
 
79
  step = 0
80
- stat_fractal_dimension = []
81
-
82
  while True:
83
  if stop:
84
  st.warning("⏹️ Эфир остановлен пользователем.")
@@ -87,22 +119,39 @@ if start:
87
  if step != 0:
88
  seq = bio_mutate(seq)
89
 
90
- torsion_profile = sequence_to_torsion(seq)
91
- fractal_dim = correlation_dimension(torsion_profile)
92
- stat_fractal_dimension.append(fractal_dim)
93
-
94
- # Визуализация
95
- fig, axs = plt.subplots(2, 1, figsize=(10, 8))
 
 
 
 
 
 
96
  plt.subplots_adjust(hspace=0.45)
97
 
98
  axs[0].plot(torsion_profile, color='royalblue')
 
 
 
99
  axs[0].set_title(f"Шаг {step}: {seq}")
100
  axs[0].set_ylabel("Торсионный угол")
101
 
102
- axs[1].plot(stat_fractal_dimension, '-o', color='green', markersize=4)
103
- axs[1].set_title(f"Фрактальная размерность: {fractal_dim:.3f}")
104
- axs[1].set_xlabel("Шаг")
 
 
 
 
105
 
 
 
 
 
106
  plot_placeholder.pyplot(fig)
107
  plt.close(fig)
108
 
 
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
+ import time
7
+ import imageio
8
+ from datetime import datetime
9
 
10
+ st.set_page_config(layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # --- ПАРАМЕТРЫ ---
13
  seqlen = 60
14
+ min_run, max_run = 1, 2
15
+ ANGLE_MAP = {'A': 60.0, 'C': 180.0, 'G': -60.0, 'T': -180.0, 'N': 0.0}
16
  bases = ['A', 'C', 'G', 'T']
17
 
18
+ # --- ФУНКЦИИ ---
19
+
20
+ # Функция для нахождения локальных минимумов (например, биомашин)
21
+ def find_local_min_runs(profile, min_run=1, max_run=2):
22
+ result = []
23
+ N = len(profile)
24
+ i = 0
25
+ while i < N:
26
+ run_val = profile[i]
27
+ run_length = 1
28
+ while i + run_length < N and profile[i + run_length] == run_val:
29
+ run_length += 1
30
+ if min_run <= run_length <= max_run:
31
+ result.append((i, i + run_length - 1, run_val))
32
+ i += run_length
33
+ return result
34
+
35
+ # Функция для мутации последовательности
36
  def bio_mutate(seq):
37
  r = random.random()
38
  if r < 0.70:
 
67
  seq += random.choice(bases)
68
  return seq[:seqlen]
69
 
70
+ # Функция для вычисления автокорреляции
71
+ def compute_autocorr(profile):
72
+ profile = profile - np.mean(profile)
73
+ result = np.correlate(profile, profile, mode='full')
74
+ result = result[result.size // 2:]
75
+ norm = np.max(result) if np.max(result) != 0 else 1
76
+ return result[:10]/norm
77
+
78
+ # Функция для вычисления энтропии
79
+ def compute_entropy(profile):
80
+ vals, counts = np.unique(profile, return_counts=True)
81
+ p = counts / counts.sum()
82
+ return scipy_entropy(p, base=2)
83
+
84
+ # Функция для вычисления фрактальной размерности (корреляционной размерности)
85
+ def correlation_dimension(data, max_radius=20, min_points=5):
86
+ N = len(data)
87
+ dimensions = []
88
+ for radius in range(1, max_radius):
89
+ count = 0
90
+ for i in range(N):
91
+ for j in range(i + 1, N):
92
+ if np.abs(data[i] - data[j]) < radius:
93
+ count += 1
94
+ if count > min_points and radius > 1:
95
+ dimension = np.log(count) / np.log(radius)
96
+ dimensions.append(dimension)
97
+
98
+ return np.mean(dimensions) if dimensions else 0
99
 
100
+ # --- UI ---
101
+ st.title("🔴 Живой эфир мутаций ДНК")
102
  start = st.button("▶️ Старт эфира")
103
  stop = st.checkbox("⏹️ Остановить")
104
 
 
106
 
107
  if start:
108
  seq = ''.join(random.choices(bases, k=seqlen))
109
+ stat_bist_counts = []
110
+ stat_entropy = []
111
+ stat_fractal = []
112
+
113
  step = 0
 
 
114
  while True:
115
  if stop:
116
  st.warning("⏹️ Эфир остановлен пользователем.")
 
119
  if step != 0:
120
  seq = bio_mutate(seq)
121
 
122
+ torsion_profile = np.array([ANGLE_MAP.get(nt, 0.0) for nt in seq])
123
+ runs = find_local_min_runs(torsion_profile, min_run, max_run)
124
+ stat_bist_counts.append(len(runs))
125
+ ent = compute_entropy(torsion_profile)
126
+ stat_entropy.append(ent)
127
+
128
+ acorr = compute_autocorr(torsion_profile)
129
+
130
+ fractal_dimension = correlation_dimension(torsion_profile)
131
+ stat_fractal.append(fractal_dimension)
132
+
133
+ fig, axs = plt.subplots(4, 1, figsize=(10, 10))
134
  plt.subplots_adjust(hspace=0.45)
135
 
136
  axs[0].plot(torsion_profile, color='royalblue')
137
+ for start_, end_, val in runs:
138
+ axs[0].axvspan(start_, end_, color="red", alpha=0.3)
139
+ axs[0].set_ylim(-200, 200)
140
  axs[0].set_title(f"Шаг {step}: {seq}")
141
  axs[0].set_ylabel("Торсионный угол")
142
 
143
+ axs[1].plot(stat_bist_counts, '-o', color='crimson', markersize=4)
144
+ axs[1].set_ylabel("Биомашины")
145
+ axs[1].set_title("Количество машин")
146
+
147
+ axs[2].bar(np.arange(6), acorr[:6], color='teal')
148
+ axs[2].set_title(f"Автокорреляция / Энтропия: {ent:.2f}")
149
+ axs[2].set_xlabel("Лаг")
150
 
151
+ axs[3].plot(stat_fractal, '-o', color='green', markersize=4)
152
+ axs[3].set_title("Фрактальная размерность")
153
+ axs[3].set_ylabel("Размерность")
154
+
155
  plot_placeholder.pyplot(fig)
156
  plt.close(fig)
157