Hoaxx / app.py
Dmtlant's picture
Update app.py
6c5a763 verified
raw
history blame
5.55 kB
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import random
from scipy.stats import entropy as scipy_entropy
import time
import imageio
from datetime import datetime
st.set_page_config(layout="wide")
# --- ПАРАМЕТРЫ ---
seqlen = 60
min_run, max_run = 1, 2
ANGLE_MAP = {'A': 60.0, 'C': 180.0, 'G': -60.0, 'T': -180.0, 'N': 0.0}
bases = ['A', 'C', 'G', 'T']
# --- ФУНКЦИИ ---
# Функция для нахождения локальных минимумов (например, биомашин)
def find_local_min_runs(profile, min_run=1, max_run=2):
result = []
N = len(profile)
i = 0
while i < N:
run_val = profile[i]
run_length = 1
while i + run_length < N and profile[i + run_length] == run_val:
run_length += 1
if min_run <= run_length <= max_run:
result.append((i, i + run_length - 1, run_val))
i += run_length
return result
# Функция для мутации последовательности
def bio_mutate(seq):
r = random.random()
if r < 0.70:
idx = random.randint(0, len(seq)-1)
orig = seq[idx]
prob = random.random()
if orig in 'AG':
newbase = 'C' if prob < 0.65 else random.choice(['T', 'C'])
elif orig in 'CT':
newbase = 'G' if prob < 0.65 else random.choice(['A', 'G'])
else:
newbase = random.choice([b for b in bases if b != orig])
seq = seq[:idx] + newbase + seq[idx+1:]
elif r < 0.80:
idx = random.randint(0, len(seq)-1)
ins = ''.join(random.choices(bases, k=random.randint(1, 3)))
seq = seq[:idx] + ins + seq[idx:]
if len(seq) > seqlen:
seq = seq[:seqlen]
elif r < 0.90:
if len(seq) > 4:
idx = random.randint(0, len(seq)-2)
dell = random.randint(1, min(3, len(seq)-idx))
seq = seq[:idx] + seq[idx+dell:]
else:
if len(seq) > 10:
start = random.randint(0, len(seq)-6)
end = start + random.randint(3,6)
subseq = seq[start:end][::-1]
seq = seq[:start] + subseq + seq[end:]
while len(seq) < seqlen:
seq += random.choice(bases)
return seq[:seqlen]
# Функция для вычисления автокорреляции
def compute_autocorr(profile):
profile = profile - np.mean(profile)
result = np.correlate(profile, profile, mode='full')
result = result[result.size // 2:]
norm = np.max(result) if np.max(result) != 0 else 1
return result[:10]/norm
# Функция для вычисления энтропии
def compute_entropy(profile):
vals, counts = np.unique(profile, return_counts=True)
p = counts / counts.sum()
return scipy_entropy(p, base=2)
# Функция для вычисления фрактальной размерности (корреляционной размерности)
def correlation_dimension(data, max_radius=20, min_points=5):
N = len(data)
dimensions = []
for radius in range(1, max_radius):
count = 0
for i in range(N):
for j in range(i + 1, N):
if np.abs(data[i] - data[j]) < radius:
count += 1
if count > min_points and radius > 1:
dimension = np.log(count) / np.log(radius)
dimensions.append(dimension)
return np.mean(dimensions) if dimensions else 0
# --- UI ---
st.title("🔴 Живой эфир мутаций ДНК")
start = st.button("▶️ Старт эфира")
stop = st.checkbox("⏹️ Остановить")
plot_placeholder = st.empty()
if start:
seq = ''.join(random.choices(bases, k=seqlen))
stat_bist_counts = []
stat_entropy = []
stat_fractal = []
step = 0
while True:
if stop:
st.warning("⏹️ Эфир остановлен пользователем.")
break
if step != 0:
seq = bio_mutate(seq)
torsion_profile = np.array([ANGLE_MAP.get(nt, 0.0) for nt in seq])
runs = find_local_min_runs(torsion_profile, min_run, max_run)
stat_bist_counts.append(len(runs))
ent = compute_entropy(torsion_profile)
stat_entropy.append(ent)
acorr = compute_autocorr(torsion_profile)
fractal_dimension = correlation_dimension(torsion_profile)
stat_fractal.append(fractal_dimension)
fig, axs = plt.subplots(4, 1, figsize=(10, 10))
plt.subplots_adjust(hspace=0.45)
axs[0].plot(torsion_profile, color='royalblue')
for start_, end_, val in runs:
axs[0].axvspan(start_, end_, color="red", alpha=0.3)
axs[0].set_ylim(-200, 200)
axs[0].set_title(f"Шаг {step}: {seq}")
axs[0].set_ylabel("Торсионный угол")
axs[1].plot(stat_bist_counts, '-o', color='crimson', markersize=4)
axs[1].set_ylabel("Биомашины")
axs[1].set_title("Количество машин")
axs[2].bar(np.arange(6), acorr[:6], color='teal')
axs[2].set_title(f"Автокорреляция / Энтропия: {ent:.2f}")
axs[2].set_xlabel("Лаг")
axs[3].plot(stat_fractal, '-o', color='green', markersize=4)
axs[3].set_title("Фрактальная размерность")
axs[3].set_ylabel("Размерность")
plot_placeholder.pyplot(fig)
plt.close(fig)
step += 1
time.sleep(0.3)