Skip to content

Commit

Permalink
feat: change comments language and pylint workflow modify
Browse files Browse the repository at this point in the history
  • Loading branch information
lilpuzeen committed Jan 16, 2024
1 parent b3f1cb9 commit ce0b9df
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 104 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/pylint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10"]
python-version: ["3.11"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
Expand All @@ -20,4 +20,4 @@ jobs:
pip install pylint
- name: Analysing the code with pylint
run: |
pylint $(git ls-files '*.py')
pylint $(git ls-files '*.py') --max-line-length 121 --ignore-docstrings
180 changes: 91 additions & 89 deletions functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,106 +6,108 @@
from tensorflow.keras.optimizers import Adam


# Определение системы дифференциальных уравнений
# Definition of a system of differential equations
def system(y, t, a, b, c, d):
y1, y2 = y
dy1_dt = a * y1 + b * y2
dy2_dt = c * y1 + d * y2
return [dy1_dt, dy2_dt]
y1, y2 = y
dy1_dt = a * y1 + b * y2
dy2_dt = c * y1 + d * y2
return [dy1_dt, dy2_dt]


# Функция для расчета MSE
# Function for calculating MSE
def calculate_mse(y_true, y_pred):
return np.mean((y_true - y_pred) ** 2)
return np.mean((y_true - y_pred) ** 2)


# Определение модели NeuralODE для системы уравнений
# Definition of the NeuralODE model for the system of equations
def build_neural_ode_model_system():
input_y = Input(shape=(2,))
input_t = Input(shape=(1,))
combined_input = Concatenate()([input_y, input_t])
x = Dense(units=64, activation='relu')(combined_input)
x = Dense(units=64, activation='relu')(x)
x = Dense(units=64, activation='relu')(x)
output_a = Dense(units=1, name='output_a')(x)
output_b = Dense(units=1, name='output_b')(x)
output_c = Dense(units=1, name='output_c')(x)
output_d = Dense(units=1, name='output_d')(x)
model = Model(inputs=[input_y, input_t], outputs=[output_a, output_b, output_c, output_d])
return model
input_y = Input(shape=(2,))
input_t = Input(shape=(1,))
combined_input = Concatenate()([input_y, input_t])
x = Dense(units=64, activation='relu')(combined_input)
x = Dense(units=64, activation='relu')(x)
x = Dense(units=64, activation='relu')(x)
output_a = Dense(units=1, name='output_a')(x)
output_b = Dense(units=1, name='output_b')(x)
output_c = Dense(units=1, name='output_c')(x)
output_d = Dense(units=1, name='output_d')(x)
model = Model(inputs=[input_y, input_t], outputs=[output_a, output_b, output_c, output_d])
return model


neural_ode_model_system = build_neural_ode_model_system()
neural_ode_model_system.compile(optimizer='adam', loss='mse')


# Функция для проведения одного эксперимента
# Function for a single experiment
def conduct_experiment(a, b, c, d, experiment_id):
# Начальные условия для всех экспериментов
y0 = [1.0, 2.0]
time_points = np.linspace(0, 5, 100)

# Решение системы уравнений и добавление шума к данным
solution = odeint(system, y0, time_points, args=(a, b, c, d))
noise = np.random.normal(0, 0.5, solution.shape)
noisy_data = solution + noise

# Подготовка данных для обучения
X_train = [noisy_data, time_points.reshape(-1, 1)]
y_train = [np.full((len(time_points), 1), a), np.full((len(time_points), 1), b), np.full((len(time_points), 1), c),
np.full((len(time_points), 1), d)]

# Обучение модели
neural_ode_model_system.fit(X_train, y_train, epochs=200, verbose=1)

# Предсказание параметров
predicted_params = neural_ode_model_system.predict(X_train)

# Предсказанные параметры
predicted_a, predicted_b, predicted_c, predicted_d = [p.flatten()[0] for p in predicted_params]

# Вывод результатов
print(f"Эксперимент {experiment_id}:")
print("Истинные параметры:", [a, b, c, d])
print("Предсказанные параметры (с шумом):", [predicted_a, predicted_b, predicted_c, predicted_d])

# Предсказание параметров на основе истинных данных (без шума)
predicted_params_clean = neural_ode_model_system.predict([solution, time_points.reshape(-1, 1)])
predicted_a_clean, predicted_b_clean, predicted_c_clean, predicted_d_clean = [p.flatten()[0] for p in
predicted_params_clean]
print("Предсказанные параметры (без шума):",
[predicted_a_clean, predicted_b_clean, predicted_c_clean, predicted_d_clean])

# Создание предсказанного решения на основе предсказанных параметров
predicted_solution = odeint(system, y0, time_points, args=(predicted_a, predicted_b, predicted_c, predicted_d))

# Расчёт MSE для предсказанных параметров
mse = calculate_mse(solution, predicted_solution)
print("MSE:", mse)

# Визуализация результатов
plt.figure(figsize=(10, 8))

# Подграфик для y1
plt.subplot(2, 1, 1)
plt.scatter(time_points, noisy_data[:, 0], label='Симулированные данные y1 с шумом', color='blue')
plt.scatter(time_points, solution[:, 0], label='Входные данные y1', color='orange')
plt.plot(time_points, predicted_solution[:, 0], label='Оптимизированные данные y1', color='red')
plt.plot(time_points, solution[:, 0], label='Истинные данные y1', color='green')
plt.xlabel('Время')
plt.ylabel('y1')
plt.title(f"Результаты эксперимента {experiment_id} для y1")
plt.legend()

# Подграфик для y2
plt.subplot(2, 1, 2)
plt.scatter(time_points, noisy_data[:, 1], label='Симулированные данные y2 с шумом', color='blue')
plt.scatter(time_points, solution[:, 1], label='Входные данные y2', color='orange')
plt.plot(time_points, predicted_solution[:, 1], label='Оптимизированные данные y2', color='red')
plt.plot(time_points, solution[:, 1], label='Истинные данные y2', color='blue')
plt.xlabel('Время')
plt.ylabel('y2')
plt.title(f"Результаты эксперимента {experiment_id} для y2")
plt.legend()
plt.tight_layout()
plt.show()
# Initial conditions for all experiments
y0 = [1.0, 2.0]
time_points = np.linspace(0, 5, 100)

# Solving the system of equations and adding noise to the data
solution = odeint(system, y0, time_points, args=(a, b, c, d))
noise = np.random.normal(0, 0.5, solution.shape)
noisy_data = solution + noise

# Preparing data for training
X_train = [noisy_data, time_points.reshape(-1, 1)]
y_train = [np.full((len(time_points), 1), a),
np.full((len(time_points), 1), b),
np.full((len(time_points), 1), c),
np.full((len(time_points), 1), d)]

# Model training
neural_ode_model_system.fit(X_train, y_train, epochs=200, verbose=1)

# Prediction of parameters
predicted_params = neural_ode_model_system.predict(X_train)

# Predicted parameters
predicted_a, predicted_b, predicted_c, predicted_d = [p.flatten()[0] for p in predicted_params]

# Results output
print(f"Эксперимент {experiment_id}:")
print("Истинные параметры:", [a, b, c, d])
print("Предсказанные параметры (с шумом):", [predicted_a, predicted_b, predicted_c, predicted_d])

# Prediction of parameters based on true data (without noise)
predicted_params_clean = neural_ode_model_system.predict([solution, time_points.reshape(-1, 1)])
predicted_a_clean, predicted_b_clean, predicted_c_clean, predicted_d_clean = [p.flatten()[0] for p in
predicted_params_clean]
print("Предсказанные параметры (без шума):",
[predicted_a_clean, predicted_b_clean, predicted_c_clean, predicted_d_clean])

# Creating a predicted solution based on the predicted parameters
predicted_solution = odeint(system, y0, time_points, args=(predicted_a, predicted_b, predicted_c, predicted_d))

# MSE calculation for predicted parameters
mse = calculate_mse(solution, predicted_solution)
print("MSE:", mse)

# Visualization of results
plt.figure(figsize=(10, 8))

# Subgraph for y1
plt.subplot(2, 1, 1)
plt.scatter(time_points, noisy_data[:, 0], label='Симулированные данные y1 с шумом', color='blue')
plt.scatter(time_points, solution[:, 0], label='Входные данные y1', color='orange')
plt.plot(time_points, predicted_solution[:, 0], label='Оптимизированные данные y1', color='red')
plt.plot(time_points, solution[:, 0], label='Истинные данные y1', color='green')
plt.xlabel('Время')
plt.ylabel('y1')
plt.title(f"Результаты эксперимента {experiment_id} для y1")
plt.legend()

# Subgraph for y2
plt.subplot(2, 1, 2)
plt.scatter(time_points, noisy_data[:, 1], label='Симулированные данные y2 с шумом', color='blue')
plt.scatter(time_points, solution[:, 1], label='Входные данные y2', color='orange')
plt.plot(time_points, predicted_solution[:, 1], label='Оптимизированные данные y2', color='red')
plt.plot(time_points, solution[:, 1], label='Истинные данные y2', color='blue')
plt.xlabel('Время')
plt.ylabel('y2')
plt.title(f"Результаты эксперимента {experiment_id} для y2")
plt.legend()
plt.tight_layout()
plt.show()
26 changes: 13 additions & 13 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
from functions import *

# Параметры экспериментов
# Experimental parameters
experiment_params = [
(-2, 1, 3, -4), # Эксперимент 1
(-1, 2, -3, 4), # Эксперимент 2
(0.5, -1.5, 2, -2.5), # Эксперимент 3
(1, -1, 1.5, -1.5), # Эксперимент 4
(-2.5, 2.5, -0.5, 0.5), # Эксперимент 5
(2, -2, 3, -3), # Эксперимент 6
(-1.5, 1, 2.5, -2), # Эксперимент 7
(1.5, -1, -2, 2), # Эксперимент 8
(-3, 3, -1, 1), # Эксперимент 9
(2.5, -2.5, 0.5, -0.5) # Эксперимент 10
(-2, 1, 3, -4), # Experiment 1
(-1, 2, -3, 4), # Experiment 2
(0.5, -1.5, 2, -2.5), # Experiment 3
(1, -1, 1.5, -1.5), # Experiment 4
(-2.5, 2.5, -0.5, 0.5), # Experiment 5
(2, -2, 3, -3), # Experiment 6
(-1.5, 1, 2.5, -2), # Experiment 7
(1.5, -1, -2, 2), # Experiment 8
(-3, 3, -1, 1), # Experiment 9
(2.5, -2.5, 0.5, -0.5) # Experiment 10
]

# Запуск экспериментов
# Running experiments
for i, params in enumerate(experiment_params, start=1):
conduct_experiment(*params, experiment_id=i)
conduct_experiment(*params, experiment_id=i)

0 comments on commit ce0b9df

Please sign in to comment.