From 6563cc227a01f704a1be0f044fcb69b7bb622bec Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 14:21:37 +0500 Subject: [PATCH 01/34] =?UTF-8?q?feat(galerkin):=20add=20Galerkin=20BVP=20?= =?UTF-8?q?solver=20core=20=E2=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements the Galerkin method for second-order linear boundary value problems: safe expression parsing (no eval), symbolic derivatives via mathjs, composite Simpson integration with error estimate, Gaussian elimination with partial pivoting, residual and orthogonality checks. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- lib/galerkin.ts | 370 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 370 insertions(+) create mode 100644 lib/galerkin.ts diff --git a/lib/galerkin.ts b/lib/galerkin.ts new file mode 100644 index 0000000..2905922 --- /dev/null +++ b/lib/galerkin.ts @@ -0,0 +1,370 @@ +import { math } from '@/lib/math'; +import type { MathNode } from 'mathjs'; + +export interface GalerkinInput { + p: string; + q: string; + f: string; + a: string; + b: string; + alpha0: string; + alpha1: string; + alphaValue: string; + beta0: string; + beta1: string; + betaValue: string; + phi0: string; + basis: string[]; +} + +export interface GalerkinFunction { + text: string; + tex: string; + d1Text: string; + d1Tex: string; + d2Text: string; + d2Tex: string; + value: (x: number) => number; + d1: (x: number) => number; + d2: (x: number) => number; +} + +export interface GalerkinIntegral { + name: string; + row: number; + col: number; + integrandTex: string; + samples: Array<{ x: number; value: number }>; + value: number; + error: number; +} + +export interface GalerkinResult { + operatorTex: string; + phi0: GalerkinFunction; + basis: GalerkinFunction[]; + pTex: string; + qTex: string; + fTex: string; + boundaryLeft: { phi0: number; target: number }; + boundaryRight: { phi0: number; target: number }; + approximationTex: string; + integrals: GalerkinIntegral[]; + matrix: number[][]; + rhs: number[]; + coefficients: number[]; + finalTex: string; + solutionText: string; + residualMax: number; + orthogonality: number[]; + boundaryErrors: { left: number; right: number }; + samples: Array<{ x: number; u: number; residual: number }>; + method: 'adaptive-simpson'; +} + +const ALLOWED_SYMBOLS = new Set(['x', 'pi', 'e', 'E', 'tau', 'i']); +const FORBIDDEN_FUNCTIONS = new Set([ + 'import', + 'createUnit', + 'config', + 'evaluate', + 'parse', + 'compile', +]); +const EPS = 1e-9; +const SAMPLE_COUNT = 201; +const SIMPSON_N = 800; + +type Scope = Record; + +function parseOrThrow(source: string, label: string): MathNode { + const text = source.trim(); + if (!text) throw new Error(`${label} bo‘sh bo‘lmasligi kerak.`); + let node: MathNode; + try { + node = math.parse(text); + } catch { + throw new Error(`${label} ifodasini tushunib bo‘lmadi: “${text}”.`); + } + node.traverse((child) => { + if (child.type !== 'SymbolNode') return; + const name = (child as unknown as { name: string }).name; + const isFunctionName = name in math && typeof math[name] === 'function'; + if (ALLOWED_SYMBOLS.has(name) || (isFunctionName && !FORBIDDEN_FUNCTIONS.has(name))) + return; + if (name in math && !isFunctionName) return; + throw new Error(`${label} ichida noma’lum belgi: “${name}”.`); + }); + return node; +} + +function toScalar(value: unknown, label: string, x: number): number { + const result = typeof value === 'number' ? value : Number(value); + if (!Number.isFinite(result)) + throw new Error(`${label} x=${formatNumber(x)} nuqtada chekli qiymat bermadi.`); + return result; +} + +function makeFunction(source: string, label: string): GalerkinFunction { + const node = parseOrThrow(source, label); + const d1Node = math.derivative(node, 'x'); + const d2Node = math.derivative(d1Node, 'x'); + const compiled = node.compile(); + const compiledD1 = d1Node.compile(); + const compiledD2 = d2Node.compile(); + const evalAt = (fn: ReturnType) => (x: number) => + toScalar(fn.evaluate({ x } as Scope), label, x); + return { + text: node.toString(), + tex: node.toTex(), + d1Text: d1Node.toString(), + d1Tex: d1Node.toTex(), + d2Text: d2Node.toString(), + d2Tex: d2Node.toTex(), + value: evalAt(compiled), + d1: evalAt(compiledD1), + d2: evalAt(compiledD2), + }; +} + +function parseNumber(value: string, label: string): number { + try { + const result = Number(math.evaluate(value.trim() || '0')); + if (!Number.isFinite(result)) throw new Error(); + return result; + } catch { + throw new Error(`${label} uchun son yoki kasr kiriting.`); + } +} + +export function formatNumber(value: number, digits = 8): string { + if (!Number.isFinite(value)) return String(value); + return Number(value.toFixed(digits)).toString(); +} + +export function texNumber(value: number): string { + if (Math.abs(value) < EPS) return '0'; + const sign = value < 0 ? '-' : ''; + const absolute = Math.abs(value); + let numerator = Math.round(absolute); + let denominator = 1; + let bestError = Math.abs(absolute - numerator); + for (let d = 1; d <= 4096; d += 1) { + const n = Math.round(absolute * d); + const error = Math.abs(absolute - n / d); + if (error < bestError) { + numerator = n; + denominator = d; + bestError = error; + } + if (error < 1e-9) break; + } + if (bestError > 1e-7) return `${sign}${formatNumber(absolute)}`; + return `${sign}${denominator === 1 ? numerator : `\\frac{${numerator}}{${denominator}}`}`; +} + +function simpson(g: (x: number) => number, a: number, b: number, n: number): number { + const m = n % 2 === 0 ? n : n + 1; + const h = (b - a) / m; + let sum = g(a) + g(b); + for (let i = 1; i < m; i += 1) { + sum += g(a + i * h) * (i % 2 === 1 ? 4 : 2); + } + return (sum * h) / 3; +} + +function integrate( + g: (x: number) => number, + a: number, + b: number, +): { value: number; error: number } { + const coarse = simpson(g, a, b, SIMPSON_N / 2); + const fine = simpson(g, a, b, SIMPSON_N); + return { value: fine, error: Math.abs(fine - coarse) / 15 }; +} + +function sampleGrid(a: number, b: number, count: number): number[] { + return Array.from({ length: count }, (_, index) => a + ((b - a) * index) / (count - 1)); +} + +export function solveLinearSystem(matrix: number[][], rhs: number[]): number[] { + const n = rhs.length; + const m = matrix.map((row, i) => [...row, rhs[i]]); + for (let col = 0; col < n; col += 1) { + let pivot = col; + for (let row = col + 1; row < n; row += 1) { + if (Math.abs(m[row][col]) > Math.abs(m[pivot][col])) pivot = row; + } + if (Math.abs(m[pivot][col]) < 1e-12) + throw new Error( + 'Algebraik sistema singulyar yoki yechimga ega emas. Bazis funksiyalarni tekshiring.', + ); + [m[col], m[pivot]] = [m[pivot], m[col]]; + for (let row = col + 1; row < n; row += 1) { + const factor = m[row][col] / m[col][col]; + for (let k = col; k <= n; k += 1) m[row][k] -= factor * m[col][k]; + } + } + const x = new Array(n).fill(0); + for (let row = n - 1; row >= 0; row -= 1) { + let sum = m[row][n]; + for (let k = row + 1; k < n; k += 1) sum -= m[row][k] * x[k]; + x[row] = sum / m[row][row]; + } + return x; +} + +function linearCombinationText(coefficients: number[]): string { + return coefficients + .map((c, index) => `${c < 0 ? '-' : '+'} ${formatNumber(Math.abs(c))}*phi${index + 1}(x)`) + .join(' '); +} + +export function solveGalerkin(input: GalerkinInput): GalerkinResult { + const a = parseNumber(input.a, 'Chap chegara a'); + const b = parseNumber(input.b, 'O‘ng chegara b'); + if (!(a < b)) throw new Error('Integrallash oralig‘ida a < b bo‘lishi kerak.'); + + const alpha0 = parseNumber(input.alpha0, 'α₀'); + const alpha1 = parseNumber(input.alpha1, 'α₁'); + const alphaValue = parseNumber(input.alphaValue, 'F_a'); + const beta0 = parseNumber(input.beta0, 'β₀'); + const beta1 = parseNumber(input.beta1, 'β₁'); + const betaValue = parseNumber(input.betaValue, 'F_b'); + if (Math.abs(alpha0) + Math.abs(alpha1) < EPS) + throw new Error('Chap chegaraviy shartda α₀ yoki α₁ noldan farqli bo‘lishi kerak.'); + if (Math.abs(beta0) + Math.abs(beta1) < EPS) + throw new Error('O‘ng chegaraviy shartda β₀ yoki β₁ noldan farqli bo‘lishi kerak.'); + + const pFn = makeFunction(input.p, 'p(x)'); + const qFn = makeFunction(input.q, 'q(x)'); + const fFn = makeFunction(input.f, 'f(x)'); + const phi0 = makeFunction(input.phi0, 'φ₀(x)'); + const basis = input.basis.map((source, index) => + makeFunction(source, `φ${index + 1}(x)`), + ); + const n = basis.length; + if (n < 1) throw new Error('Kamida bitta bazis funksiya kiriting.'); + + const boundaryLeft = { + phi0: alpha0 * phi0.value(a) + alpha1 * phi0.d1(a), + target: alphaValue, + }; + const boundaryRight = { + phi0: beta0 * phi0.value(b) + beta1 * phi0.d1(b), + target: betaValue, + }; + if (Math.abs(boundaryLeft.phi0 - alphaValue) > 1e-7) + throw new Error( + `φ₀(x) chap chegaraviy shartni qanoatlantirmaydi: ${formatNumber(boundaryLeft.phi0)} ≠ ${formatNumber(alphaValue)}.`, + ); + if (Math.abs(boundaryRight.phi0 - betaValue) > 1e-7) + throw new Error( + `φ₀(x) o‘ng chegaraviy shartni qanoatlantirmaydi: ${formatNumber(boundaryRight.phi0)} ≠ ${formatNumber(betaValue)}.`, + ); + + basis.forEach((phi, index) => { + const left = alpha0 * phi.value(a) + alpha1 * phi.d1(a); + const right = beta0 * phi.value(b) + beta1 * phi.d1(b); + if (Math.abs(left) > 1e-7 || Math.abs(right) > 1e-7) + throw new Error( + `φ${index + 1}(x) bir jinsli chegaraviy shartlarni qanoatlantirmaydi (chap: ${formatNumber(left)}, o‘ng: ${formatNumber(right)}).`, + ); + }); + + const operator = (u: { value: (x: number) => number; d1: (x: number) => number; d2: (x: number) => number }) => + (x: number) => + u.d2(x) + pFn.value(x) * u.d1(x) + qFn.value(x) * u.value(x); + const opPhi0 = operator(phi0); + const opBasis = basis.map((phi) => operator(phi)); + + const matrix: number[][] = []; + const integrals: GalerkinIntegral[] = []; + for (let k = 0; k < n; k += 1) { + const row: number[] = []; + for (let i = 0; i < n; i += 1) { + const integrand = (x: number) => basis[k].value(x) * opBasis[i](x); + const { value, error } = integrate(integrand, a, b); + row.push(value); + integrals.push({ + name: `a_{${k + 1}${i + 1}}`, + row: k, + col: i, + integrandTex: `\\varphi_{${k + 1}}(x)\\left[\\varphi_{${i + 1}}''+p(x)\\varphi_{${i + 1}}'+q(x)\\varphi_{${i + 1}}\\right]`, + samples: sampleGrid(a, b, 5).map((x) => ({ x, value: integrand(x) })), + value, + error, + }); + } + matrix.push(row); + } + + const rhs: number[] = []; + for (let k = 0; k < n; k += 1) { + const integrand = (x: number) => basis[k].value(x) * (fFn.value(x) - opPhi0(x)); + const { value, error } = integrate(integrand, a, b); + rhs.push(value); + integrals.push({ + name: `b_{${k + 1}}`, + row: k, + col: -1, + integrandTex: `\\varphi_{${k + 1}}(x)\\left[f(x)-L(\\varphi_0)\\right]`, + samples: sampleGrid(a, b, 5).map((x) => ({ x, value: integrand(x) })), + value, + error, + }); + } + + const coefficients = solveLinearSystem(matrix, rhs); + + const uOf = (x: number) => + phi0.value(x) + coefficients.reduce((s, c, i) => s + c * basis[i].value(x), 0); + const d1Of = (x: number) => + phi0.d1(x) + coefficients.reduce((s, c, i) => s + c * basis[i].d1(x), 0); + const d2Of = (x: number) => + phi0.d2(x) + coefficients.reduce((s, c, i) => s + c * basis[i].d2(x), 0); + const residualAt = (x: number) => + d2Of(x) + pFn.value(x) * d1Of(x) + qFn.value(x) * uOf(x) - fFn.value(x); + + const orthogonality = basis.map((phi) => { + const { value } = integrate((x) => phi.value(x) * residualAt(x), a, b); + return value; + }); + + const grid = sampleGrid(a, b, SAMPLE_COUNT); + const samples = grid.map((x) => ({ x, u: uOf(x), residual: residualAt(x) })); + const residualMax = samples.reduce((m, s) => Math.max(m, Math.abs(s.residual)), 0); + + const boundaryErrors = { + left: alpha0 * uOf(a) + alpha1 * d1Of(a) - alphaValue, + right: beta0 * uOf(b) + beta1 * d1Of(b) - betaValue, + }; + + const terms = basis.map((phi, i) => `${texNumber(coefficients[i])}\\,${phi.tex}`); + const finalTex = `u_n(x)=${phi0.tex}${coefficients + .map((c, i) => `${c < 0 ? '-' : '+'}${texNumber(Math.abs(c))}\\,${basis[i].tex}`) + .join('')}`; + + return { + operatorTex: `u''+(${pFn.tex})u'+(${qFn.tex})u=${fFn.tex}`, + phi0, + basis, + pTex: pFn.tex, + qTex: qFn.tex, + fTex: fFn.tex, + boundaryLeft, + boundaryRight, + approximationTex: `u_n(x)=${phi0.tex}+${terms.join('+').replace(/\+-/g, '-')}`, + integrals, + matrix, + rhs, + coefficients, + finalTex, + solutionText: linearCombinationText(coefficients), + residualMax, + orthogonality, + boundaryErrors, + samples, + method: 'adaptive-simpson', + }; +} From 599b151ef862e663e97ccc45586ceb7d237190a8 Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 14:24:02 +0500 Subject: [PATCH 02/34] =?UTF-8?q?feat(galerkin):=20add=20step-by-step=20Ga?= =?UTF-8?q?lerkin=20solver=20page=20=E2=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds /methods/galerkin: input panel with safe expression parsing, the 12 solution stages (problem, operator, basis checks, L(phi) evaluation, a_ki and b_k integrals with expandable details, linear system with matrix form, coefficients, final result, verification with boundary, residual and orthogonality checks), precision selector, copy formula and residual / approximation plots. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- app/(workspace)/methods/galerkin/page.tsx | 50 ++ components/galerkin-method.tsx | 568 ++++++++++++++++++++++ lib/galerkin.ts | 2 +- 3 files changed, 619 insertions(+), 1 deletion(-) create mode 100644 app/(workspace)/methods/galerkin/page.tsx create mode 100644 components/galerkin-method.tsx diff --git a/app/(workspace)/methods/galerkin/page.tsx b/app/(workspace)/methods/galerkin/page.tsx new file mode 100644 index 0000000..8a91973 --- /dev/null +++ b/app/(workspace)/methods/galerkin/page.tsx @@ -0,0 +1,50 @@ +import type { Metadata } from 'next'; +import { GalerkinMethod } from '@/components/galerkin-method'; +import { MethodJsonLd } from '@/components/seo/json-ld'; +import { siteConfig } from '@/lib/config'; + +export const metadata: Metadata = { + title: 'Galerkin Method | Метод Галеркина | Galyorkin usuli', + description: + 'Solve second-order linear boundary value problems step by step with the Galerkin method. Метод Галеркина для краевой задачи. Galyorkin usuli bilan chegaraviy masalani bosqichma-bosqich yeching.', + keywords: [ + 'galerkin method', + 'galerkin boundary value problem', + 'boundary value problem solver', + 'second order ODE solver', + 'numerical methods', + 'метод галеркина', + 'краевая задача метод галеркина', + 'galyorkin usuli', + 'chegaraviy masala galyorkin', + ], + alternates: { canonical: '/methods/galerkin' }, + openGraph: { + title: 'Galerkin Method Solver | Метод Галеркина', + description: + 'Build basis functions, Galerkin integrals, and a linear system for a second-order boundary value problem.', + url: `${siteConfig.url}/methods/galerkin`, + images: [{ url: '/images/og/collocation.png', width: 1200, height: 630, alt: 'Galyorkin usuli' }], + }, + twitter: { + card: 'summary_large_image', + title: 'Galerkin Method | Метод Галеркина', + description: 'Step-by-step Galerkin solution of a second-order boundary value problem.', + images: ['/images/og/collocation.png'], + }, +}; + +export default function GalerkinPage() { + return ( + <> + + + + ); +} diff --git a/components/galerkin-method.tsx b/components/galerkin-method.tsx new file mode 100644 index 0000000..7c6540e --- /dev/null +++ b/components/galerkin-method.tsx @@ -0,0 +1,568 @@ +'use client'; + +import { useState, type FormEvent, type ReactNode } from 'react'; +import katex from 'katex'; +import { Calculator, Check, Copy, Info } from 'lucide-react'; +import { + PsHero, + PsNote, + PsPanel, + PsPanelHead, +} from '@/components/ui/print-stream'; +import { useScrollToResult } from '@/components/ui/use-scroll-to-result'; +import { + formatNumber, + solveGalerkin, + texNumber, + type GalerkinInput, + type GalerkinResult, +} from '@/lib/galerkin'; + +const DEFAULT_INPUT: GalerkinInput = { + p: '-cos(x)', + q: 'sin(x)', + f: 'sin(x)', + a: '0', + b: 'pi', + alpha0: '1', + alpha1: '0', + alphaValue: '1', + beta0: '1', + beta1: '0', + betaValue: '2', + phi0: '1 + x/pi', + basis: ['sin(x)', 'sin(2*x)'], +}; + +const PRESET_BASIS = ['sin(x)', 'sin(2*x)', 'sin(3*x)', 'sin(4*x)', 'sin(5*x)', 'sin(6*x)']; +const PRECISIONS = [4, 6, 8, 12] as const; + +function katexHtml(source: string, displayMode: boolean): string { + return katex.renderToString(source, { throwOnError: false, displayMode }); +} + +function Tex({ value, block = true }: { value: string; block?: boolean }) { + return ( +
+ ); +} + +function Step({ + index, + title, + children, +}: { + index: number; + title: string; + children: ReactNode; +}) { + return ( + + +
{children}
+
+ ); +} + +function Details({ summary, children }: { summary: string; children: ReactNode }) { + return ( +
+ + {summary} + +
{children}
+
+ ); +} + +function CopyButton({ value }: { value: string }) { + const [copied, setCopied] = useState(false); + const copy = async () => { + try { + await navigator.clipboard.writeText(value); + setCopied(true); + setTimeout(() => setCopied(false), 1500); + } catch { + setCopied(false); + } + }; + return ( + + ); +} + +function Chart({ + samples, + pick, + color, + label, +}: { + samples: Array<{ x: number; y: number }>; + pick: 'u' | 'residual'; + color: string; + label: string; +}) { + const width = 760; + const height = 240; + const pad = 36; + const ys = samples.map((s) => s.y); + const min = Math.min(0, ...ys); + const max = Math.max(0, ...ys); + const span = max - min || 1; + const xs = samples.map((s) => s.x); + const xMin = Math.min(...xs); + const xMax = Math.max(...xs); + const xSpan = xMax - xMin || 1; + const toX = (x: number) => pad + ((x - xMin) / xSpan) * (width - 2 * pad); + const toY = (y: number) => height - pad - ((y - min) / span) * (height - 2 * pad); + const polyline = samples.map((s) => `${toX(s.x)},${toY(s.y)}`).join(' '); + const zeroY = toY(0); + return ( +
+ + + + + + x = {formatNumber(xMin, 3)} + + + x = {formatNumber(xMax, 3)} + + + {pick === 'u' ? 'uₙ(x)' : 'R(x)'} ∈ [{formatNumber(min, 3)}, {formatNumber(max, 3)}] + + +
+ ); +} + +function fmt(value: number, digits: number): string { + return formatNumber(value, digits); +} + +function ResultView({ + result, + digits, +}: { + result: GalerkinResult; + digits: number; +}) { + const n = result.coefficients.length; + const copyText = `u_n(x) = ${result.phi0.text} + ${result.coefficients + .map((c, i) => `${fmt(c, digits)}*(${result.basis[i].text})`) + .join(' + ')}`; + + return ( + <> + + +

+ Oraliq [a, b] bo‘yicha ikkinchi tartibli chiziqli chegaraviy masala. +

+ + +
+ + + + +

+ Tenglamaning o‘ng tomoni f(x) = {result.fTex}. +

+
+
+ + + + +

+ Chap chegarada α₀φ₀(a)+α₁φ₀′(a) = {fmt(result.boundaryLeft.phi0, digits)} — + kutilgan {fmt(result.boundaryLeft.target, digits)}. O‘ng chegarada:{' '} + {fmt(result.boundaryRight.phi0, digits)} — kutilgan {fmt(result.boundaryRight.target, digits)}. +

+
+ + + {result.basis.map((phi, i) => ( + + ))} +

+ Har bir bazis funksiya bir jinsli chegaraviy shartlarni (α₀φ(a)+α₁φ′(a)=0, + β₀φ(b)+β₁φ′(b)=0) qanoatlantiradi — tekshiruv muvaffaqiyatli o‘tdi. +

+
+ + + + + + + + {result.basis.map((phi, i) => ( +
+ + + +
+ ))} +
+ + + + +
+ {result.integrals + .filter((item) => item.name.startsWith('a')) + .map((item) => ( +
+ +

+ Integrand qiymatlari (x = a … b):{' '} + {item.samples.map((s) => fmt(s.value, 4)).join(', ')} +

+

+ Natija: {fmt(item.value, digits)} · xato baholash: ±{fmt(item.error, 2)} +

+
+ ))} +
+
+ + + +
+ {result.integrals + .filter((item) => item.name.startsWith('b')) + .map((item) => ( +
+ +

+ Natija: {fmt(item.value, digits)} · xato baholash: ±{fmt(item.error, 2)} +

+
+ ))} +
+
+ + + + + + + + +

+ Sistema teskari matritsasiz, qisman tanlash (partial pivoting) bilan Gauss usulida yechildi. +

+
+
+ {result.coefficients.map((c, i) => ( +
+ +

{fmt(c, digits)}

+
+ ))} +
+
+ +
+
+ + Bosqich 11 · Yakuniy natija + + +
+
+ +
+
+ Aniqlik: {digits} xona · n = {n} +
+
+ + +
+ + + +
+

+ Galerkin ortogonallik qoldiqlari ∫φₖR(x)dx:{' '} + + {result.orthogonality.map((v) => fmt(v, 3)).join(', ')} + + . +

+ }> +

+ Galerkin ortogonalligi differensial tenglama har bir x nuqtada aniq bajarilishini anglatmaydi. + Quyidagi R(x) = L(uₙ) − f qoldiq funksiyasi bu farqni ko‘rsatadi. +

+
+ ({ x: s.x, y: s.residual }))} + pick="residual" + color="var(--brand)" + label="Qoldiq R(x) grafigi" + /> + ({ x: s.x, y: s.u }))} + pick="u" + color="var(--cyan)" + label="Taqribiy yechim uₙ(x) grafigi" + /> +
+ + ); +} + +function Stat({ label, value }: { label: string; value: string }) { + return ( +
+
{label}
+
{value}
+
+ ); +} + +function CoefficientMatrix({ result, digits }: { result: GalerkinResult; digits: number }) { + return ( +
+
+ {result.matrix.flatMap((row, r) => + row.map((value, c) => ( +
+ a{r + 1}{c + 1}= {fmt(value, digits)} +
+ )), + )} +
+
+ ); +} + +function SystemView({ result, digits }: { result: GalerkinResult; digits: number }) { + const n = result.rhs.length; + return ( + <> + + row.map((v, c) => `${v < 0 ? '' : '+'}${fmt(v, 4)}\\,C_{${c + 1}}`).join('') + + `=${fmt(result.rhs[r], 4)}`, + ) + .join(' \\\\ ')}\\end{cases}`} + /> + row.map((v) => fmt(v, 4)).join(' & ')) + .join(' \\\\ ')}\\end{pmatrix},\\quad B=\\begin{pmatrix}${result.rhs + .map((v) => fmt(v, 4)) + .join(' \\\\ ')}\\end{pmatrix}`} + /> +

n = {n} · hisoblash aniqligi {digits} xona

+ + ); +} + +export function GalerkinMethod() { + const [input, setInput] = useState(DEFAULT_INPUT); + const [result, setResult] = useState(null); + const [error, setError] = useState(''); + const [digits, setDigits] = useState<(typeof PRECISIONS)[number]>(6); + const resultRef = useScrollToResult(result); + + const update = (key: K, value: GalerkinInput[K]) => { + setInput((current) => ({ ...current, [key]: value })); + setResult(null); + setError(''); + }; + + const setBasisCount = (count: number) => { + const next = Array.from({ length: count }, (_, i) => + input.basis[i] ?? PRESET_BASIS[i] ?? `sin(${i + 1}*x)`, + ); + update('basis', next); + }; + + const submit = (event: FormEvent) => { + event.preventDefault(); + try { + setResult(solveGalerkin(input)); + setError(''); + } catch (cause) { + setResult(null); + setError(cause instanceof Error ? cause.message : 'Noma’lum xatolik.'); + } + }; + + const reset = () => { + setInput(DEFAULT_INPUT); + setResult(null); + setError(''); + }; + + const fieldClass = + 'w-full rounded-md border border-line bg-bg-2 px-3 py-2 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-brand/40'; + const labelClass = 'font-mono text-[11px] uppercase tracking-[.1em] text-muted'; + + return ( + <> + + +
+ + +
+ + + + + +
+ Chap chegara: α₀ u(a) + α₁ u′(a) = F_a + update('alpha0', e.target.value)} /> + update('alpha1', e.target.value)} /> + update('alphaValue', e.target.value)} /> +
+
+ O‘ng chegara: β₀ u(b) + β₁ u′(b) = F_b + update('beta0', e.target.value)} /> + update('beta1', e.target.value)} /> + update('betaValue', e.target.value)} /> +
+ +
+ Bazis funksiyalar soni (n) +
+ {[1, 2, 3, 4, 5, 6].map((count) => ( + + ))} +
+
+ {input.basis.map((source, index) => ( + + ))} +
+

+ Misol: sin(x), sin(2*x), x/pi, exp(x), x^2. Ifodalar xavfsiz parser orqali o‘qiladi. +

+
+ + + +
+
+
+ + {error && ( + }> +

{error}

+
+ )} + +
+ {result && ( + <> + +

+ Integrallar sonli usulda (Simpson, 800 bo‘lak) hisoblandi; simvolik integrallash qo‘llanmaydi. + Xato baholash taxminiy. +

+
+ + + )} +
+ + ); +} diff --git a/lib/galerkin.ts b/lib/galerkin.ts index 2905922..d8e00d6 100644 --- a/lib/galerkin.ts +++ b/lib/galerkin.ts @@ -89,7 +89,7 @@ function parseOrThrow(source: string, label: string): MathNode { node.traverse((child) => { if (child.type !== 'SymbolNode') return; const name = (child as unknown as { name: string }).name; - const isFunctionName = name in math && typeof math[name] === 'function'; + const isFunctionName = name in math && typeof Reflect.get(math, name) === 'function'; if (ALLOWED_SYMBOLS.has(name) || (isFunctionName && !FORBIDDEN_FUNCTIONS.has(name))) return; if (name in math && !isFunctionName) return; From 42db6460a76360676321bb09ee07dd029eb0ee78 Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 14:25:18 +0500 Subject: [PATCH 03/34] =?UTF-8?q?feat(galerkin):=20register=20Galerkin=20m?= =?UTF-8?q?ethod=20in=20navigation=20and=20hub=20=E2=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the Galerkin entry to the sidebar, the methods dashboard, page title lookup, i18n labels (uz/en/ru) and SEO keywords. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- components/app-shell.tsx | 9 +++++++++ components/dashboard/methods-hub.tsx | 14 ++++++++++++++ lib/config.ts | 2 ++ lib/i18n/locales/en.json | 6 ++++-- lib/i18n/locales/ru.json | 6 ++++-- lib/i18n/locales/uz.json | 6 ++++-- 6 files changed, 37 insertions(+), 6 deletions(-) diff --git a/components/app-shell.tsx b/components/app-shell.tsx index dd6d92b..1136962 100644 --- a/components/app-shell.tsx +++ b/components/app-shell.tsx @@ -10,6 +10,7 @@ import { ArrowUpRight, BookOpenText, Orbit, + Layers, ExternalLink, Info, LayoutDashboard, @@ -152,6 +153,12 @@ export function AppShell({ icon: Orbit, isNew: true, }, + { + href: '/methods/galerkin', + label: t('nav.galerkin'), + icon: Layers, + isNew: true, + }, ]; const sortedMethods = [...methodItems].sort((a, b) => { @@ -201,6 +208,8 @@ export function AppShell({ ? t('nav.bvp') : pathname.startsWith('/methods/collocation') ? t('nav.collocation') + : pathname.startsWith('/methods/galerkin') + ? t('nav.galerkin') : pathname.startsWith('/methods/sweep') ? t('nav.sweep') : pathname.startsWith('/methods/lagrange') diff --git a/components/dashboard/methods-hub.tsx b/components/dashboard/methods-hub.tsx index 3a0df5a..8e7a687 100644 --- a/components/dashboard/methods-hub.tsx +++ b/components/dashboard/methods-hub.tsx @@ -5,6 +5,7 @@ import Link from 'next/link'; import { Activity, ArrowRightLeft, + Layers, ArrowUpRight, Search, Sigma, @@ -202,6 +203,19 @@ const METHODS: MethodDef[] = [ icon: Activity, accentClass: 'text-amber-600 dark:text-amber-400 bg-amber-500/10 border-amber-500/25', }, + { + id: 'galerkin', + code: '14 / ODE', + category: 'odes', + categoryKey: 'dashboard.cat_odes', + titleKey: 'nav.galerkin', + descKey: 'dashboard.desc_galerkin', + href: '/methods/galerkin', + formulaTex: '\\int_a^b \\varphi_k\\,L(u_n)\\,dx = \\int_a^b \\varphi_k f\\,dx', + orderTex: 'n', + icon: Layers, + accentClass: 'text-cyan bg-cyan-soft border-cyan/25', + }, ]; function renderKatexSafe(tex: string, displayMode = false): string { diff --git a/lib/config.ts b/lib/config.ts index a049794..bf2cda3 100644 --- a/lib/config.ts +++ b/lib/config.ts @@ -86,6 +86,8 @@ export const siteConfig = { 'collocation method', 'collocation points', 'boundary value problem collocation', + 'galerkin method', + 'galerkin boundary value problem', 'math solver online', ], }; diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 9ac9417..132b916 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -20,7 +20,8 @@ "newtonInterpolation": "Newton Interpolation", "adamsPredictor": "Adams Predictor Method", "bvp": "Finite Difference BVP", - "collocation": "Collocation Method" + "collocation": "Collocation Method", + "galerkin": "Galerkin Method" }, "about": { "strip": "DOC-002 / ABOUT", @@ -117,7 +118,8 @@ "desc_newtonInterpolation": "Build the Newton polynomial from divided differences, compare finite differences, and evaluate P(x*) step by step.", "desc_adamsPredictor": "Solve an initial value problem with RK4 startup steps and the third-order Adams predictor formula.", "desc_bvp": "Solve second-order linear boundary value problems with finite differences and a step-by-step Thomas algorithm trace.", - "desc_collocation": "Solve second-order linear boundary value problems with basis functions and collocation points." + "desc_collocation": "Solve second-order linear boundary value problems with basis functions and collocation points.", + "desc_galerkin": "Solve second-order linear boundary value problems with basis functions and the Galerkin orthogonality condition." }, "actions": { "tools_badge": "EXPORT / TOOLS", diff --git a/lib/i18n/locales/ru.json b/lib/i18n/locales/ru.json index 724aff4..a3131d6 100644 --- a/lib/i18n/locales/ru.json +++ b/lib/i18n/locales/ru.json @@ -20,7 +20,8 @@ "newtonInterpolation": "Интерполяция Ньютона", "adamsPredictor": "Метод предиктора Адамса", "bvp": "Метод конечных разностей", - "collocation": "Метод коллокаций" + "collocation": "Метод коллокаций", + "galerkin": "Метод Галеркина" }, "about": { "strip": "DOC-002 / О ПРОЕКТЕ", @@ -117,7 +118,8 @@ "desc_newtonInterpolation": "Постройте многочлен Ньютона по разделённым разностям, сравните конечные разности и пошагово вычислите P(x*).", "desc_adamsPredictor": "Решите задачу Коши с начальными шагами Рунге — Кутты и формулой предиктора Адамса третьего порядка.", "desc_bvp": "Решение линейной краевой задачи второго порядка методом конечных разностей и пошаговой прогонкой Томаса.", - "desc_collocation": "Решение линейной краевой задачи второго порядка с базисными функциями и точками коллокации." + "desc_collocation": "Решение линейной краевой задачи второго порядка с базисными функциями и точками коллокации.", + "desc_galerkin": "Решение линейной краевой задачи второго порядка с базисными функциями и условием ортогональности Галеркина." }, "actions": { "tools_badge": "ЭКСПОРТ / ИНСТРУМЕНТЫ", diff --git a/lib/i18n/locales/uz.json b/lib/i18n/locales/uz.json index 4484b70..4961962 100644 --- a/lib/i18n/locales/uz.json +++ b/lib/i18n/locales/uz.json @@ -20,7 +20,8 @@ "newtonInterpolation": "Nyuton interpolyatsiyasi", "adamsPredictor": "Adams başorat qiluvçi usuli", "bvp": "Chekli ayirmalar usuli", - "collocation": "Kollokatsiya usuli" + "collocation": "Kollokatsiya usuli", + "galerkin": "Galyorkin usuli" }, "about": { "strip": "DOC-002 / HAQIDA", @@ -117,7 +118,8 @@ "desc_newtonInterpolation": "Bölingan ayirmalar orqali Nyuton köphadini tuzing, çekli ayirmalarni taqqoslang va P(x*) qiymatini qadam-baqadam hisoblang.", "desc_adamsPredictor": "Koşi masalasini RK4 boşlanğiç qadamlari va uçinçi tartibli Adams başorat formulasi bilan yeçing.", "desc_bvp": "Ikkinchi tartibli chiziqli chegaraviy masalani chekli ayirmalar va qadamma-qadam haydash (progonka) usuli bilan yeching.", - "desc_collocation": "Ikkinchi tartibli chiziqli chegaraviy masalani bazis funksiyalar va kollokatsiya nuqtalari orqali yeching." + "desc_collocation": "Ikkinchi tartibli chiziqli chegaraviy masalani bazis funksiyalar va kollokatsiya nuqtalari orqali yeching.", + "desc_galerkin": "Chegaraviy masalani bazis funksiyalar va Galyorkin ortogonallik sharti orqali yeching." }, "actions": { "tools_badge": "EXPORT / TOOLS", From b8c522b3d91aa962f17bce097540b3c8e24835d4 Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 14:39:44 +0500 Subject: [PATCH 04/34] =?UTF-8?q?fix(theme):=20animate=20both=20theme=20di?= =?UTF-8?q?rections=20and=20reduce=20toggle=20cost=20=F0=9F=90=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dark -> light had no visible animation: the new view sits on top, so animating the old snapshot was hidden. The new view now always expands from the click point. Removed the body background/color transition that ran on top of the view transition, and skip the animation when the user prefers reduced motion. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- app/globals.css | 2 -- components/theme-toggle.tsx | 41 ++++++++++++++++++------------------- 2 files changed, 20 insertions(+), 23 deletions(-) diff --git a/app/globals.css b/app/globals.css index 13312fd..d3d8e77 100644 --- a/app/globals.css +++ b/app/globals.css @@ -86,7 +86,6 @@ background-attachment: fixed; color: var(--ink); font-family: var(--font-sans); - transition: background .2s ease, color .2s ease; } button, input { font: inherit; } button { cursor: pointer; } @@ -151,7 +150,6 @@ ::view-transition-new(root) { z-index: 9999; } -/* When transitioning to dark, we can either expand the new dark theme, or shrink the old light theme */ /* Print Stream Navigation Top Loader */ #nprogress { diff --git a/components/theme-toggle.tsx b/components/theme-toggle.tsx index 90b375c..2e35665 100644 --- a/components/theme-toggle.tsx +++ b/components/theme-toggle.tsx @@ -1,4 +1,4 @@ -'use client'; +'use client'; import { Moon, Sun } from 'lucide-react'; import { useSyncExternalStore } from 'react'; @@ -22,14 +22,19 @@ export function ThemeToggle() { const theme = useSyncExternalStore(subscribe, getTheme, () => 'light'); const isDark = theme === 'dark'; + function applyTheme(next: Theme) { + document.documentElement.dataset.theme = next; + window.localStorage.setItem('numeric-theme', next); + window.dispatchEvent(new Event(themeEvent)); + } + function toggleTheme(event: React.MouseEvent) { const next: Theme = isDark ? 'light' : 'dark'; + const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches; - // Fallback for browsers that don't support View Transitions - if (!document.startViewTransition) { - document.documentElement.dataset.theme = next; - window.localStorage.setItem('numeric-theme', next); - window.dispatchEvent(new Event(themeEvent)); + // Instant switch: no View Transitions support or the user prefers reduced motion + if (!document.startViewTransition || reduceMotion) { + applyTheme(next); return; } @@ -40,29 +45,23 @@ export function ThemeToggle() { Math.max(y, innerHeight - y) ); - const transition = document.startViewTransition(() => { - document.documentElement.dataset.theme = next; - window.localStorage.setItem('numeric-theme', next); - window.dispatchEvent(new Event(themeEvent)); - }); + const transition = document.startViewTransition(() => applyTheme(next)); + // The new view always expands from the click point, in both directions. + // Animating the old snapshot (dark -> light) was invisible because the new + // view is layered on top of it. transition.ready.then(() => { - const clipPath = [ - `circle(0px at ${x}px ${y}px)`, - `circle(${endRadius}px at ${x}px ${y}px)`, - ]; - - // To light: new view expands. To dark: old view shrinks (revealing dark underneath) document.documentElement.animate( { - clipPath: isDark ? [...clipPath].reverse() : clipPath, + clipPath: [ + `circle(0px at ${x}px ${y}px)`, + `circle(${endRadius}px at ${x}px ${y}px)`, + ], }, { duration: 400, easing: 'cubic-bezier(0.4, 0, 0.2, 1)', - pseudoElement: isDark - ? '::view-transition-old(root)' - : '::view-transition-new(root)', + pseudoElement: '::view-transition-new(root)', } ); }); From 83892732fec464c75ad562c1b1abd2f5a8bd379d Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 14:45:54 +0500 Subject: [PATCH 05/34] =?UTF-8?q?style(dashboard):=20compact=20workspace?= =?UTF-8?q?=20status=20cards=20on=20mobile=20=F0=9F=8E=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stat cards are now single-row items on small screens instead of tall 140px blocks. The original card layout is kept from the md breakpoint up. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- components/dashboard/dashboard-view.tsx | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/components/dashboard/dashboard-view.tsx b/components/dashboard/dashboard-view.tsx index d650a7f..ab3c329 100644 --- a/components/dashboard/dashboard-view.tsx +++ b/components/dashboard/dashboard-view.tsx @@ -46,25 +46,27 @@ export function DashboardView() { title={t('dashboard.overview')} idx="SYS" /> -
+
{stats.map(([number, label, value, mark]) => (
- + {number} - +
+ + {label} + + + {value} + +
+ {mark} - - {label} - - - {value} - - + ↗
From fe1f2fe0d497fa12094990c2402ce8f2e6193432 Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 14:55:44 +0500 Subject: [PATCH 06/34] =?UTF-8?q?style(dashboard):=20fix=20container=20max?= =?UTF-8?q?-width=20and=20tighten=20panel=20header=20on=20mobile=20?= =?UTF-8?q?=F0=9F=8E=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dashboard container used an invalid class (ax-w-290), so its max-width never applied. Panel headers now use smaller spacing and title size on phones. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- components/dashboard/dashboard-view.tsx | 4 ++-- components/ui/print-stream.tsx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/components/dashboard/dashboard-view.tsx b/components/dashboard/dashboard-view.tsx index ab3c329..52b2aaf 100644 --- a/components/dashboard/dashboard-view.tsx +++ b/components/dashboard/dashboard-view.tsx @@ -21,7 +21,7 @@ export function DashboardView() { ]; return ( -
+
{stats.map(([number, label, value, mark]) => (
diff --git a/components/ui/print-stream.tsx b/components/ui/print-stream.tsx index 667e1e9..1187312 100644 --- a/components/ui/print-stream.tsx +++ b/components/ui/print-stream.tsx @@ -95,12 +95,12 @@ export function PsPanel({ children, className = '' }: { children: React.ReactNod export function PsPanelHead({ eyebrow, title, idx }: { eyebrow: string; title: string; idx: string }) { return ( -
+
{eyebrow} -

+

{title}

From 00e35efd6e5219a23430b832ab354dbd55637903 Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 14:55:45 +0500 Subject: [PATCH 07/34] =?UTF-8?q?perf(ui):=20remove=20fixed=20background?= =?UTF-8?q?=20and=20narrow=20card=20transitions=20=E2=9A=A1=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixed body background forces repaints on every scroll, which is costly on phones. Removed it. Replaced transition-all on dashboard and method cards with the specific properties that change, so the browser animates less. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- app/globals.css | 1 - components/dashboard/methods-hub.tsx | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/app/globals.css b/app/globals.css index d3d8e77..0e84b5b 100644 --- a/app/globals.css +++ b/app/globals.css @@ -83,7 +83,6 @@ body { margin: 0; min-width: 320px; background: var(--page-glow), var(--bg); - background-attachment: fixed; color: var(--ink); font-family: var(--font-sans); } diff --git a/components/dashboard/methods-hub.tsx b/components/dashboard/methods-hub.tsx index 8e7a687..0cf460b 100644 --- a/components/dashboard/methods-hub.tsx +++ b/components/dashboard/methods-hub.tsx @@ -335,7 +335,7 @@ export function MethodsHub() { key={method.id} href={method.href} prefetch={false} - className="group relative flex flex-col justify-between p-5 rounded-xl border border-line bg-bg-2 shadow-xs transition-all duration-200 hover:-translate-y-1 hover:border-brand hover:bg-panel hover:shadow-md cursor-pointer" + className="group relative flex flex-col justify-between p-5 rounded-xl border border-line bg-bg-2 shadow-xs transition-[transform,box-shadow,border-color,background-color] duration-200 hover:-translate-y-1 hover:border-brand hover:bg-panel hover:shadow-md cursor-pointer" >
{/* Top Bar: Code, Category & Order */} From bc37b9cae593c22dec1a82b4519d3b250e3fe495 Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 15:06:52 +0500 Subject: [PATCH 08/34] =?UTF-8?q?feat(galerkin):=20simplify=20input=20to?= =?UTF-8?q?=20notebook-style=20defaults=20=E2=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Default form now asks only for p, q, f, a, b, u(a), u(b), phi0, n and a single basis template (sin(i*x)). Boundary coefficients (alpha/beta) and per-function basis fields are behind "Kengaytirilgan sozlamalar". A live equation preview shows the entered problem in LaTeX. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- components/galerkin-method.tsx | 188 +++++++++++++++++++++++---------- 1 file changed, 133 insertions(+), 55 deletions(-) diff --git a/components/galerkin-method.tsx b/components/galerkin-method.tsx index 7c6540e..4c31257 100644 --- a/components/galerkin-method.tsx +++ b/components/galerkin-method.tsx @@ -1,6 +1,7 @@ 'use client'; import { useState, type FormEvent, type ReactNode } from 'react'; +import { math } from '@/lib/math'; import katex from 'katex'; import { Calculator, Check, Copy, Info } from 'lucide-react'; import { @@ -34,6 +35,7 @@ const DEFAULT_INPUT: GalerkinInput = { basis: ['sin(x)', 'sin(2*x)'], }; +const DEFAULT_TEMPLATE = 'sin(i*x)'; const PRESET_BASIS = ['sin(x)', 'sin(2*x)', 'sin(3*x)', 'sin(4*x)', 'sin(5*x)', 'sin(6*x)']; const PRECISIONS = [4, 6, 8, 12] as const; @@ -387,8 +389,26 @@ function SystemView({ result, digits }: { result: GalerkinResult; digits: number ); } +function basisFromTemplate(template: string, count: number): string[] { + return Array.from({ length: count }, (_, k) => template.replace(/\bi\b/g, String(k + 1))); +} + +function equationTex(p: string, q: string, f: string): string { + const tex = (source: string) => { + try { + return math.parse(source.trim() || '0').toTex(); + } catch { + return '\\text{?}'; + } + }; + return `u''+\\left(${tex(p)}\\right)u'+\\left(${tex(q)}\\right)u=${tex(f)}`; +} + export function GalerkinMethod() { const [input, setInput] = useState(DEFAULT_INPUT); + const [template, setTemplate] = useState(DEFAULT_TEMPLATE); + const [count, setCount] = useState(2); + const [advanced, setAdvanced] = useState(false); const [result, setResult] = useState(null); const [error, setError] = useState(''); const [digits, setDigits] = useState<(typeof PRECISIONS)[number]>(6); @@ -400,17 +420,24 @@ export function GalerkinMethod() { setError(''); }; - const setBasisCount = (count: number) => { - const next = Array.from({ length: count }, (_, i) => - input.basis[i] ?? PRESET_BASIS[i] ?? `sin(${i + 1}*x)`, - ); - update('basis', next); + const changeTemplate = (value: string) => { + setTemplate(value); + update('basis', basisFromTemplate(value, count)); + }; + + const changeCount = (value: number) => { + setCount(value); + update('basis', basisFromTemplate(template, value)); }; const submit = (event: FormEvent) => { event.preventDefault(); + // Simple mode uses Dirichlet conditions: u(a) and u(b) are given directly + const payload: GalerkinInput = advanced + ? input + : { ...input, alpha0: '1', alpha1: '0', beta0: '1', beta1: '0' }; try { - setResult(solveGalerkin(input)); + setResult(solveGalerkin(payload)); setError(''); } catch (cause) { setResult(null); @@ -420,13 +447,17 @@ export function GalerkinMethod() { const reset = () => { setInput(DEFAULT_INPUT); + setTemplate(DEFAULT_TEMPLATE); + setCount(2); + setAdvanced(false); setResult(null); setError(''); }; const fieldClass = - 'w-full rounded-md border border-line bg-bg-2 px-3 py-2 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-brand/40'; + 'w-full rounded-md border border-line bg-bg-2 px-3 py-2.5 font-mono text-base sm:text-sm focus:outline-none focus:ring-2 focus:ring-brand/40'; const labelClass = 'font-mono text-[11px] uppercase tracking-[.1em] text-muted'; + const hintClass = 'text-xs leading-[1.5] text-muted'; return ( <> @@ -439,92 +470,116 @@ export function GalerkinMethod() {
- + + +
+
+
+
+ -
- Chap chegara: α₀ u(a) + α₁ u′(a) = F_a - update('alpha0', e.target.value)} /> - update('alpha1', e.target.value)} /> - update('alphaValue', e.target.value)} /> -
-
- O‘ng chegara: β₀ u(b) + β₁ u′(b) = F_b - update('beta0', e.target.value)} /> - update('beta1', e.target.value)} /> - update('betaValue', e.target.value)} /> -
+ + {advanced ? ( + <> +
+ Chap: α₀·u(a) + α₁·u′(a) = F_a + update('alpha0', e.target.value)} /> + update('alpha1', e.target.value)} /> + update('alphaValue', e.target.value)} /> +
+
+ O‘ng: β₀·u(b) + β₁·u′(b) = F_b + update('beta0', e.target.value)} /> + update('beta1', e.target.value)} /> + update('betaValue', e.target.value)} /> +
+ + ) : ( + <> + + + + )} + -
+ +
Bazis funksiyalar soni (n)
- {[1, 2, 3, 4, 5, 6].map((count) => ( + {[1, 2, 3, 4, 5, 6].map((value) => ( ))}
- {input.basis.map((source, index) => ( - - ))} + +
-

- Misol: sin(x), sin(2*x), x/pi, exp(x), x^2. Ifodalar xavfsiz parser orqali o‘qiladi. -

+
+
+ + {advanced && ( +
+

+ Kengaytirilgan rejim: chegaraviy shartlar umumiy ko‘rinishda (α, β) va har bir bazis funksiyani alohida kiritish. +

+ {input.basis.map((source, index) => ( + + ))} +
+ )} From be4f73a28eaeba4c42f4c20de1bf7a735f0dd85d Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 15:15:51 +0500 Subject: [PATCH 09/34] =?UTF-8?q?feat(galerkin):=20empty=20form=20on=20loa?= =?UTF-8?q?d,=20a2=20coefficient=20and=20sample=20button=20=E2=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Galerkin page starts with empty inputs. Coefficients follow the collocation naming: a2 (u''), a1 (u'), a0 (u), f. Empty a2 means 1; empty a1, a0 and f mean 0. Required fields (a, b, boundary values, phi0, basis) show a clear error when empty. "Namuna masala" loads the notebook problem and "Tozalash" clears the form. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- components/galerkin-method.tsx | 98 +++++++++++++++++++++++++--------- lib/galerkin.ts | 34 +++++++----- 2 files changed, 93 insertions(+), 39 deletions(-) diff --git a/components/galerkin-method.tsx b/components/galerkin-method.tsx index 4c31257..8b64c2b 100644 --- a/components/galerkin-method.tsx +++ b/components/galerkin-method.tsx @@ -19,9 +19,29 @@ import { type GalerkinResult, } from '@/lib/galerkin'; -const DEFAULT_INPUT: GalerkinInput = { - p: '-cos(x)', - q: 'sin(x)', +// Empty form on page load; the user enters their own problem +const EMPTY_INPUT: GalerkinInput = { + a2: '', + a1: '', + a0: '', + f: '', + a: '', + b: '', + alpha0: '1', + alpha1: '0', + alphaValue: '', + beta0: '1', + beta1: '0', + betaValue: '', + phi0: '', + basis: [], +}; + +// Notebook example: u'' - u' cos x + u sin x = sin x, u(0)=1, u(pi)=2 +const SAMPLE_INPUT: GalerkinInput = { + a2: '1', + a1: '-cos(x)', + a0: 'sin(x)', f: 'sin(x)', a: '0', b: 'pi', @@ -35,8 +55,7 @@ const DEFAULT_INPUT: GalerkinInput = { basis: ['sin(x)', 'sin(2*x)'], }; -const DEFAULT_TEMPLATE = 'sin(i*x)'; -const PRESET_BASIS = ['sin(x)', 'sin(2*x)', 'sin(3*x)', 'sin(4*x)', 'sin(5*x)', 'sin(6*x)']; +const SAMPLE_TEMPLATE = 'sin(i*x)'; const PRECISIONS = [4, 6, 8, 12] as const; function katexHtml(source: string, displayMode: boolean): string { @@ -186,7 +205,7 @@ function ResultView({ - +

Tenglamaning o‘ng tomoni f(x) = {result.fTex}. @@ -393,20 +412,31 @@ function basisFromTemplate(template: string, count: number): string[] { return Array.from({ length: count }, (_, k) => template.replace(/\bi\b/g, String(k + 1))); } -function equationTex(p: string, q: string, f: string): string { - const tex = (source: string) => { +function equationTex(a2: string, a1: string, a0: string, f: string): string { + const tex = (source: string): string | null => { + if (!source.trim()) return null; try { - return math.parse(source.trim() || '0').toTex(); + return math.parse(source.trim()).toTex(); } catch { return '\\text{?}'; } }; - return `u''+\\left(${tex(p)}\\right)u'+\\left(${tex(q)}\\right)u=${tex(f)}`; + // Empty u'' coefficient means 1; other empty terms are omitted + const a2t = tex(a2); + const a1t = tex(a1); + const a0t = tex(a0); + const ft = tex(f) ?? '0'; + const lhs = [ + a2t ? `\\left(${a2t}\\right)u''` : "u''", + a1t ? `+\\left(${a1t}\\right)u'` : '', + a0t ? `+\\left(${a0t}\\right)u` : '', + ].join(''); + return `${lhs}=${ft}`; } export function GalerkinMethod() { - const [input, setInput] = useState(DEFAULT_INPUT); - const [template, setTemplate] = useState(DEFAULT_TEMPLATE); + const [input, setInput] = useState(EMPTY_INPUT); + const [template, setTemplate] = useState(''); const [count, setCount] = useState(2); const [advanced, setAdvanced] = useState(false); const [result, setResult] = useState(null); @@ -446,14 +476,21 @@ export function GalerkinMethod() { }; const reset = () => { - setInput(DEFAULT_INPUT); - setTemplate(DEFAULT_TEMPLATE); + setInput(SAMPLE_INPUT); + setTemplate(SAMPLE_TEMPLATE); setCount(2); setAdvanced(false); setResult(null); setError(''); }; + const clear = () => { + setInput(EMPTY_INPUT); + setTemplate(''); + setResult(null); + setError(''); + }; + const fieldClass = 'w-full rounded-md border border-line bg-bg-2 px-3 py-2.5 font-mono text-base sm:text-sm focus:outline-none focus:ring-2 focus:ring-brand/40'; const labelClass = 'font-mono text-[11px] uppercase tracking-[.1em] text-muted'; @@ -473,23 +510,29 @@ export function GalerkinMethod() {

-
+
+
@@ -574,6 +619,9 @@ export function GalerkinMethod() { +
+
- +
+ + {template.trim() && ( +

+ {input.basis.map((item, index) => `φ${index + 1} = ${item}`).join(' ')} +

+ )}
-
+
- - {advanced && ( -
-

- Kengaytirilgan rejim: chegaraviy shartlar umumiy ko‘rinishda (α, β) va har bir bazis funksiyani alohida kiritish. -

- {input.basis.map((source, index) => ( - - ))} -
- )} From 35288e55ababc63fe1dcdbd727d666111d987759 Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 16:19:41 +0500 Subject: [PATCH 13/34] =?UTF-8?q?fix(galerkin):=20accept=20Pi=20in=20any?= =?UTF-8?q?=20capitalisation=20=F0=9F=90=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit mathjs only recognises lowercase pi, so inputs like "Pi" or "-Pi" failed with a misleading "number expected" error. Constants are normalised before parsing. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- lib/galerkin.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/lib/galerkin.ts b/lib/galerkin.ts index 85b43ba..049ba58 100644 --- a/lib/galerkin.ts +++ b/lib/galerkin.ts @@ -79,8 +79,13 @@ const SIMPSON_N = 800; type Scope = Record; +// Accept Pi, PI, pI as well as pi +function normalizeConstants(source: string): string { + return source.replace(/\bpi\b/gi, 'pi'); +} + function parseOrThrow(source: string, label: string): MathNode { - const text = source.trim(); + const text = normalizeConstants(source.trim()); if (!text) throw new Error(`${label} bo‘sh bo‘lmasligi kerak.`); let node: MathNode; try { @@ -132,7 +137,7 @@ function makeFunction(source: string, label: string): GalerkinFunction { function parseNumber(value: string, label: string): number { if (!value.trim()) throw new Error(`${label} kiritilishi shart.`); try { - const result = Number(math.evaluate(value.trim())); + const result = Number(math.evaluate(normalizeConstants(value.trim()))); if (!Number.isFinite(result)) throw new Error(); return result; } catch { From d33143960b1892ac51d895977e57d8f7618f6604 Mon Sep 17 00:00:00 2001 From: hexjasur Date: Wed, 25 Nov 2026 16:41:45 +0500 Subject: [PATCH 14/34] =?UTF-8?q?feat(galerkin):=20add=20blackboard=20meth?= =?UTF-8?q?od=20option=20to=20match=20classroom=20solutions=20=E2=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Standard Galerkin requires basis functions that vanish at the boundary. The classroom solution uses x^2-3 and x^3-4, which do not, so the solver rejected it. A new option skips that check. With the same inputs the integrals and coefficients now match the board (a11 = -22.9333, a12 = -31.1667, a21 = -32.3333, a22 = -44.2286). The verification section shows the boundary errors that method produces. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- components/galerkin-method.tsx | 27 ++++++++++++++++++++++++--- lib/galerkin.ts | 4 +++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/components/galerkin-method.tsx b/components/galerkin-method.tsx index 03048c4..4f64b05 100644 --- a/components/galerkin-method.tsx +++ b/components/galerkin-method.tsx @@ -463,6 +463,7 @@ export function GalerkinMethod() { const [template, setTemplate] = useState(''); const [count, setCount] = useState(2); const [advanced, setAdvanced] = useState(false); + const [board, setBoard] = useState(false); const [result, setResult] = useState(null); const [error, setError] = useState(''); const [digits, setDigits] = useState<(typeof PRECISIONS)[number]>(6); @@ -487,9 +488,10 @@ export function GalerkinMethod() { const submit = (event: FormEvent) => { event.preventDefault(); // Simple mode uses Dirichlet conditions: u(a) and u(b) are given directly - const payload: GalerkinInput = advanced - ? input - : { ...input, alpha0: '1', alpha1: '0', beta0: '1', beta1: '0' }; + const payload: GalerkinInput = { + ...(advanced ? input : { ...input, alpha0: '1', alpha1: '0', beta0: '1', beta1: '0' }), + allowNonHomogeneousBasis: board, + }; try { setResult(solveGalerkin(payload)); setError(''); @@ -602,6 +604,18 @@ export function GalerkinMethod() { )}
+ +
); } @@ -190,6 +198,7 @@ function ResultView({ result: GalerkinResult; digits: number; }) { + const { t } = useI18n(); const n = result.coefficients.length; const copyText = `u_n(x) = ${result.phi0.text} + ${result.coefficients .map((c, i) => `${fmt(c, digits)}*(${result.basis[i].text})`) @@ -197,52 +206,50 @@ function ResultView({ return ( <> - + -

- Oraliq [a, b] bo‘yicha ikkinchi tartibli chiziqli chegaraviy masala. -

+

{t('galerkin.s1_text')}

- +

- Tenglamaning o‘ng tomoni . + {t('galerkin.s2_rhs')} .

- +

- Chap chegarada α₀φ₀(a)+α₁φ₀′(a) = {fmt(result.boundaryLeft.phi0, digits)} — - kutilgan {fmt(result.boundaryLeft.target, digits)}. O‘ng chegarada:{' '} - {fmt(result.boundaryRight.phi0, digits)} — kutilgan {fmt(result.boundaryRight.target, digits)}. + {t('galerkin.s3_text', { + left: fmt(result.boundaryLeft.phi0, digits), + leftTarget: fmt(result.boundaryLeft.target, digits), + right: fmt(result.boundaryRight.phi0, digits), + rightTarget: fmt(result.boundaryRight.target, digits), + })}

- + {result.basis.map((phi, i) => ( ))} -

- Har bir bazis funksiya bir jinsli chegaraviy shartlarni (α₀φ(a)+α₁φ′(a)=0, - β₀φ(b)+β₁φ′(b)=0) qanoatlantiradi — tekshiruv muvaffaqiyatli o‘tdi. -

+

{t('galerkin.s4_text')}

- + - + {result.basis.map((phi, i) => ( -
+
@@ -250,7 +257,7 @@ function ResultView({ ))} - +
@@ -260,18 +267,18 @@ function ResultView({

- Integrand qiymatlari (x = a … b):{' '} + {t('galerkin.s7_samples')}{' '} {item.samples.map((s) => fmt(s.value, 4)).join(', ')}

- Natija: {fmt(item.value, digits)} · xato baholash: ±{fmt(item.error, 2)} + {t('galerkin.result', { value: fmt(item.value, digits), error: fmt(item.error, 2) })}

))}
- +
{result.integrals @@ -280,23 +287,21 @@ function ResultView({

- Natija: {fmt(item.value, digits)} · xato baholash: ±{fmt(item.error, 2)} + {t('galerkin.result', { value: fmt(item.value, digits), error: fmt(item.error, 2) })}

))}
- + - + -

- Sistema teskari matritsasiz, qisman tanlash (partial pivoting) bilan Gauss usulida yechildi. -

+

{t('galerkin.s10_note')}

{result.coefficients.map((c, i) => ( @@ -311,7 +316,7 @@ function ResultView({
- Bosqich 11 · Yakuniy natija + {t('galerkin.final_step')}
@@ -319,40 +324,37 @@ function ResultView({
- Aniqlik: {digits} xona · n = {n} + {t('galerkin.final_meta', { precision: digits, n })}
- +
- - - + + +

- Galerkin ortogonallik qoldiqlari ∫φₖR(x)dx:{' '} + {t('galerkin.s12_orthogonality')}{' '} {result.orthogonality.map((v) => fmt(v, 3)).join(', ')} .

}> -

- Galerkin ortogonalligi differensial tenglama har bir x nuqtada aniq bajarilishini anglatmaydi. - Quyidagi R(x) = L(uₙ) − f qoldiq funksiyasi bu farqni ko‘rsatadi. -

+

{t('galerkin.s12_note')}

({ x: s.x, y: s.residual }))} pick="residual" color="var(--brand)" - label="Qoldiq R(x) grafigi" + label={t('galerkin.chart_residual')} /> ({ x: s.x, y: s.u }))} pick="u" color="var(--cyan)" - label="Taqribiy yechim uₙ(x) grafigi" + label={t('galerkin.chart_solution')} />
@@ -386,6 +388,7 @@ function CoefficientMatrix({ result, digits }: { result: GalerkinResult; digits: } function SystemView({ result, digits }: { result: GalerkinResult; digits: number }) { + const { t } = useI18n(); const n = result.rhs.length; return ( <> @@ -405,7 +408,7 @@ function SystemView({ result, digits }: { result: GalerkinResult; digits: number .map((v) => fmt(v, 4)) .join(' \\\\ ')}\\end{pmatrix}`} /> -

n = {n} · hisoblash aniqligi {digits} xona

+

{t('galerkin.system_meta', { n, precision: digits })}

); } @@ -414,6 +417,11 @@ function basisFromTemplate(template: string, count: number): string[] { return Array.from({ length: count }, (_, k) => template.replace(/\bi\b/g, String(k + 1))); } +// Empty template → empty basis, so the solver builds φᵢ itself (autoCount) +function buildBasis(template: string, count: number): string[] { + return template.trim() ? basisFromTemplate(template, count) : []; +} + function equationTex(a2: string, a1: string, a0: string, f: string): string { // Empty u'' coefficient means 1; empty u′ and u coefficients mean 0; empty f means 0 const term = (source: string, fallback: string): TexTerm => { @@ -428,6 +436,12 @@ function equationTex(a2: string, a1: string, a0: string, f: string): string { return `${lhs}=${term(f, '0').tex}`; } +// Translated message for a solver error; unexpected errors get a generic text +function describeError(cause: unknown, t: Translate): string { + if (cause instanceof GalerkinError) return t(`galerkin.errors.${cause.code}`, cause.params); + return t('galerkin.unknown_error'); +} + function Field({ label, placeholder, @@ -453,6 +467,7 @@ function Field({ } export function GalerkinMethod() { + const { t } = useI18n(); const [input, setInput] = useState(EMPTY_INPUT); const [template, setTemplate] = useState(''); const [count, setCount] = useState(2); @@ -469,9 +484,6 @@ export function GalerkinMethod() { setError(''); }; - // Empty template → empty basis, so the solver builds φᵢ itself (autoCount) - const buildBasis = (tpl: string, n: number) => (tpl.trim() ? basisFromTemplate(tpl, n) : []); - const changeTemplate = (value: string) => { setTemplate(value); update('basis', buildBasis(value, count)); @@ -495,7 +507,7 @@ export function GalerkinMethod() { setError(''); } catch (cause) { setResult(null); - setError(cause instanceof Error ? cause.message : 'Noma’lum xatolik.'); + setError(describeError(cause, t)); } }; @@ -521,31 +533,31 @@ export function GalerkinMethod() { return ( <>
- +
- Tenglama koeffitsiyentlari + {t('galerkin.coefficients')} update('a2', v)} /> update('a1', v)} /> update('a0', v)} /> update('f', v)} />
-

Bo‘sh qolsa: a₂ = 1, qolganlari = 0.

+

{t('galerkin.coefficients_hint')}

- Oraliq va chegara shartlari + {t('galerkin.interval')} update('a', v)} /> update('b', v)} /> update('alphaValue', v)} /> @@ -554,7 +566,7 @@ export function GalerkinMethod() { {advanced && (
- Umumiy chegara: α₀u + α₁u′ = F · β₀u + β₁u′ = F + {t('galerkin.advanced_legend')} update('alpha0', v)} /> update('alpha1', v)} /> update('beta0', v)} /> @@ -564,13 +576,13 @@ export function GalerkinMethod() {
update('phi0', v)} />
- n + {t('galerkin.n_label')}
{[1, 2, 3, 4, 5, 6].map((value) => (
@@ -613,9 +623,7 @@ export function GalerkinMethod() { onChange={(e) => setBoard(e.target.checked)} className="mt-0.5" /> - - Bazis funksiyalar chegarada nolga teng bo‘lishi shart emas. Bu usulda chegaraviy shartlar aniq bajarilmasligi mumkin. - + {t('galerkin.board_label')}
@@ -624,23 +632,23 @@ export function GalerkinMethod() { className="inline-flex items-center gap-2 rounded-md bg-brand px-4 py-2.5 text-sm font-semibold text-white" > - Yechish + {t('galerkin.submit')}
diff --git a/lib/galerkin.ts b/lib/galerkin.ts index 835dd5b..5ff1734 100644 --- a/lib/galerkin.ts +++ b/lib/galerkin.ts @@ -142,6 +142,27 @@ function texTerm(node: MathNode): TexTerm { return { tex: cleanTex(node.toTex()), atomic }; } +// Legendre polynomials P0, P1, … in t, where t maps [a, b] to [-1, 1] +const LEGENDRE = [ + '1', + 't', + '(3*t^2-1)/2', + '(5*t^3-3*t)/2', + '(35*t^4-30*t^2+3)/8', + '(63*t^5-70*t^3+15*t)/8', + '(231*t^6-315*t^4+105*t^2-5)/16', + '(429*t^7-693*t^5+315*t^3-35*t)/16', +]; + +// Legendre-type basis: φᵢ = (x − a)(b − x)·P_{i−1}(t). The factor makes every φᵢ +// vanish at both ends, so the basis fits Dirichlet conditions. +export function legendreBasis(a: string, b: string, count: number): string[] { + const t = `((2*x-(${a})-(${b}))/((${b})-(${a})))`; + return LEGENDRE.slice(0, count).map( + (p) => `((x-(${a}))*((${b})-x))*${p.split('t').join(t)}`, + ); +} + export function exprTex(source: string): TexTerm { return texTerm(math.parse(normalizeInput(source.trim()))); } diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index f33342c..22fe4fe 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -985,6 +985,8 @@ "n_label": "n", "template_label": "φᵢ(x) template (i = 1, 2, …, n) — empty = automatic", "auto_placeholder": "automatic", + "legendre_button": "Legendre basis", + "legendre_hint": "φᵢ = (x − a)(b − x)·P(i−1)(t), zero at both ends. For Dirichlet problems.", "template_auto": "Automatic: φᵢ = (x − a)^(i+1) − linear correction, matching the boundary conditions.", "board_label": "Basis functions need not vanish at the boundary. With this option the boundary conditions may not hold exactly.", "submit": "Solve", diff --git a/lib/i18n/locales/ru.json b/lib/i18n/locales/ru.json index 47dfac2..eb157df 100644 --- a/lib/i18n/locales/ru.json +++ b/lib/i18n/locales/ru.json @@ -985,6 +985,8 @@ "n_label": "n", "template_label": "Шаблон φᵢ(x) (i = 1, 2, …, n) — пусто = автоматически", "auto_placeholder": "автоматически", + "legendre_button": "Базис Лежандра", + "legendre_hint": "φᵢ = (x − a)(b − x)·P(i−1)(t), равны нулю на концах. Для задач Дирихле.", "template_auto": "Автоматически: φᵢ = (x − a)^(i+1) − линейная поправка, согласованная с граничными условиями.", "board_label": "Базисные функции не обязаны обращаться в ноль на границе. С этой опцией граничные условия могут выполняться неточно.", "submit": "Решить", diff --git a/lib/i18n/locales/uz.json b/lib/i18n/locales/uz.json index 8c0a615..9275b68 100644 --- a/lib/i18n/locales/uz.json +++ b/lib/i18n/locales/uz.json @@ -985,6 +985,8 @@ "n_label": "n", "template_label": "φᵢ(x) shabloni (i = 1, 2, …, n) — bo‘sh qolsa avtomatik", "auto_placeholder": "avtomatik", + "legendre_button": "Legendre bazisi", + "legendre_hint": "φᵢ = (x − a)(b − x)·P(i−1)(t), chegarada nolga teng. Dirichlet masalalari uchun.", "template_auto": "Avtomatik: φᵢ = (x − a)^(i+1) − chiziqli tuzatma, chegara shartlarga mos.", "board_label": "Bazis funksiyalar chegarada nolga teng bo‘lishi shart emas. Bu usulda chegaraviy shartlar aniq bajarilmasligi mumkin.", "submit": "Yechish", From 2d8da4466ae100a35b165ad2966ca1a2aa385aeb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 13:53:43 +0500 Subject: [PATCH 24/34] =?UTF-8?q?fix(galerkin):=20round=20formulas=20to=20?= =?UTF-8?q?chosen=20precision=20and=20expand=20final=20u=E2=82=99=20?= =?UTF-8?q?=F0=9F=90=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every decimal in result formulas follows the precision selector. The final approximation is written as an expanded polynomial when uₙ is a polynomial (automatic and Legendre bases), checked against the sum at extra points; otherwise the basis sum is kept. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- components/galerkin-method.tsx | 33 ++++++++++++++++------- lib/galerkin.ts | 49 ++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 9 deletions(-) diff --git a/components/galerkin-method.tsx b/components/galerkin-method.tsx index 84a8bb9..3b91ce7 100644 --- a/components/galerkin-method.tsx +++ b/components/galerkin-method.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useState, type FormEvent, type ReactNode } from 'react'; +import { createContext, useContext, useState, type FormEvent, type ReactNode } from 'react'; import katex from 'katex'; import { Calculator, Check, Copy, Info } from 'lucide-react'; import { @@ -14,6 +14,7 @@ import { useI18n } from '@/components/i18n-provider'; import { GalerkinError, exprTex, + expandedApproximation, formatNumber, legendreBasis, operatorLhsTex, @@ -69,12 +70,21 @@ function katexHtml(source: string, displayMode: boolean): string { return katex.renderToString(source, { throwOnError: false, displayMode }); } +// Precision chosen by the user; every decimal in result formulas is rounded to it +const PrecisionContext = createContext(6); + +function roundNumbers(source: string, digits: number): string { + return source.replace(/\d+\.\d+/g, (m) => String(Number(Number(m).toFixed(digits)))); +} + function Tex({ value, block = true }: { value: string; block?: boolean }) { + const digits = useContext(PrecisionContext); + const text = roundNumbers(value, digits); // Inline formulas are spans so they can sit inside paragraphs return block ? ( -
+
) : ( - + ); } @@ -201,9 +211,14 @@ function ResultView({ }) { const { t } = useI18n(); const n = result.coefficients.length; - const copyText = `u_n(x) = ${result.phi0.text} + ${result.coefficients - .map((c, i) => `${fmt(c, digits)}*(${result.basis[i].text})`) - .join(' + ')}`; + // Fully expanded form when uₙ is a polynomial; otherwise the sum of basis terms + const expanded = expandedApproximation(result, digits); + const finalTex = expanded ? `u_n(x)=${expanded.tex}` : result.finalTex; + const copyText = expanded + ? `u_n(x) = ${expanded.text}` + : `u_n(x) = ${result.phi0.text} + ${result.coefficients + .map((c, i) => `${fmt(c, digits)}*(${result.basis[i].text})`) + .join(' + ')}`; return ( <> @@ -322,7 +337,7 @@ function ResultView({
- +
{t('galerkin.final_meta', { precision: digits, n })} @@ -704,7 +719,7 @@ export function GalerkinMethod() {
{result && ( - <> + {board && ( }>

{t('galerkin.board_notice')}

@@ -714,7 +729,7 @@ export function GalerkinMethod() {

{t('galerkin.numeric_notice')}

- +
)}
diff --git a/lib/galerkin.ts b/lib/galerkin.ts index 5ff1734..3a2fee6 100644 --- a/lib/galerkin.ts +++ b/lib/galerkin.ts @@ -296,6 +296,55 @@ function sampleGrid(a: number, b: number, count: number): number[] { return Array.from({ length: count }, (_, index) => a + ((b - a) * index) / (count - 1)); } +// Expand uₙ into powers of x, e.g. 1 + 0.3183x + 0.0388x², rounded to `digits`. +// Works when uₙ is a polynomial (automatic and Legendre bases). The coefficients come +// from interpolation at n+3 points and are checked at other points; otherwise returns null +// (for example with sine bases). +export function expandedApproximation( + result: GalerkinResult, + digits: number, +): { tex: string; text: string } | null { + const u = (x: number) => + result.phi0.value(x) + result.coefficients.reduce((s, c, i) => s + c * result.basis[i].value(x), 0); + const a = result.samples[0].x; + const b = result.samples[result.samples.length - 1].x; + const nodes = result.basis.length + 3; + const points = Array.from({ length: nodes }, (_, k) => a + ((b - a) * k) / (nodes - 1)); + const matrix = points.map((x) => Array.from({ length: nodes }, (_, j) => x ** j)); + let coeffs: number[]; + try { + coeffs = solveLinearSystem(matrix, points.map(u)); + } catch { + return null; + } + for (let k = 0; k < 9; k++) { + const x = a + ((b - a) * (k + 0.37)) / 9; + const fitted = coeffs.reduce((s, c, j) => s + c * x ** j, 0); + if (Math.abs(fitted - u(x)) > 1e-7 * Math.max(1, Math.abs(u(x)))) return null; + } + + const rounded = coeffs.map((c) => Number(c.toFixed(digits))); + let tex = ''; + let text = ''; + rounded.forEach((c, j) => { + if (c === 0) return; + const mag = Math.abs(c); + const num = String(mag); + const powTex = j === 0 ? '' : j === 1 ? 'x' : `x^{${j}}`; + const powText = j === 0 ? '' : j === 1 ? 'x' : `x^${j}`; + const bodyTex = j > 0 && mag === 1 ? powTex : `${num}${powTex}`; + const bodyText = j > 0 && mag === 1 ? powText : `${num}${powText}`; + if (!tex) { + tex = c < 0 ? `-${bodyTex}` : bodyTex; + text = c < 0 ? `-${bodyText}` : bodyText; + } else { + tex += c < 0 ? ` - ${bodyTex}` : ` + ${bodyTex}`; + text += c < 0 ? ` - ${bodyText}` : ` + ${bodyText}`; + } + }); + return tex ? { tex, text } : { tex: '0', text: '0' }; +} + export function solveLinearSystem(matrix: number[][], rhs: number[]): number[] { const n = rhs.length; const m = matrix.map((row, i) => [...row, rhs[i]]); From e35d87841a9f5af36b67514a3ff2df751fda4ef2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 28 Nov 2026 14:00:45 +0500 Subject: [PATCH 25/34] =?UTF-8?q?refactor(collocation):=20move=20input=20p?= =?UTF-8?q?anel=20above=20results=20like=20Galerkin=20=F0=9F=8E=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Input is a centered full-width form above the results instead of a sticky left column, so the page scrolls naturally on desktop. Co-Authored-By: Claude Haiku 5.5 Claude-Session: https://claude.ai/code/session_014R1cEMD4uzti3MNab95hN5 --- components/collocation-method.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/components/collocation-method.tsx b/components/collocation-method.tsx index cc9e39c..596a221 100644 --- a/components/collocation-method.tsx +++ b/components/collocation-method.tsx @@ -263,8 +263,8 @@ export function CollocationMethod() { }, ]} /> -
-