495 lines
19 KiB
JavaScript
495 lines
19 KiB
JavaScript
/**
|
||
* Аудит качества fertilizer_field_acts → пригодность к факторному анализу.
|
||
* Запуск: node dashboard/build-fertilizer-quality-data.js
|
||
*/
|
||
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
const { Client } = require('pg');
|
||
|
||
const OUT_JSON = path.join(__dirname, 'data', 'fertilizer-quality.json');
|
||
const OUT_JS = path.join(__dirname, 'data', 'fertilizer-quality-data.js');
|
||
|
||
/** Мягкие/жёсткие потолки д.в. кг/га (юг РФ, сезонный итог по актам) */
|
||
const LIMITS = {
|
||
default: { nSoft: 280, nHard: 400, pSoft: 180, pHard: 300, kSoft: 250, kHard: 450 },
|
||
'Пшеница озимая': { nSoft: 280, nHard: 400, pSoft: 150, pHard: 250, kSoft: 180, kHard: 350 },
|
||
'Пшеница яровая мягкая': { nSoft: 250, nHard: 350, pSoft: 140, pHard: 220, kSoft: 160, kHard: 300 },
|
||
'Ячмень озимый': { nSoft: 220, nHard: 320, pSoft: 140, pHard: 220, kSoft: 160, kHard: 300 },
|
||
'Кукуруза на зерно': { nSoft: 280, nHard: 420, pSoft: 160, pHard: 280, kSoft: 220, kHard: 400 },
|
||
'Подсолнечник масличный': { nSoft: 140, nHard: 220, pSoft: 120, pHard: 200, kSoft: 200, kHard: 350 },
|
||
'Подсолнечник СПК (крупноплодный)': { nSoft: 140, nHard: 220, pSoft: 120, pHard: 200, kSoft: 200, kHard: 350 },
|
||
Соя: { nSoft: 100, nHard: 180, pSoft: 120, pHard: 200, kSoft: 160, kHard: 300 },
|
||
'Свекла сахарная': { nSoft: 220, nHard: 350, pSoft: 160, pHard: 280, kSoft: 280, kHard: 450 },
|
||
'Горох яровой': { nSoft: 80, nHard: 150, pSoft: 120, pHard: 200, kSoft: 140, kHard: 280 },
|
||
Горох: { nSoft: 80, nHard: 150, pSoft: 120, pHard: 200, kSoft: 140, kHard: 280 },
|
||
'Рапс озимый': { nSoft: 220, nHard: 320, pSoft: 140, pHard: 240, kSoft: 180, kHard: 320 },
|
||
'Лен масличный': { nSoft: 120, nHard: 200, pSoft: 100, pHard: 180, kSoft: 120, kHard: 220 },
|
||
};
|
||
|
||
const MASS_SOFT = 1500; // кг/га минералки без органики
|
||
const MASS_HARD = 3000;
|
||
const MANURE_SOFT = 60000; // кг/га
|
||
const MANURE_HARD = 120000;
|
||
const ACTS_SOFT = 25;
|
||
const ACTS_HARD = 50;
|
||
|
||
const PROD_MAX = {
|
||
'Пшеница озимая': 120,
|
||
'Пшеница яровая мягкая': 100,
|
||
'Ячмень озимый': 120,
|
||
'Подсолнечник масличный': 50,
|
||
'Подсолнечник СПК (крупноплодный)': 50,
|
||
'Кукуруза на зерно': 150,
|
||
'Кукуруза на силос и зеленый корм': 800,
|
||
Соя: 50,
|
||
'Свекла сахарная': 800,
|
||
'Горох яровой': 60,
|
||
Горох: 60,
|
||
Рис: 120,
|
||
'Рапс озимый': 50,
|
||
'Лен масличный': 30,
|
||
};
|
||
|
||
const FLAG_META = {
|
||
unlinked: { label: 'Нет связи с fields', severity: 'warn', analysis: 'partial' },
|
||
multi_crop: { label: 'Несколько культур в строке', severity: 'warn', analysis: 'exclude' },
|
||
zero_input: { label: 'Нулевые масса и NPK', severity: 'info', analysis: 'exclude' },
|
||
missing_dv: { label: 'Есть масса, нет д.в. NPK', severity: 'hard', analysis: 'exclude' },
|
||
incomplete_dv_acts: { label: 'Не все акты с д.в.', severity: 'warn', analysis: 'caution' },
|
||
n_soft: { label: 'N выше мягкого потолка', severity: 'warn', analysis: 'caution' },
|
||
n_hard: { label: 'N выше жёсткого потолка', severity: 'hard', analysis: 'exclude' },
|
||
p_soft: { label: 'P₂O₅ выше мягкого потолка', severity: 'warn', analysis: 'caution' },
|
||
p_hard: { label: 'P₂O₅ выше жёсткого потолка', severity: 'hard', analysis: 'exclude' },
|
||
k_soft: { label: 'K₂O выше мягкого потолка', severity: 'warn', analysis: 'caution' },
|
||
k_hard: { label: 'K₂O выше жёсткого потолка', severity: 'hard', analysis: 'exclude' },
|
||
mass_soft: { label: 'Масса удобрений высокая', severity: 'warn', analysis: 'caution' },
|
||
mass_hard: { label: 'Масса удобрений экстремальная', severity: 'hard', analysis: 'exclude' },
|
||
manure_soft: { label: 'Органика высокая', severity: 'warn', analysis: 'caution' },
|
||
manure_hard: { label: 'Органика экстремальная', severity: 'hard', analysis: 'exclude' },
|
||
npk_gt_mass: { label: 'NPK > массы (без органики)', severity: 'hard', analysis: 'exclude' },
|
||
acts_soft: { label: 'Много актов на поле-год', severity: 'warn', analysis: 'caution' },
|
||
acts_hard: { label: 'Сверхмного актов', severity: 'hard', analysis: 'exclude' },
|
||
prod_outlier: { label: 'Выброс урожайности', severity: 'hard', analysis: 'exclude' },
|
||
high_n_zero_yield: { label: 'Высокий N при нулевом урожае', severity: 'warn', analysis: 'caution' },
|
||
};
|
||
|
||
function pg() {
|
||
return new Client({
|
||
host: process.env.PGHOST,
|
||
port: Number(process.env.PGPORT || 5432),
|
||
database: process.env.PGDATABASE || 'ak_fields',
|
||
user: process.env.PGUSER,
|
||
password: process.env.PGPASSWORD,
|
||
});
|
||
}
|
||
|
||
function num(v) {
|
||
if (v == null) return null;
|
||
const n = Number(v);
|
||
return Number.isFinite(n) ? n : null;
|
||
}
|
||
|
||
function round(n, d = 1) {
|
||
if (n == null || Number.isNaN(Number(n))) return null;
|
||
const f = 10 ** d;
|
||
return Math.round(Number(n) * f) / f;
|
||
}
|
||
|
||
function primaryCrop(crop) {
|
||
if (!crop) return null;
|
||
return String(crop).split(';')[0].trim();
|
||
}
|
||
|
||
function limitsFor(crop) {
|
||
return LIMITS[crop] || LIMITS.default;
|
||
}
|
||
|
||
function percentile(sorted, p) {
|
||
if (!sorted.length) return null;
|
||
const idx = (sorted.length - 1) * p;
|
||
const lo = Math.floor(idx);
|
||
const hi = Math.ceil(idx);
|
||
if (lo === hi) return sorted[lo];
|
||
return sorted[lo] * (1 - (idx - lo)) + sorted[hi] * (idx - lo);
|
||
}
|
||
|
||
function hist(values, edges) {
|
||
const bins = edges.slice(0, -1).map((lo, i) => ({
|
||
lo,
|
||
hi: edges[i + 1],
|
||
label: edges[i + 1] === Infinity ? `${lo}+` : `${lo}–${edges[i + 1]}`,
|
||
n: 0,
|
||
}));
|
||
for (const v of values) {
|
||
const x = Number(v);
|
||
if (!Number.isFinite(x)) continue;
|
||
for (const b of bins) {
|
||
if (x >= b.lo && x < b.hi) {
|
||
b.n += 1;
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
return bins;
|
||
}
|
||
|
||
function flagRow(r) {
|
||
const flags = [];
|
||
const crop = r.crop;
|
||
const lim = limitsFor(crop);
|
||
const n = r.nKgHa || 0;
|
||
const p = r.pKgHa || 0;
|
||
const k = r.kKgHa || 0;
|
||
const mass = r.massKgHa || 0;
|
||
const manure = r.manureKgHa || 0;
|
||
const mineralMass = Math.max(0, mass - manure);
|
||
const npk = n + p + k;
|
||
|
||
if (!r.linked) flags.push('unlinked');
|
||
if (r.multiCrop) flags.push('multi_crop');
|
||
if (mass <= 0 && npk <= 0 && manure <= 0) flags.push('zero_input');
|
||
if (mass > 0 && npk <= 0) flags.push('missing_dv');
|
||
if (r.acts != null && r.actsDv != null && r.acts > 0 && r.actsDv < r.acts) {
|
||
flags.push('incomplete_dv_acts');
|
||
}
|
||
|
||
if (n >= lim.nHard) flags.push('n_hard');
|
||
else if (n >= lim.nSoft) flags.push('n_soft');
|
||
if (p >= lim.pHard) flags.push('p_hard');
|
||
else if (p >= lim.pSoft) flags.push('p_soft');
|
||
if (k >= lim.kHard) flags.push('k_hard');
|
||
else if (k >= lim.kSoft) flags.push('k_soft');
|
||
|
||
if (mineralMass >= MASS_HARD) flags.push('mass_hard');
|
||
else if (mineralMass >= MASS_SOFT) flags.push('mass_soft');
|
||
if (manure >= MANURE_HARD) flags.push('manure_hard');
|
||
else if (manure >= MANURE_SOFT) flags.push('manure_soft');
|
||
|
||
// д.в. не может заметно превышать массу минералки (грубая хим. проверка)
|
||
if (manure <= 0 && mineralMass > 0 && npk > mineralMass * 1.05) flags.push('npk_gt_mass');
|
||
|
||
if ((r.acts || 0) >= ACTS_HARD) flags.push('acts_hard');
|
||
else if ((r.acts || 0) >= ACTS_SOFT) flags.push('acts_soft');
|
||
|
||
if (r.productivity != null && r.productivity > 0) {
|
||
const max = PROD_MAX[crop] ?? 200;
|
||
if (r.productivity > max) flags.push('prod_outlier');
|
||
}
|
||
if ((r.productivity == null || r.productivity <= 0) && n >= lim.nSoft) {
|
||
flags.push('high_n_zero_yield');
|
||
}
|
||
|
||
return flags;
|
||
}
|
||
|
||
function severityOf(flags) {
|
||
let hard = 0;
|
||
let warn = 0;
|
||
for (const f of flags) {
|
||
const s = FLAG_META[f]?.severity;
|
||
if (s === 'hard') hard += 1;
|
||
else if (s === 'warn') warn += 1;
|
||
}
|
||
if (hard) return 'exclude';
|
||
if (warn) return 'caution';
|
||
return 'ok';
|
||
}
|
||
|
||
function bump(map, key, field = 'n') {
|
||
if (!map[key]) map[key] = { n: 0, ok: 0, caution: 0, exclude: 0 };
|
||
map[key][field] += 1;
|
||
}
|
||
|
||
async function main() {
|
||
const c = pg();
|
||
await c.connect();
|
||
console.log('Building fertilizer quality audit...');
|
||
|
||
const exists = await c.query(`
|
||
SELECT EXISTS (
|
||
SELECT 1 FROM information_schema.tables
|
||
WHERE table_schema='public' AND table_name='fertilizer_field_acts'
|
||
) AS ok
|
||
`);
|
||
if (!exists.rows[0].ok) {
|
||
console.error('Table fertilizer_field_acts missing. Run: npm run fertilizer:load');
|
||
process.exit(1);
|
||
}
|
||
|
||
const { rows } = await c.query(`
|
||
SELECT
|
||
a.field_name AS field,
|
||
a.field_id IS NOT NULL AS linked,
|
||
NULLIF(trim(both FROM split_part(f.zone_hierarchy, ' -> ', 2)), '') AS division,
|
||
a.year,
|
||
a.crop AS crop_raw,
|
||
a.nomenclature,
|
||
a.area_ha::float AS area_ha,
|
||
a.acts_count AS acts,
|
||
a.acts_with_dv AS acts_dv,
|
||
a.fertilizer_mass_kg_ha::float AS mass_kg_ha,
|
||
a.manure_kg_ha::float AS manure_kg_ha,
|
||
a.n_kg_ha::float AS n_kg_ha,
|
||
a.p2o5_kg_ha::float AS p_kg_ha,
|
||
a.k2o_kg_ha::float AS k_kg_ha,
|
||
a.productivity::float AS productivity,
|
||
a.yield_category
|
||
FROM fertilizer_field_acts a
|
||
LEFT JOIN fields f ON f.id = a.field_id
|
||
WHERE a.year BETWEEN 2019 AND 2025
|
||
`);
|
||
|
||
const byFlag = {};
|
||
const byYear = {};
|
||
const byCrop = {};
|
||
const byDivision = {};
|
||
const examples = [];
|
||
const nVals = [];
|
||
const pVals = [];
|
||
const kVals = [];
|
||
const massVals = [];
|
||
const manureVals = [];
|
||
const actsVals = [];
|
||
|
||
let ok = 0;
|
||
let caution = 0;
|
||
let exclude = 0;
|
||
let withProd = 0;
|
||
let withDv = 0;
|
||
let withManure = 0;
|
||
let linked = 0;
|
||
let analysisReady = 0; // ok|caution + productivity + dv
|
||
|
||
for (const raw of rows) {
|
||
const crop = primaryCrop(raw.crop_raw);
|
||
const multiCrop = !!(raw.crop_raw && String(raw.crop_raw).includes(';'));
|
||
const r = {
|
||
field: raw.field,
|
||
linked: !!raw.linked,
|
||
division: raw.division || 'Без дивизиона',
|
||
year: raw.year,
|
||
crop,
|
||
multiCrop,
|
||
nomenclature: raw.nomenclature || '',
|
||
areaHa: round(num(raw.area_ha), 1),
|
||
acts: raw.acts,
|
||
actsDv: raw.acts_dv,
|
||
massKgHa: round(num(raw.mass_kg_ha), 1),
|
||
manureKgHa: round(num(raw.manure_kg_ha), 1),
|
||
nKgHa: round(num(raw.n_kg_ha), 1),
|
||
pKgHa: round(num(raw.p_kg_ha), 1),
|
||
kKgHa: round(num(raw.k_kg_ha), 1),
|
||
productivity:
|
||
raw.productivity != null && Number(raw.productivity) > 0
|
||
? round(num(raw.productivity), 1)
|
||
: null,
|
||
yieldCat: raw.yield_category || '—',
|
||
};
|
||
|
||
if (r.linked) linked += 1;
|
||
if (r.productivity != null) withProd += 1;
|
||
if ((r.nKgHa || 0) + (r.pKgHa || 0) + (r.kKgHa || 0) > 0) withDv += 1;
|
||
if ((r.manureKgHa || 0) > 0) withManure += 1;
|
||
|
||
if (r.nKgHa != null) nVals.push(r.nKgHa);
|
||
if (r.pKgHa != null) pVals.push(r.pKgHa);
|
||
if (r.kKgHa != null) kVals.push(r.kKgHa);
|
||
if (r.massKgHa != null) massVals.push(r.massKgHa);
|
||
if ((r.manureKgHa || 0) > 0) manureVals.push(r.manureKgHa);
|
||
if (r.acts != null) actsVals.push(r.acts);
|
||
|
||
const flags = flagRow(r);
|
||
const status = severityOf(flags);
|
||
if (status === 'ok') ok += 1;
|
||
else if (status === 'caution') caution += 1;
|
||
else exclude += 1;
|
||
|
||
const usableForImpact =
|
||
(status === 'ok' || status === 'caution') &&
|
||
r.productivity != null &&
|
||
(r.nKgHa || 0) + (r.pKgHa || 0) + (r.kKgHa || 0) > 0 &&
|
||
!r.multiCrop;
|
||
if (usableForImpact) analysisReady += 1;
|
||
|
||
for (const f of flags) {
|
||
byFlag[f] = (byFlag[f] || 0) + 1;
|
||
}
|
||
|
||
bump(byYear, String(r.year), 'n');
|
||
bump(byYear, String(r.year), status);
|
||
bump(byCrop, r.crop || '—', 'n');
|
||
bump(byCrop, r.crop || '—', status);
|
||
bump(byDivision, r.division, 'n');
|
||
bump(byDivision, r.division, status);
|
||
|
||
if (flags.length) {
|
||
examples.push({
|
||
field: r.field,
|
||
division: r.division,
|
||
year: r.year,
|
||
crop: r.crop,
|
||
nKgHa: r.nKgHa,
|
||
pKgHa: r.pKgHa,
|
||
kKgHa: r.kKgHa,
|
||
massKgHa: r.massKgHa,
|
||
manureKgHa: r.manureKgHa,
|
||
acts: r.acts,
|
||
actsDv: r.actsDv,
|
||
productivity: r.productivity,
|
||
status,
|
||
flags,
|
||
score: flags.reduce((s, f) => s + (FLAG_META[f]?.severity === 'hard' ? 3 : 1), 0),
|
||
});
|
||
}
|
||
}
|
||
|
||
examples.sort((a, b) => b.score - a.score || (b.nKgHa || 0) - (a.nKgHa || 0));
|
||
const topExamples = examples.slice(0, 250).map(({ score, ...rest }) => rest);
|
||
|
||
const sortNums = (arr) => [...arr].sort((a, b) => a - b);
|
||
const nS = sortNums(nVals);
|
||
const pS = sortNums(pVals);
|
||
const kS = sortNums(kVals);
|
||
const mS = sortNums(massVals);
|
||
|
||
const dist = {
|
||
n: hist(nVals, [0, 1, 50, 100, 150, 200, 250, 300, 400, 600, Infinity]),
|
||
p: hist(pVals, [0, 1, 30, 60, 100, 150, 200, 300, Infinity]),
|
||
k: hist(kVals, [0, 1, 30, 60, 100, 150, 200, 300, 450, Infinity]),
|
||
mass: hist(massVals, [0, 1, 100, 300, 500, 800, 1200, 2000, 3000, Infinity]),
|
||
manure: hist(manureVals, [0, 5000, 20000, 40000, 60000, 100000, Infinity]),
|
||
acts: hist(actsVals, [0, 1, 5, 10, 15, 25, 50, Infinity]),
|
||
};
|
||
|
||
const flagRows = Object.entries(byFlag)
|
||
.map(([id, n]) => ({
|
||
id,
|
||
n,
|
||
pct: round((100 * n) / rows.length, 1),
|
||
...FLAG_META[id],
|
||
}))
|
||
.sort((a, b) => b.n - a.n);
|
||
|
||
const toArr = (map) =>
|
||
Object.entries(map)
|
||
.map(([key, v]) => ({
|
||
key,
|
||
...v,
|
||
okPct: round((100 * v.ok) / v.n, 1),
|
||
cautionPct: round((100 * v.caution) / v.n, 1),
|
||
excludePct: round((100 * v.exclude) / v.n, 1),
|
||
}))
|
||
.sort((a, b) => b.n - a.n);
|
||
|
||
const total = rows.length;
|
||
const verdict =
|
||
analysisReady / total >= 0.55
|
||
? 'usable'
|
||
: analysisReady / total >= 0.35
|
||
? 'usable_with_filters'
|
||
: 'weak';
|
||
|
||
const payload = {
|
||
meta: {
|
||
generatedAt: new Date().toISOString(),
|
||
company: 'АО фирма «Агрокомплекс» им. Н.И. Ткачева',
|
||
rows: total,
|
||
years: '2019–2025',
|
||
nutrientUnit: 'кг д.в./га',
|
||
massUnit: 'кг/га',
|
||
limitsNote:
|
||
'Потолки — ориентир сезонного итога по актам для юга РФ, не техкарта хозяйства.',
|
||
notes: [
|
||
'Жёсткие флаги → исключать из dose–response; мягкие → оставлять с осторожностью.',
|
||
'missing_dv: масса списана, но д.в. не рассчитано — для NPK-анализа непригодно.',
|
||
'npk_gt_mass: сумма д.в. больше массы минералки — ошибка единиц или расчёта.',
|
||
'Баланс выноса на этой странице не считается — только sanity-check входных доз.',
|
||
'Доля «готова к анализу влияния» = без hard-флагов + есть урожайность + есть NPK + одна культура.',
|
||
],
|
||
},
|
||
limits: LIMITS,
|
||
thresholds: {
|
||
massSoft: MASS_SOFT,
|
||
massHard: MASS_HARD,
|
||
manureSoft: MANURE_SOFT,
|
||
manureHard: MANURE_HARD,
|
||
actsSoft: ACTS_SOFT,
|
||
actsHard: ACTS_HARD,
|
||
},
|
||
flagMeta: FLAG_META,
|
||
summary: {
|
||
rows: total,
|
||
linked,
|
||
linkedPct: round((100 * linked) / total, 1),
|
||
withDv,
|
||
withDvPct: round((100 * withDv) / total, 1),
|
||
withProd,
|
||
withProdPct: round((100 * withProd) / total, 1),
|
||
withManure,
|
||
withManurePct: round((100 * withManure) / total, 1),
|
||
ok,
|
||
caution,
|
||
exclude,
|
||
okPct: round((100 * ok) / total, 1),
|
||
cautionPct: round((100 * caution) / total, 1),
|
||
excludePct: round((100 * exclude) / total, 1),
|
||
analysisReady,
|
||
analysisReadyPct: round((100 * analysisReady) / total, 1),
|
||
verdict,
|
||
verdictText:
|
||
verdict === 'usable'
|
||
? 'Данные в целом пригодны для анализа влияния при фильтрации hard-выбросов.'
|
||
: verdict === 'usable_with_filters'
|
||
? 'Анализ влияния возможен, но нужна жёсткая фильтрация и проверка по культурам/годам.'
|
||
: 'Качество слабое: большая доля строк непригодна; факторный анализ будет смещён.',
|
||
},
|
||
quantiles: {
|
||
n: {
|
||
p50: round(percentile(nS, 0.5), 1),
|
||
p90: round(percentile(nS, 0.9), 1),
|
||
p99: round(percentile(nS, 0.99), 1),
|
||
max: nS.length ? round(nS[nS.length - 1], 1) : null,
|
||
},
|
||
p: {
|
||
p50: round(percentile(pS, 0.5), 1),
|
||
p90: round(percentile(pS, 0.9), 1),
|
||
p99: round(percentile(pS, 0.99), 1),
|
||
max: pS.length ? round(pS[pS.length - 1], 1) : null,
|
||
},
|
||
k: {
|
||
p50: round(percentile(kS, 0.5), 1),
|
||
p90: round(percentile(kS, 0.9), 1),
|
||
p99: round(percentile(kS, 0.99), 1),
|
||
max: kS.length ? round(kS[kS.length - 1], 1) : null,
|
||
},
|
||
mass: {
|
||
p50: round(percentile(mS, 0.5), 1),
|
||
p90: round(percentile(mS, 0.9), 1),
|
||
p99: round(percentile(mS, 0.99), 1),
|
||
max: mS.length ? round(mS[mS.length - 1], 1) : null,
|
||
},
|
||
},
|
||
distributions: dist,
|
||
flags: flagRows,
|
||
byYear: toArr(byYear).sort((a, b) => Number(a.key) - Number(b.key)),
|
||
byCrop: toArr(byCrop).slice(0, 25),
|
||
byDivision: toArr(byDivision),
|
||
examples: topExamples,
|
||
};
|
||
|
||
fs.mkdirSync(path.dirname(OUT_JSON), { recursive: true });
|
||
fs.writeFileSync(OUT_JSON, JSON.stringify(payload));
|
||
fs.writeFileSync(OUT_JS, `window.__FERT_Q__=${JSON.stringify(payload)};\n`);
|
||
const mb = (fs.statSync(OUT_JSON).size / 1024 / 1024).toFixed(2);
|
||
console.log(
|
||
`Wrote ${OUT_JSON} (${mb} MB). ready=${payload.summary.analysisReadyPct}% verdict=${verdict}`
|
||
);
|
||
await c.end();
|
||
}
|
||
|
||
main().catch((e) => {
|
||
console.error(e);
|
||
process.exit(1);
|
||
});
|