Spaces:
Sleeping

kriyatrack / src /forecast.js
budijuarto's picture
Publish KriyaTrack sewing studio, forecast evaluation and interactive 3D scene
d091b2c verified
Raw History Blame Contribute Delete
9.24 kB
export const FORECAST_MODELS = Object.freeze([
Object.freeze({ id: 'moving', label: 'Moving Average 3', minHistory: 3, description: 'Rata-rata omzet tiga bulan terakhir.' }),
Object.freeze({ id: 'seasonal', label: 'Seasonal Naive', minHistory: 12, description: 'Nilai bulan yang sama pada tahun sebelumnya.' }),
Object.freeze({ id: 'holt', label: 'Holt-Winters', minHistory: 24, description: 'Pemulusan dengan tren teredam dan musim tahunan aditif.' }),
Object.freeze({ id: 'ridge', label: 'Ridge Regression', minHistory: 24, description: 'Regresi regularisasi pada riwayat dan kalender.' }),
Object.freeze({ id: 'neural', label: 'Neural Network', minHistory: 24, description: 'Jaringan dua lapisan tersembunyi dengan acuan musiman.' }),
]);
const lags = [1, 2, 3, 6, 12];
const periodicity = 12;
const maxAmount = 1_000_000_000_000;
const models = new Map(FORECAST_MODELS.map((entry) => [entry.id, entry]));
const mean = (numbers) => numbers.reduce((sum, number) => sum + number, 0) / numbers.length;
export function monthIndex(value) {
const parsed = typeof value === 'string' && value.match(/^(\d{4})-(0[1-9]|1[0-2])$/);
if (!parsed || Number(parsed[1]) < 1900 || Number(parsed[1]) > 2200) throw new Error('Periode harus berformat YYYY-MM.');
return Number(parsed[1]) * 12 + Number(parsed[2]) - 1;
}
function formatMonth(month) {
return Math.floor(month / 12) + '-' + String(month % 12 + 1).padStart(2, '0');
}
export const nextMonth = (month) => formatMonth(monthIndex(month) + 1);
export function validateHistory(history) {
if (!Array.isArray(history) || history.length > 240) throw new Error('Gunakan hingga 240 bulan dengan data lengkap.');
let previous = null;
for (const row of history) {
const current = monthIndex(row?.month);
if (previous != null && current !== previous + 1) throw new Error('Rekap bulanan harus berurutan tanpa bulan kosong.');
if (!Number.isSafeInteger(row.value) || row.value < 0 || row.value > maxAmount) {
throw new Error('Omzet harus dalam rupiah bulat dari Rp0 hingga Rp1 triliun.');
}
previous = current;
}
return history;
}
export function aggregatePaidOrders(orders, { from, to, productId } = {}) {
const initial = monthIndex(from);
const end = monthIndex(to);
if (initial > end || end - initial >= 240) throw new Error('Gunakan rentang hingga 240 bulan.');
const months = Array.from({ length: end - initial + 1 }, (_, index) => ({
month: formatMonth(initial + index), value: 0, paidOrders: 0, units: 0,
}));
for (const order of orders) {
if (order.status !== 'paid' || productId && order.productId !== productId) continue;
const index = monthIndex(order.orderDate.slice(0, 7)) - initial;
if (!months[index]) continue;
if (!Number.isSafeInteger(order.quantity) || order.quantity < 1 || !Number.isSafeInteger(order.unitPrice)
|| order.unitPrice < 0 || order.total !== order.quantity * order.unitPrice) {
throw new Error('Total transaksi berbeda dari jumlah × harga.');
}
months[index].value += order.total;
months[index].paidOrders += 1;
months[index].units += order.quantity;
}
return validateHistory(months);
}
function featureRow(values, targetMonth) {
const ordinal = monthIndex(targetMonth);
const angle = 2 * Math.PI * (ordinal % 12) / 12;
return [
...lags.map((lag) => values.at(-lag)),
mean(values.slice(-3)), mean(values.slice(-6)), ordinal, Math.sin(angle), Math.cos(angle),
];
}
export function forecastFeatures(history) {
validateHistory(history);
if (history.length < 12) throw new Error('Diperlukan 12 bulan untuk membentuk fitur musiman.');
return featureRow(history.map((row) => row.value), nextMonth(history.at(-1).month));
}
function holtWinters(values, { alpha = .35, beta = .08, gamma = .18, phi = .94 } = {}) {
if (![alpha, beta, gamma, phi].every((value) => Number.isFinite(value) && value >= 0 && value <= 1)) {
throw new Error('Parameter Holt-Winters harus di antara 0 dan 1.');
}
const first = mean(values.slice(0, periodicity));
const second = mean(values.slice(periodicity, 2 * periodicity));
let growth = (second - first) / periodicity;
let level = first + (periodicity - 1) / 2 * growth;
const season = values.slice(0, periodicity).map((value, i) => (
(value + values[i + periodicity]) / 2 - (first + second) / 2 - (i - (periodicity - 1) / 2) * growth
));
for (let i = periodicity; i < values.length; i++) {
const slot = i % periodicity;
const previous = level;
const seasonal = season[slot];
level = alpha * (values[i] - seasonal) + (1 - alpha) * (level + phi * growth);
growth = beta * (level - previous) + (1 - beta) * phi * growth;
season[slot] = gamma * (values[i] - level) + (1 - gamma) * seasonal;
}
return level + phi * growth + season[values.length % periodicity];
}
function solveLinear(matrix, values) {
const augmented = matrix.map((row, i) => [...row, values[i]]);
const size = values.length;
for (let col = 0; col < size; col += 1) {
let pivot = col;
for (let i = col + 1; i < size; i += 1) {
if (Math.abs(augmented[i][col]) > Math.abs(augmented[pivot][col])) pivot = i;
}
[augmented[col], augmented[pivot]] = [augmented[pivot], augmented[col]];
const divisor = augmented[col][col];
for (let j = col; j <= size; j += 1) augmented[col][j] /= divisor;
for (let i = 0; i < size; i += 1) {
if (i === col) continue;
const multiplier = augmented[i][col];
for (let j = col; j <= size; j += 1) augmented[i][j] -= multiplier * augmented[col][j];
}
}
return augmented.map((row) => row[size]);
}
function ridge(history, values, { lambda = 4 } = {}) {
if (!Number.isFinite(lambda) || lambda <= 0 || lambda > 1000) throw new Error('Regularisasi ridge harus lebih dari nol.');
const training = history.slice(12).map((row, index) => featureRow(values.slice(0, index + 12), row.month));
const targets = history.slice(12).map((row, i) => row.value - training[i][4]);
const targetMean = mean(targets);
const featureMeans = training[0].map((_value, col) => mean(training.map((row) => row[col])));
const featureScales = featureMeans.map((center, col) => Math.sqrt(mean(training.map((row) => (row[col] - center) ** 2))) || 1);
const standardize = (row) => row.map((value, col) => (value - featureMeans[col]) / featureScales[col]);
const vectors = training.map(standardize);
const standardized = standardize(featureRow(values, nextMonth(history.at(-1).month)));
const size = standardized.length;
const gram = Array.from({ length: size }, (_, i) => Array.from({ length: size }, (_, j) => i === j ? lambda : 0));
const rhs = new Array(size).fill(0);
for (const [i, vector] of vectors.entries()) {
for (let j = 0; j < size; j += 1) {
rhs[j] += vector[j] * (targets[i] - targetMean);
for (let k = 0; k < size; k += 1) gram[j][k] += vector[j] * vector[k];
}
}
const weights = solveLinear(gram, rhs);
const correction = weights.reduce((value, weight, index) => value + weight * standardized[index], targetMean);
return values.at(-12) + correction;
}
export function neuralForward(features, artifact) {
if (artifact?.schema !== 'kriyatrack-neural/v1' || !Array.isArray(artifact.layers) || features.length !== 10) {
throw new Error('Model neural belum dimuat.');
}
const { mean: centers, variance } = artifact.normalization;
let vector = features.map((value, i) => (Math.fround(value) - centers[i]) / Math.max(Math.sqrt(variance[i]), 1e-7));
for (const layer of artifact.layers) {
vector = layer.bias.map((bias, output) => {
const sum = vector.reduce((value, input, index) => value + input * layer.weights[index][output], bias);
return layer.activation === 'tanh' ? Math.tanh(sum) : sum;
});
}
return Math.fround(features[4]) + vector[0] * artifact.correction.scale + artifact.correction.offset;
}
const calculate = {
moving: (_history, values) => mean(values.slice(-3)),
seasonal: (_history, values) => values.at(-12),
holt: (_history, values, params) => holtWinters(values, params),
ridge,
neural: (history, values, artifact) => {
const trainedThrough = artifact?.trainedThrough;
if (!trainedThrough) throw new Error('Model neural belum dimuat.');
if (monthIndex(history.at(-1).month) < monthIndex(trainedThrough)) {
throw new Error('Model neural memerlukan riwayat hingga ' + trainedThrough + ' atau sesudahnya.');
}
return neuralForward(featureRow(values, nextMonth(history.at(-1).month)), artifact);
},
};
export function forecastNext(history, profileId = 'moving', params) {
validateHistory(history);
const info = models.get(profileId);
if (!info) throw new Error('Model prakiraan tidak dikenal.');
if (history.length < info.minHistory) return null;
const trainedThrough = history.at(-1).month;
const amount = calculate[profileId](history, history.map((row) => row.value), params);
if (!Number.isFinite(amount) || amount > maxAmount) throw new Error('Model menghasilkan nilai di luar batas.');
return { id: info.id, label: info.label, month: nextMonth(trainedThrough), value: Math.round(Math.max(0, amount)),
trainedThrough, historySize: history.length };
}