import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import segyio
import matplotlib.cm as cm
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_squared_error
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.callbacks import EarlyStopping
from mpl_toolkits.mplot3d import Axes3D
-------------- 1. Загрузка и предобработка данных --------------
print(f"После объединения осталось записей: {merged_df.shape[0]}")
-------------- 2. Загрузка и обработка SEGY данных --------------
with segyio.open(segy_path, "r", ignore_geometry=True) as seg:
# Извлечение inline и crossline атрибутов всей трассы
ilines = seg.attributes(segyio.TraceField.INLINE_3D)[:] # Извлечение inline
xlines = seg.attributes(segyio.TraceField.CROSSLINE_3D)[:] # Извлечение crossline
code
# Получение шага дискретизации времени в микросекундах
sample_rate_us = segyio.tools.dt(seg) # Шаг дискретизации в микросекундах
sample_rate_ms = sample_rate_us / 1000 # Преобразование в миллисекунды
print(f"Шаг дискретизации: {sample_rate_us} мкс ({sample_rate_ms} мс)")
first_trace = seg.trace[0]
num_samples = len(first_trace)
traces = np.array([tr for tr in seg.trace])
print(f"Количество сэмплов на трассу: {num_samples}")
print(f"Размер трассового массива: {traces.shape}")
Assistant
Создание словаря для быстрого поиска трасс по (inline, crossline)
il_xl_to_trace_idx = {}
for idx, (il, xl) in enumerate(zip(ilines, xlines)):
il_xl_to_trace_idx[(il, xl)] = idx
Инициализация списков для выбранных трасс и координат
selected_traces = []
selected_coords = []
print("Загрузка и нормализация необходимых трасс...")
for idx, row in merged_df.iterrows():
il = row['inline']
xl = row['crossline']
time_ms = row['time_ms']
code
# Находим индекс трассы в SEGY файле
trace_idx = il_xl_to_trace_idx.get((il, xl))
if trace_idx is None:
print(f"Трасса inline={il}, crossline={xl} не найдена в SEGY файле.")
continue
trace = traces[trace_idx]
# Определение окна выборки (30 дискретов по 2 мс = 60 мс)
window_size_samples = 30
half_window = window_size_samples // 2
center_sample = int(time_ms / sample_rate_ms)
start_sample = center_sample - half_window
end_sample = center_sample + half_window
trace_window = trace[start_sample:end_sample]
# Нормализация трассы по среднеквадратичной амплитуде
rms = np.sqrt(np.mean(trace_window**2))
trace_normalized = trace_window / rms
selected_traces.append(trace_normalized)
selected_coords.append((il, xl))
selected_traces = np.array(selected_traces)
selected_coords = np.array(selected_coords)
print(f"Выбранные и нормализованные трассы: {selected_traces.shape}") Задачи:
Загрузить сейсмические трассы из SEGY во временном интервале 60мс – 30 дискретов B. При загрузке трассы нормализовать на их среднеквадратичную амплитуду.
Преобразовать сейсмические трассы, используя МГК и автокодировщик. Каждую трассу из 30 дискретов требуется превратить в три значения.
Сформировать datasetы для обучения: первый должен в себя включать три главные компоненты и значение толщины горизонта, второй – три значения от автокодировщика и значение толщины.
Выполнить обучение для двух datasetов, используя метод ближайших соседей
Рассчитать прогнозные значения толщин
Программа должна на выходе выдать два 3d кроссплота, где по осям будут значения главных компонент и значения от автокодировщика, а точки закрашены значениями толщин горизонта. Помимо кроссплотов должны быть выведены сами карты plt.pcolormesh( cmap='jet')
plt.colorbar(label='Значение').
Certainly! Let's continue your seismic data processing pipeline by implementing the remaining tasks you've outlined. We'll perform the following steps:
Dimensionality Reduction:
Principal Component Analysis (PCA) to reduce each 30-sample trace to 3 principal components.
Autoencoder to learn a compressed 3-dimensional representation of each trace.
Dataset Preparation:
Create two datasets:
Dataset 1: Includes the three principal components and the corresponding thickness.
Dataset 2: Includes the three autoencoder components and the corresponding thickness.
Model Training:
Train two separate K-Nearest Neighbors (KNN) regressors on the respective datasets.
Prediction:
Use the trained models to predict thickness values.
Visualization:
Generate 3D scatter plots (crossplots) for both PCA and autoencoder components, colored by thickness.
Create pcolormesh maps to visualize the thickness distribution.
Let's implement each step in detail.
1. Dimensionality Reduction
1.1 Principal Component Analysis (PCA)
We'll use Scikit-learn's PCA to reduce each trace from 30 samples to 3 principal components.
python
# -------------- 3. Преобразование с помощью PCA --------------
# Инициализация PCA с 3 компонентами
pca = PCA(n_components=3)
pca_components = pca.fit_transform(selected_traces)
print(f"PCA components shape: {pca_components.shape}")
1.2 Autoencoder
We'll build a simple autoencoder using TensorFlow/Keras to compress each trace into 3-dimensional representations.
python
# -------------- 4. Преобразование с помощью автокодировщика --------------
from tensorflow.keras.optimizers import Adam
# Определение архитектуры автокодировщика
input_dim = selected_traces.shape[1] # 30
encoding_dim = 3
input_layer = Input(shape=(input_dim,))
# Энкодер
encoded = Dense(16, activation='relu')(input_layer)
encoded = Dense(8, activation='relu')(encoded)
encoded = Dense(encoding_dim, activation='relu')(encoded)
# Декодер
decoded = Dense(8, activation='relu')(encoded)
decoded = Dense(16, activation='relu')(decoded)
decoded = Dense(input_dim, activation='linear')(decoded)
# Создание модели автокодировщика
autoencoder = Model(inputs=input_layer, outputs=decoded)
encoder = Model(inputs=input_layer, outputs=encoded)
autoencoder.compile(optimizer=Adam(learning_rate=0.001), loss='mse')
# Обучение автокодировщика
early_stop = EarlyStopping(monitor='loss', patience=10, restore_best_weights=True)
autoencoder.fit(
selected_traces,
selected_traces,
epochs=100,
batch_size=32,
shuffle=True,
callbacks=[early_stop],
verbose=1
)
# Получение закодированных (сжимаемых) данных
autoencoder_components = encoder.predict(selected_traces)
print(f"Autoencoder components shape: {autoencoder_components.shape}")
2. Dataset Preparation
We'll create two separate datasets incorporating the PCA and autoencoder components along with the thickness values.
We'll create pcolormesh maps to visualize the thickness distribution. This requires spatial data (e.g., inline and crossline coordinates). We'll use inline and crossline as grid coordinates.
python
# Функция для создания pcolormesh карты
def plot_pcolormesh(inlines, xlines, thickness, title):
plt.figure(figsize=(12, 8))
# Создание сетки
grid_inline = np.unique(inlines)
grid_crossline = np.unique(xlines)
grid = thickness.reshape(len(grid_inline), len(grid_crossline))
# Создание карты
pcm = plt.pcolormesh(grid_crossline, grid_inline, grid, cmap='jet', shading='auto')
plt.title(title)
plt.xlabel('Crossline')
plt.ylabel('Inline')
plt.colorbar(pcm, label='Thickness')
plt.gca().invert_yaxis() # Инвертируем ось чтобы inline увеличивался сверху вниз
plt.show()
# Предполагаем, что selected_coords содержит (inline, crossline)
inlines_selected = selected_coords[:, 0]
xlines_selected = selected_coords[:, 1]
# Обученные модели прогнозов
# Для визуализации, будем использовать все данные (не только тестовые)
def get_full_predictions(knn, scaler, dataset, feature_cols):
X_full = dataset[feature_cols].values
X_full_scaled = scaler.transform(X_full)
y_full_pred = knn.predict(X_full_scaled)
return y_full_pred
# Прогнозы для PCA
thickness_pred_pca = get_full_predictions(knn_pca, scaler_pca, dataset_pca, ['PC1', 'PC2', 'PC3'])
# Прогнозы для Autoencoder
thickness_pred_ae = get_full_predictions(knn_ae, scaler_ae, dataset_ae, ['AE1', 'AE2', 'AE3'])
# Визуализация прогнозов PCA
plot_pcolormesh(
inlines_selected,
xlines_selected,
thickness_pred_pca,
'Predicted Thickness - PCA'
)
# Визуализация прогнозов Autoencoder
plot_pcolormesh(
inlines_selected,
xlines_selected,
thickness_pred_ae,
'Predicted Thickness - Autoencoder'
)
6. Полный Код
Для удобства вы можете объединить все части в один полный скрипт. Убедитесь, что все необходимые библиотеки установлены и данные правильно загружены.
python
The above code includes the initial data loading and preprocessing steps. Continuing from here, the following sections perform PCA, autoencoding, dataset preparation, model training, prediction, and visualization.
Note: Ensure that the data files (Cube.sgy, B, dh_dataset.txt) are correctly placed in the working directory and that their formats match the expected structure. Additionally, the autoencoder's architecture and hyperparameters (like the number of layers and neurons) can be tuned based on the specific characteristics of your data to achieve better performance.
If you encounter any issues or have further questions, feel free to ask!