Skip to main content

Vector

Type Alias Vector 

Source
pub type Vector<T, const N: usize> = Matrix<T, 1, N>;
Expand description

A row vector (1×N matrix).

Vectors support single-index access (v[i]), dot products, norms, and cross products (3-element vectors). Use ColumnVector for column vectors.

§Examples

use numeris::Vector;

let v = Vector::from_array([3.0_f64, 4.0]);
assert_eq!(v[0], 3.0);
assert_eq!(v.dot(&v), 25.0);
assert!((v.norm() - 5.0).abs() < 1e-12);

Aliased Type§

pub struct Vector<T, const N: usize> { /* private fields */ }

Implementations§

Source§

impl<T: Scalar, const N: usize> Vector<T, N>

Source

pub fn head<const P: usize>(&self) -> Vector<T, P>

Extract the first P elements.

use numeris::Vector;
let v = Vector::from_array([10, 20, 30, 40, 50]);
let h: Vector<i32, 3> = v.head();
assert_eq!(h[0], 10);
assert_eq!(h[2], 30);
Source

pub fn tail<const P: usize>(&self) -> Vector<T, P>

Extract the last P elements.

use numeris::Vector;
let v = Vector::from_array([10, 20, 30, 40, 50]);
let t: Vector<i32, 2> = v.tail();
assert_eq!(t[0], 40);
assert_eq!(t[1], 50);
Source

pub fn segment<const P: usize>(&self, i: usize) -> Vector<T, P>

Extract P elements starting at index i.

Source§

impl<T: Scalar, const N: usize> Vector<T, N>

Source

pub fn norm_squared(&self) -> T

Squared L2 norm (dot product with self). No sqrt, works with integers.

use numeris::Vector;
let v = Vector::from_array([3.0, 4.0]);
assert_eq!(v.norm_squared(), 25.0);

let vi = Vector::from_array([3, 4]);
assert_eq!(vi.norm_squared(), 25);
Source§

impl<T: LinalgScalar, const N: usize> Vector<T, N>

Source

pub fn norm(&self) -> T::Real

L2 (Euclidean) norm.

For complex vectors, this is sqrt(sum(|x_i|^2)).

use numeris::Vector;
let v = Vector::from_array([3.0_f64, 4.0]);
assert!((v.norm() - 5.0).abs() < 1e-12);
Source

pub fn norm_l1(&self) -> T::Real

L1 norm (sum of absolute values / moduli).

use numeris::Vector;
let v = Vector::from_array([1.0_f64, -2.0, 3.0]);
assert!((v.norm_l1() - 6.0).abs() < 1e-12);
Source

pub fn normalize(&self) -> Self

Return a unit vector in the same direction.

Panics if the norm is zero.

use numeris::Vector;
let v = Vector::from_array([3.0_f64, 4.0]);
let u = v.normalize();
assert!((u.norm() - 1.0).abs() < 1e-12);
assert!((u[0] - 0.6).abs() < 1e-12);
Source§

impl<T: FloatScalar, const N: usize> Vector<T, N>

Source

pub fn scaled_norm(&self) -> T

Scaled norm: norm() / sqrt(N).

Makes the error metric independent of state dimension, used by ODE solvers for step size control.

use numeris::Vector;
let v = Vector::from_array([3.0_f64, 4.0]);
let sn = v.scaled_norm();
assert!((sn - 5.0 / 2.0_f64.sqrt()).abs() < 1e-12);
Source§

impl<T: Scalar, const N: usize> Vector<T, N>

Source

pub fn from_array(data: [T; N]) -> Self

Create a vector from a 1D array.

use numeris::Vector;
let v = Vector::from_array([1.0, 2.0, 3.0]);
assert_eq!(v[0], 1.0);
Examples found in repository?
docs/examples/gen_plots.rs (line 149)
147fn make_ode_plot() -> String {
148    let tau = 4.0 * PI;
149    let y0 = Vector::from_array([1.0_f64, 0.0]);
150    let settings = AdaptiveSettings {
151        dense_output: true,
152        ..AdaptiveSettings::default()
153    };
154    let sol = RKTS54::integrate(
155        0.0,
156        tau,
157        &y0,
158        |_t, y| Vector::from_array([y[1], -y[0]]),
159        &settings,
160    )
161    .expect("ODE integration failed");
162
163    const N: usize = 300;
164    let mut t = vec![0.0; N];
165    let mut x = vec![0.0; N];
166    let mut v = vec![0.0; N];
167    for i in 0..N {
168        let ti = tau * i as f64 / (N - 1) as f64;
169        let yi = RKTS54::interpolate(ti, &sol).unwrap();
170        t[i] = ti;
171        x[i] = yi[0];
172        v[i] = yi[1];
173    }
174
175    let traces = format!(
176        "[{{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"position x(t)\",\
177          \"x\":{},\"y\":{},\"line\":{{\"width\":2.5}}}},\
178         {{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"velocity v(t)\",\
179          \"x\":{},\"y\":{},\"line\":{{\"width\":2.5,\"dash\":\"dash\"}}}}]",
180        fmt_arr(&t),
181        fmt_arr(&x),
182        fmt_arr(&t),
183        fmt_arr(&v),
184    );
185
186    let layout = decorate_layout(
187        "Harmonic Oscillator — RKTS54 Dense Output",
188        "t",
189        "Value",
190        "",
191    );
192
193    plotly_snippet("plot-ode", &traces, &layout, 420)
194}
195
196// ─── Interpolation plot ───────────────────────────────────────────────────
197
198fn make_interp_plot() -> String {
199    let tau = 2.0 * PI;
200    let kx: [f64; 6] = core::array::from_fn(|i| tau * i as f64 / 5.0);
201    let ky: [f64; 6] = core::array::from_fn(|i| kx[i].sin());
202    let kd: [f64; 6] = core::array::from_fn(|i| kx[i].cos());
203
204    let linear = LinearInterp::new(kx, ky).unwrap();
205    let hermite = HermiteInterp::new(kx, ky, kd).unwrap();
206    let lagrange = LagrangeInterp::new(kx, ky).unwrap();
207    let spline = CubicSpline::new(kx, ky).unwrap();
208
209    const N: usize = 200;
210    let mut xv = vec![0.0; N];
211    let mut y_true = vec![0.0; N];
212    let mut y_lin = vec![0.0; N];
213    let mut y_her = vec![0.0; N];
214    let mut y_lag = vec![0.0; N];
215    let mut y_spl = vec![0.0; N];
216    for i in 0..N {
217        let xi = tau * i as f64 / (N - 1) as f64;
218        xv[i] = xi;
219        y_true[i] = xi.sin();
220        y_lin[i] = linear.eval(xi);
221        y_her[i] = hermite.eval(xi);
222        y_lag[i] = lagrange.eval(xi);
223        y_spl[i] = spline.eval(xi);
224    }
225
226    let traces = format!(
227        "[{{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"sin(x) exact\",\
228          \"x\":{},\"y\":{},\"line\":{{\"width\":2.5,\"color\":\"rgba(120,120,120,0.6)\",\"dash\":\"dot\"}}}},\
229         {{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"Linear\",\
230          \"x\":{},\"y\":{},\"line\":{{\"width\":2}}}},\
231         {{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"Hermite\",\
232          \"x\":{},\"y\":{},\"line\":{{\"width\":2}}}},\
233         {{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"Lagrange\",\
234          \"x\":{},\"y\":{},\"line\":{{\"width\":2}}}},\
235         {{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"Cubic Spline\",\
236          \"x\":{},\"y\":{},\"line\":{{\"width\":2}}}},\
237         {{\"type\":\"scatter\",\"mode\":\"markers\",\"name\":\"knots\",\
238          \"x\":{},\"y\":{},\"marker\":{{\"size\":9,\"color\":\"black\",\"symbol\":\"diamond\"}}}}]",
239        fmt_arr(&xv), fmt_arr(&y_true),
240        fmt_arr(&xv), fmt_arr(&y_lin),
241        fmt_arr(&xv), fmt_arr(&y_her),
242        fmt_arr(&xv), fmt_arr(&y_lag),
243        fmt_arr(&xv), fmt_arr(&y_spl),
244        fmt_arr(&kx), fmt_arr(&ky),
245    );
246
247    let layout = decorate_layout(
248        "Interpolation Methods on sin(x) — 6 Knots",
249        "x",
250        "y",
251        "",
252    );
253
254    plotly_snippet("plot-interp", &traces, &layout, 440)
255}
256
257// ─── Control: Butterworth frequency response ──────────────────────────────
258
259fn biquad_cascade_freq_response<const N: usize>(
260    cascade: &BiquadCascade<f64, N>,
261    freq: f64,
262    fs: f64,
263) -> f64 {
264    let omega = 2.0 * PI * freq / fs;
265    let (sin_w, cos_w) = omega.sin_cos();
266    let cos_2w = 2.0 * cos_w * cos_w - 1.0;
267    let sin_2w = 2.0 * sin_w * cos_w;
268
269    let mut mag_sq = 1.0;
270    for section in &cascade.sections {
271        let (b, a) = section.coefficients();
272        let nr = b[0] + b[1] * cos_w + b[2] * cos_2w;
273        let ni = -b[1] * sin_w - b[2] * sin_2w;
274        let dr = a[0] + a[1] * cos_w + a[2] * cos_2w;
275        let di = -a[1] * sin_w - a[2] * sin_2w;
276        mag_sq *= (nr * nr + ni * ni) / (dr * dr + di * di);
277    }
278    mag_sq.sqrt()
279}
280
281fn make_control_plot() -> String {
282    let fs = 8000.0;
283    let fc = 1000.0;
284
285    let bw2: BiquadCascade<f64, 1> = butterworth_lowpass(2, fc, fs).unwrap();
286    let bw4: BiquadCascade<f64, 2> = butterworth_lowpass(4, fc, fs).unwrap();
287    let bw6: BiquadCascade<f64, 3> = butterworth_lowpass(6, fc, fs).unwrap();
288
289    const N: usize = 500;
290    let mut freqs = vec![0.0; N];
291    let mut db2 = vec![0.0; N];
292    let mut db4 = vec![0.0; N];
293    let mut db6 = vec![0.0; N];
294
295    let f_min: f64 = 10.0;
296    let f_max: f64 = 3900.0;
297    for i in 0..N {
298        let f = f_min * (f_max / f_min).powf(i as f64 / (N - 1) as f64);
299        freqs[i] = f;
300        db2[i] = 20.0 * biquad_cascade_freq_response(&bw2, f, fs).log10();
301        db4[i] = 20.0 * biquad_cascade_freq_response(&bw4, f, fs).log10();
302        db6[i] = 20.0 * biquad_cascade_freq_response(&bw6, f, fs).log10();
303    }
304
305    let traces = format!(
306        "[{{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"2nd order\",\
307          \"x\":{},\"y\":{},\"line\":{{\"width\":2.5}}}},\
308         {{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"4th order\",\
309          \"x\":{},\"y\":{},\"line\":{{\"width\":2.5}}}},\
310         {{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"6th order\",\
311          \"x\":{},\"y\":{},\"line\":{{\"width\":2.5}}}}]",
312        fmt_arr(&freqs), fmt_arr(&db2),
313        fmt_arr(&freqs), fmt_arr(&db4),
314        fmt_arr(&freqs), fmt_arr(&db6),
315    );
316
317    let layout = decorate_layout_ex(
318        "Butterworth Lowpass — f<sub>c</sub> = 1 kHz, f<sub>s</sub> = 8 kHz",
319        "Frequency (Hz)",
320        ",\"type\":\"log\"",
321        "Magnitude (dB)",
322        ",\"range\":[-80,5]",
323        &format!(
324            ",\"shapes\":[{{\"type\":\"line\",\"x0\":{f_min},\"x1\":{f_max},\
325             \"y0\":-3,\"y1\":-3,\"line\":{{\"dash\":\"dot\",\"color\":\"rgba(160,80,80,0.5)\",\"width\":1.5}}}}]"
326        ),
327    );
328
329    plotly_snippet("plot-control", &traces, &layout, 420)
330}
331
332// ─── Control: Lead/Lag compensator Bode ───────────────────────────────────
333
334fn biquad_freq_response(b: &[f64; 3], a: &[f64; 3], freq: f64, fs: f64) -> (f64, f64) {
335    let omega = 2.0 * PI * freq / fs;
336    let (sin_w, cos_w) = omega.sin_cos();
337    let cos_2w = 2.0 * cos_w * cos_w - 1.0;
338    let sin_2w = 2.0 * sin_w * cos_w;
339    let nr = b[0] + b[1] * cos_w + b[2] * cos_2w;
340    let ni = -b[1] * sin_w - b[2] * sin_2w;
341    let dr = a[0] + a[1] * cos_w + a[2] * cos_2w;
342    let di = -a[1] * sin_w - a[2] * sin_2w;
343    let mag = ((nr * nr + ni * ni) / (dr * dr + di * di)).sqrt();
344    let phase = (ni.atan2(nr) - di.atan2(dr)).to_degrees();
345    (mag, phase)
346}
347
348fn make_lead_lag_plot() -> String {
349    let fs = 1000.0;
350    let lead = lead_compensator(std::f64::consts::FRAC_PI_4, 50.0, 1.0, fs).unwrap();
351    let lag = lag_compensator(10.0, 5.0, fs).unwrap();
352
353    let (b_lead, a_lead) = lead.coefficients();
354    let (b_lag, a_lag) = lag.coefficients();
355
356    const N: usize = 400;
357    let f_min: f64 = 0.1;
358    let f_max: f64 = 490.0;
359    let mut freqs = vec![0.0; N];
360    let mut lead_db = vec![0.0; N];
361    let mut lead_ph = vec![0.0; N];
362    let mut lag_db = vec![0.0; N];
363    let mut lag_ph = vec![0.0; N];
364
365    for i in 0..N {
366        let f = f_min * (f_max / f_min).powf(i as f64 / (N - 1) as f64);
367        freqs[i] = f;
368        let (m, p) = biquad_freq_response(&b_lead, &a_lead, f, fs);
369        lead_db[i] = 20.0 * m.log10();
370        lead_ph[i] = p;
371        let (m, p) = biquad_freq_response(&b_lag, &a_lag, f, fs);
372        lag_db[i] = 20.0 * m.log10();
373        lag_ph[i] = p;
374    }
375
376    // Magnitude plot
377    let traces_mag = format!(
378        "[{{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"Lead (45° @ 50 Hz)\",\
379          \"x\":{},\"y\":{},\"line\":{{\"width\":2.5}}}},\
380         {{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"Lag (10× DC @ 5 Hz)\",\
381          \"x\":{},\"y\":{},\"line\":{{\"width\":2.5}}}}]",
382        fmt_arr(&freqs), fmt_arr(&lead_db),
383        fmt_arr(&freqs), fmt_arr(&lag_db),
384    );
385    let layout_mag = decorate_layout_ex(
386        "Lead / Lag Compensators — Magnitude",
387        "Frequency (Hz)",
388        ",\"type\":\"log\"",
389        "Magnitude (dB)",
390        "",
391        "",
392    );
393
394    // Phase plot
395    let traces_ph = format!(
396        "[{{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"Lead phase\",\
397          \"x\":{},\"y\":{},\"line\":{{\"width\":2.5}}}},\
398         {{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"Lag phase\",\
399          \"x\":{},\"y\":{},\"line\":{{\"width\":2.5}}}}]",
400        fmt_arr(&freqs), fmt_arr(&lead_ph),
401        fmt_arr(&freqs), fmt_arr(&lag_ph),
402    );
403    let layout_ph = decorate_layout_ex(
404        "Lead / Lag Compensators — Phase",
405        "Frequency (Hz)",
406        ",\"type\":\"log\"",
407        "Phase (°)",
408        "",
409        "",
410    );
411
412    let mut html = plotly_snippet("plot-lead-lag-mag", &traces_mag, &layout_mag, 380);
413    html.push_str(&plotly_snippet(
414        "plot-lead-lag-phase",
415        &traces_ph,
416        &layout_ph,
417        380,
418    ));
419    html
420}
421
422// ─── ODE: Van der Pol (stiff, RODAS4) ─────────────────────────────────────
423
424fn make_vanderpol_plot() -> String {
425    let mu = 20.0_f64;
426    let y0 = Vector::from_array([2.0, 0.0]);
427    let t_end = 120.0;
428
429    let settings = AdaptiveSettings {
430        abs_tol: 1e-8,
431        rel_tol: 1e-8,
432        max_steps: 100_000,
433        dense_output: true,
434        ..AdaptiveSettings::default()
435    };
436
437    let sol = RODAS4::integrate(
438        0.0,
439        t_end,
440        &y0,
441        |_t, y| {
442            Vector::from_array([y[1], mu * (1.0 - y[0] * y[0]) * y[1] - y[0]])
443        },
444        |_t, y| {
445            numeris::Matrix::new([
446                [0.0, 1.0],
447                [-2.0 * mu * y[0] * y[1] - 1.0, mu * (1.0 - y[0] * y[0])],
448            ])
449        },
450        &settings,
451    )
452    .expect("Van der Pol integration failed");
453
454    // Downsample accepted step points to a fixed grid for a manageable HTML size.
455    // The adaptive solver clusters points at sharp transitions; we keep enough
456    // resolution by picking the nearest stored point for each output sample.
457    let ds = sol.dense.as_ref().expect("no dense output");
458    let n_out = 2000usize;
459    let mut tv = Vec::with_capacity(n_out);
460    let mut xv = Vec::with_capacity(n_out);
461    let mut idx = 0usize;
462    for i in 0..n_out {
463        let t_want = t_end * i as f64 / (n_out - 1) as f64;
464        // advance index to nearest stored point
465        while idx + 1 < ds.t.len() && ds.t[idx + 1] <= t_want {
466            idx += 1;
467        }
468        tv.push(t_want);
469        xv.push(ds.y[idx][0]);
470    }
471
472    let traces = format!(
473        "[{{\"type\":\"scatter\",\"mode\":\"lines\",\"name\":\"y₁(t)\",\
474          \"x\":{},\"y\":{},\"line\":{{\"width\":2}}}}]",
475        fmt_arr(&tv),
476        fmt_arr(&xv),
477    );
478
479    let layout = decorate_layout(
480        "Van der Pol Oscillator (μ = 20) — RODAS4",
481        "t",
482        "y₁",
483        "",
484    );
485
486    plotly_snippet("plot-vanderpol", &traces, &layout, 420)
487}
Source

pub fn fill(value: T) -> Self

Create a vector filled with a single value.

Source

pub const fn len(&self) -> usize

Number of elements.

Source

pub fn dot(&self, rhs: &Self) -> T

Dot product of two vectors.

use numeris::Vector;
let a = Vector::from_array([1.0, 2.0, 3.0]);
let b = Vector::from_array([4.0, 5.0, 6.0]);
assert_eq!(a.dot(&b), 32.0); // 1*4 + 2*5 + 3*6
Source§

impl<T: Scalar, const N: usize> Vector<T, N>

Source

pub fn outer<const P: usize>(&self, rhs: &Vector<T, P>) -> Matrix<T, N, P>

Outer product: v.outer(w) → N×P matrix where result[i][j] = v[i] * w[j].

use numeris::Vector;
let a = Vector::from_array([1.0, 2.0]);
let b = Vector::from_array([3.0, 4.0, 5.0]);
let m = a.outer(&b);
assert_eq!(m[(0, 0)], 3.0);  // 1*3
assert_eq!(m[(1, 2)], 10.0); // 2*5

Trait Implementations§

Source§

impl<T, const N: usize> Index<usize> for Vector<T, N>

Source§

type Output = T

The returned type after indexing.
Source§

fn index(&self, i: usize) -> &T

Performs the indexing (container[index]) operation. Read more
Source§

impl<T, const N: usize> IndexMut<usize> for Vector<T, N>

Source§

fn index_mut(&mut self, i: usize) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more