-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
252 lines (217 loc) · 10.7 KB
/
script.js
File metadata and controls
252 lines (217 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
// Массив для хранения данных валютных пар и пользовательских датасетов
const datasets = [
{
name: 'USD/EUR',
data: [0.9654, 0.9742, 0.9700, 0.9624, 0.9670, 0.9690, 0.9708, 0.9759, 0.9760, 0.9699, 0.9718, 0.9709, 0.9735, 0.9599, 0.9588], // Здесь будут данные для USD/EUR
forecasts: [[], [], []] // Три массива для прогнозируемых данных
},
{
name: 'EUR/RUB',
data: [117.525, 113.926, 113.899, 111.688, 110.881, 107.818, 105.292, 104.228, 105.253, 105.853, 105.458, 105.503, 105.273, 105.177, 103.764], // Здесь будут данные для EUR/RUB
forecasts: [[], [], []] // Три массива для прогнозируемых данных
},
{
name: 'USD/RUB',
data: [113.4955, 110.9955, 110.4955, 107.4955, 107.2455, 104.4955, 102.2455, 101.7455, 102.7455, 102.7000, 102.4955, 102.4500, 102.4955, 100.9955, 99.4955], // Здесь будут данные для USD/RUB
forecasts: [[], [], []] // Три массива для прогнозируемых данных
}
];
// Функция для добавления нового датасета
function addDataset(name, data) {
datasets.push({ name, data, forecasts: [[], [], []] });
console.log(`Датасет "${name}" добавлен!`, datasets);
// Создание новой кнопки для добавленного датасета
const buttonContainer = document.querySelector('.dataset-buttons');
const newButton = document.createElement('button');
newButton.className = 'dataset-button';
newButton.innerHTML = `<img src="img/new.png" width="40" height="40" alt="${name}"><span>${name}</span>`;
// Добавление обработчика для новой кнопки
newButton.addEventListener('click', () => {
displayChart(name);
});
buttonContainer.appendChild(newButton);
}
// Функция для обработки файла txt
function handleFileUpload(file, callback) {
const reader = new FileReader();
reader.onload = (event) => {
const data = event.target.result;
// Удаление пробелов и преобразование данных в массив чисел
const cleanedData = data.split(',').map(item => parseFloat(item.trim()));
callback(cleanedData);
};
reader.readAsText(file);
}
// Функция отображения графика для выбранного датасета
function displayChart(datasetName) {
const dataset = datasets.find(ds => ds.name === datasetName);
if (!dataset) {
alert('Датасет не найден!');
return;
}
// Показываем индикатор загрузки
const loadingDiv = document.getElementById('loading');
loadingDiv.style.display = 'block';
// Запускаем обучение нейронных сетей
NeuralNetwork.addData(dataset.data, dataset.forecasts, (resultContainer) => {
// После завершения обучения скрываем индикатор загрузки
loadingDiv.style.display = 'none';
// Обновляем прогнозы в датасете
dataset.forecasts = resultContainer;
// Создание или выбор canvas для отображения графика
let canvas = document.getElementById('chartCanvas');
if (!canvas) {
canvas = document.createElement('canvas');
canvas.id = 'chartCanvas';
canvas.style.margin = '20px auto';
canvas.style.display = 'block';
canvas.style.backgroundColor = '#f4f4f4';
document.body.appendChild(canvas);
}
const ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 500;
// Очистка предыдущего графика
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Настройка масштаба графика
const allData = [...dataset.data, ...dataset.forecasts.flat()];
const maxY = Math.max(...allData);
const minY = Math.min(...allData);
const scaleX = (canvas.width - 100) / (dataset.data.length + Math.max(...dataset.forecasts.map(f => f.length)));
const scaleY = (canvas.height - 100) / (maxY - minY);
// Рисование названия графика
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.textAlign = 'center';
ctx.fillText(`График для ${datasetName}`, canvas.width / 2, 30);
// Функция рисования сетки
function drawGrid() {
ctx.strokeStyle = '#ddd';
ctx.lineWidth = 1;
// Вертикальные линии
for (let i = 0; i <= dataset.data.length + Math.max(...dataset.forecasts.map(f => f.length)); i++) {
const x = 50 + i * scaleX;
ctx.beginPath();
ctx.moveTo(x, 50); // Сетка начинается ниже названия графика
ctx.lineTo(x, canvas.height - 50);
ctx.stroke();
}
// Горизонтальные линии
for (let y = minY; y <= maxY; y += (maxY - minY) / 10) {
const yPos = canvas.height - 50 - (y - minY) * scaleY;
ctx.beginPath();
ctx.moveTo(50, yPos);
ctx.lineTo(canvas.width - 50, yPos);
ctx.stroke();
}
// Легенда осей
ctx.fillStyle = 'black';
ctx.font = '14px Arial';
ctx.fillText('День', canvas.width - 30, canvas.height - 10);
ctx.fillText('Цена', 30, 40);
}
// Функция рисования линии
function drawLine(data, color, offset = 0, connectTo = null) {
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = 2;
data.forEach((value, index) => {
const x = 50 + (index + offset) * scaleX;
const y = canvas.height - 50 - (value - minY) * scaleY;
if (index === 0) {
if (connectTo !== null) {
ctx.moveTo(connectTo.x, connectTo.y);
}
ctx.lineTo(x, y);
} else {
ctx.lineTo(x, y);
}
// Подпись точки
ctx.fillStyle = 'blue';
ctx.font = 'bold 12px Arial';
ctx.fillText(value.toFixed(4), x + 2, y - 5);
});
ctx.stroke();
return { x: 50 + (data.length - 1 + offset) * scaleX, y: canvas.height - 50 - (data[data.length - 1] - minY) * scaleY };
}
// Рисование сетки
drawGrid();
// Рисование реальных данных
const lastPoint = drawLine(dataset.data, 'green');
// Рисование прогнозов
dataset.forecasts.forEach((forecast, index) => {
const colors = ['red', 'orange', 'purple'];
drawLine(forecast, colors[index], dataset.data.length, lastPoint);
});
// Создание таблицы для прогнозов
let table = document.getElementById('forecastTable');
if (!table) {
table = document.createElement('table');
table.id = 'forecastTable';
table.style.margin = '20px auto';
table.style.borderCollapse = 'collapse';
table.style.width = '80%';
document.body.appendChild(table);
}
// Очистка предыдущей таблицы
table.innerHTML = '';
// Создание заголовка таблицы
const headerRow = document.createElement('tr');
headerRow.innerHTML = '<th>Нейронная сеть</th><th>Значения</th>';
headerRow.style.backgroundColor = '#f4f4f4';
headerRow.style.textAlign = 'left';
table.appendChild(headerRow);
// Добавление строк для каждого прогноза
const networkNames = ['Многослойный перцептрон (MLP)', '1D-CNN', 'LSTM'];
dataset.forecasts.forEach((forecast, index) => {
const row = document.createElement('tr');
row.innerHTML = `<td style="color: ${['red', 'orange', 'purple'][index]}; font-weight: bold;">${networkNames[index]}</td><td>${forecast.map(v => v.toFixed(4)).join(', ')}</td>`;
row.style.borderBottom = '1px solid #ddd';
table.appendChild(row);
});
const row = document.createElement('tr');
row.innerHTML = `<td style="color: black; font-weight: bold;">Реальные данные</td><td>${dataset.data.map(v => v.toFixed(4)).join(', ')}</td>`;
row.style.borderBottom = '1px solid #ddd';
table.appendChild(row);
// Создание таблицы для реальных данных
if (!table) {
table = document.createElement('table');
table.id = 'dataTable';
table.style.margin = '20px auto';
table.style.borderCollapse = 'collapse';
table.style.width = '80%';
document.body.appendChild(table);
}
});
}
// Обработчик для кнопки "Добавить новый"
document.getElementById('add-dataset').addEventListener('click', () => {
const datasetName = prompt('Введите название нового датасета:');
if (!datasetName) {
alert('Название не может быть пустым!');
return;
}
// Создание скрытого элемента для загрузки файла
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.txt';
fileInput.style.display = 'none';
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
handleFileUpload(file, (data) => {
addDataset(datasetName, data);
alert(`Новый датасет "${datasetName}" успешно добавлен!`);
});
}
});
document.body.appendChild(fileInput);
fileInput.click();
document.body.removeChild(fileInput);
});
// Пример для вывода информации при выборе датасета
['usd-eur', 'eur-rub', 'usd-rub'].forEach((id, index) => {
document.getElementById(id).addEventListener('click', () => {
displayChart(datasets[index].name);
});
});