Examples

22 examples with their real output

Each example is a Dart program in the site repository. The build runs all of them against scidart 0.1.1; if one fails, the site is not published.

Arrays guide

Arrays and element-wise mathCreate an Array, combine arrays element by element and reduce them.
import 'package:scidart/numdart.dart';

void main() {
  var a = Array([1, 2, 3, 4]);
  var b = Array([10, 20, 30, 40]);

  print((a + b).toList()); // element-wise sum
  print((a * b).toList()); // element-wise product
  print(arrayMultiplyToScalar(a, 0.5).toList());
  print(arrayCumSum(a).toList());

  print('sum: ${arraySum(a)}, max: ${arrayMax(b)}, argmax: ${arrayArgMax(b)}');
}
Output
[11.0, 22.0, 33.0, 44.0]
[10.0, 40.0, 90.0, 160.0]
[0.5, 1.0, 1.5, 2.0]
[1.0, 3.0, 6.0, 10.0]
sum: 10.0, max: 40.0, argmax: 3
Ranges, linspace and filled arraysBuild evenly spaced samples like numpy.arange (createArrayRange) and numpy.linspace.
import 'package:scidart/numdart.dart';

void main() {
  print(createArrayRange(start: 0, stop: 10, step: 2).toList());
  print(linspace(0, 1, num: 5).toList());
  print(linspace(0, 1, num: 4, endpoint: false).toList());
  print(ones(3).toList());
  print(zeros(3).toList());
  print(Array2d.fixed(2, 3, initialValue: 7).map((r) => r.toList()).toList());
}
Output
[0.0, 2.0, 4.0, 6.0, 8.0]
[0.0, 0.25, 0.5, 0.75, 1.0]
[0.0, 0.25, 0.5, 0.75]
[1.0, 1.0, 1.0]
[0.0, 0.0, 0.0]
[[7.0, 7.0, 7.0], [7.0, 7.0, 7.0]]

Linear algebra guide

Solve a linear systemSolve A x = b, then check the determinant, inverse and rank of A.
import 'package:scidart/numdart.dart';

void main() {
  // 3x + 2y - z = 1, 2x - 2y + 4z = -2, -x + y/2 - z = 0
  var a = Array2d([
    Array([3, 2, -1]),
    Array([2, -2, 4]),
    Array([-1, 0.5, -1]),
  ]);
  var b = Array2d([
    Array([1]),
    Array([-2]),
    Array([0]),
  ]);

  var x = matrixSolve(a, b);
  print('x = ${matrixColumnToArray(x, 0).toList()}');
  print('det(A) = ${matrixDeterminant(a)}');
  print('rank(A) = ${matrixRank(a)}');
  print('A * x = ${matrixColumnToArray(matrixDot(a, x), 0).toList()}');
}
Output
x = [1.0, -1.9999999999999996, -1.9999999999999993]
det(A) = -3.0000000000000004
rank(A) = 3
A * x = [1.0000000000000002, -1.9999999999999982, -4.440892098500626e-16]
QR, LU and SVD decompositionsFactor a matrix and rebuild it from the factors.
import 'package:scidart/numdart.dart';

void main() {
  var a = Array2d([
    Array([4, 3]),
    Array([6, 3]),
  ]);

  var qr = QR(a);
  print('Q = ${qr.Q()}');
  print('R = ${qr.R()}');
  print('Q R = ${matrixDot(qr.Q(), qr.R())}');

  var lu = LU(a);
  print('det from LU = ${lu.det()}');

  var svd = SVD(a);
  print('singular values = ${svd.singularValues().toList()}');
  print('condition number = ${svd.cond()}');
}
Output
Q = Array2d([
  Array([-0.5547001962252291, -0.8320502943378438]),
  Array([-0.8320502943378437, 0.554700196225229])
])
R = Array2d([
  Array([-7.211102550927978, -4.160251471689217]),
  Array([0.0, -0.8320502943378432])
])
Q R = Array2d([
  Array([4.0, 2.999999999999999]),
  Array([6.0, 2.9999999999999996])
])
det from LU = -6.0
singular values = [8.335579122000661, 0.7198060161367538]
condition number = 11.580313216522228

Polynomial fitting guide

Fit a polynomialLeast squares fit of a degree 2 polynomial, like numpy.polyfit.
import 'package:scidart/numdart.dart';

void main() {
  var x = Array([0, 1, 2, 3, 4, 5]);
  var y = Array([1.1, 2.9, 9.2, 19.1, 32.8, 51.2]);

  var fit = PolyFit(x, y, 2);
  print(fit);
  print('coefficients (lowest power first): ${fit.coefficients().toList()}');
  print('R2 = ${fit.R2()}');
  print('prediction at x = 6: ${fit.predict(6)}');
}
Output
2.010714285714285 x^2 +  -0.050714285714280036 x +  1.0785714285714196   (R^2 = 0.9999313529244543)
coefficients (lowest power first): [2.010714285714285, -0.050714285714280036, 1.0785714285714196]
R2 = 0.9999313529244543
prediction at x = 6: 73.16
Polynomial regression with several featuresFit y from two inputs with interaction terms, like sklearn PolynomialFeatures plus LinearRegression.
import 'package:scidart/numdart.dart';

void main() {
  // y = 1 + 1.5 x0 + x1 + 0.5 x0^2 + 2 x0 x1
  var x = Array2d([
    Array([0, 0]),
    Array([1, 0]),
    Array([0, 1]),
    Array([1, 1]),
    Array([2, 1]),
    Array([1, 2]),
    Array([2, 2]),
  ]);
  var y = Array2d([
    for (var r in x)
      Array([1 + 1.5 * r[0] + r[1] + 0.5 * r[0] * r[0] + 2 * r[0] * r[1]])
  ]);

  var fit = PolyFitMultivariate(x, y, 2);
  for (var t = 0; t < fit.powers.length; t++) {
    var c = fit.coefficients[t][0];
    print('powers ${fit.powers[t]}: ${c.toStringAsFixed(6)}');
  }
  print('rank: ${fit.rank}, R2: ${fit.R2().toList()}');
  print('predict [3, 1]: ${fit.predict(Array([3, 1])).toList()}');
}
Output
powers [0, 0]: 1.000000
powers [1, 0]: 1.500000
powers [0, 1]: 1.000000
powers [2, 0]: 0.500000
powers [1, 1]: 2.000000
powers [0, 2]: -0.000000
rank: 6, R2: [1.0]
predict [3, 1]: [17.0]

Statistics guide

Descriptive statisticsMean, median, mode, variance and standard deviation of a sample.
import 'package:scidart/numdart.dart';

void main() {
  var a = Array([2, 4, 4, 4, 5, 5, 7, 9]);

  print('mean: ${mean(a)}');
  print('median: ${median(a)}');
  print('mode: ${mode(a)}');
  print('multimode: ${multimode(Array([1, 1, 2, 2, 3])).toList()}');
  print('variance: ${variance(a)}');
  print('standard deviation: ${standardDeviation(a)}');
}
Output
mean: 5.0
median: 4.5
mode: 4.0
multimode: [1.0, 2.0]
variance: 4.571428571428571
standard deviation: 2.138089935299395

Calculus guide

Integrate and differentiateIntegrate sampled data and functions with the trapezoidal and Simpson rules, and differentiate numerically.
import 'dart:math' as math;

import 'package:scidart/numdart.dart';

void main() {
  // integral of sin(x) from 0 to pi is exactly 2
  var x = linspace(0, math.pi, num: 101);
  var y = arraySin(x);
  print('trapezoidal: ${trapzArray(y, x: x)}');
  print('simpson: ${simpsArray(y, x: x)}');
  print('simpson on a function: ${simpsFunction(0, math.pi, 100, math.sin)}');

  // derivative of x^3 at x = 2 is 12
  print('d/dx x^3 at 2: ${differentiateFunction(2, (double x) => x * x * x)}');
  print('cumulative integral: ${cumIntegration(Array([1, 2, 3, 4])).toList()}');
}
Output
trapezoidal: 1.9998355038874442
simpson: 2.0000000108245044
simpson on a function: 2.000000000676472
d/dx x^3 at 2: 11.999999927070348
cumulative integral: [1.5, 4.0, 7.5]

Interpolation guide

Find the true peak between samplesParabolic interpolation around the largest sample gives the peak position between grid points.
import 'package:scidart/numdart.dart';

void main() {
  // samples of -(x - 2.3)^2 at x = 0..5: the real peak is at 2.3
  var y = Array([for (var x = 0; x < 6; x++) -(x - 2.3) * (x - 2.3)]);
  var i = arrayArgMax(y);
  var peak = parabolic(y, i);
  print('largest sample at index $i');
  print('interpolated peak at ${peak[0]}, value ${peak[1]}');
}
Output
largest sample at index 2
interpolated peak at 2.3, value 0.0

Complex numbers guide

Complex numbersArithmetic, magnitude, conjugate and the complex exponential.
import 'dart:math' as math;

import 'package:scidart/numdart.dart';

String show(Complex z) =>
    '${z.real} ${z.imaginary < 0 ? '-' : '+'} ${z.imaginary.abs()}i';

void main() {
  var a = Complex(real: 3, imaginary: 4);
  var b = Complex.ri(1, -2);

  print('a + b = ${show(a + b)}');
  print('a * b = ${show(a * b)}');
  print('a / b = ${show(a / b)}');
  print('|a| = ${complexAbs(a)}');
  print('conj(a) = ${show(complexConjugate(a))}');
  // Euler: e^(i pi) = -1
  print('e^(i pi) = ${show(complexExp(Complex(imaginary: math.pi)))}');
}
Output
a + b = 4.0 + 2.0i
a * b = 11.0 - 2.0i
a / b = -1.0 + 2.0i
|a| = 5.0
conj(a) = 3.0 - 4.0i
e^(i pi) = -1.0 + 1.2246467991473532e-16i

Random arrays guide

Random arraysUniform random arrays of real and complex values.
import 'package:scidart/numdart.dart';

void main() {
  var a = randomArray(5);
  print(
      'length ${a.length}, all in [0, 1): ${a.every((v) => v >= 0 && v < 1)}');
  var m = randomArray2d(2, 3);
  print('matrix ${m.length} x ${m[0].length}');
  print('complex values: ${randomArrayComplex(2).length}');
}
Output
length 5, all in [0, 1): true
matrix 2 x 3
complex values: 2

Constants guide

Scientific constantsPhysical and mathematical constants and unit factors, like scipy.constants.
import 'package:scidart/numdart.dart';

void main() {
  print('speed of light: $speedOfLight m/s');
  print('Planck constant: $Planck J s');
  print('golden ratio: $golden');
  print('1 degree in radians: $degree');
}
Output
speed of light: 299792458 m/s
Planck constant: 6.62607015e-34 J s
golden ratio: 1.618033988749895
1 degree in radians: 0.017453292519943295

Fourier transform guide

Spectrum of a signal with the FFTSample two sine waves, take the real FFT and read the strongest frequencies.
import 'dart:math' as math;

import 'package:scidart/numdart.dart';
import 'package:scidart/scidart.dart';

void main() {
  var fs = 64.0; // sampling rate in Hz
  var t = linspace(0, 1, num: 64, endpoint: false);
  var signal = arraySin(arrayMultiplyToScalar(t, 2 * math.pi * 5)) +
      arrayMultiplyToScalar(
          arraySin(arrayMultiplyToScalar(t, 2 * math.pi * 12)), 0.5);

  var spectrum = arrayComplexAbs(rfft(signal));
  var freqs = fftFreq(signal.length, d: 1 / fs, realFrequenciesOnly: true);

  for (var i = 0; i < spectrum.length; i++) {
    if (spectrum[i] > 1) {
      print('${freqs[i]} Hz: magnitude ${spectrum[i].toStringAsFixed(3)}');
    }
  }
}
Output
5.0 Hz: magnitude 32.000
12.0 Hz: magnitude 16.000
Estimate a frequency preciselyWindow the signal, find the FFT peak and refine it with parabolic interpolation.
import 'dart:math' as math;

import 'package:scidart/numdart.dart';
import 'package:scidart/scidart.dart';

void main() {
  var fs = 128.0;
  var f0 = 3.7; // between two FFT bins
  var n = linspace(0, 4, num: (4 * fs).toInt(), endpoint: false);
  var signal = arraySin(arrayMultiplyToScalar(n, 2 * math.pi * f0));

  var windowed = signal * blackmanharris(signal.length);
  var spectrum = arrayComplexAbs(rfft(windowed));
  var i = arrayArgMax(spectrum);
  var refined = parabolic(arrayLog(spectrum), i)[0];

  print('naive estimate: ${fs * i / windowed.length} Hz');
  print(
      'refined estimate: ${(fs * refined / windowed.length).toStringAsFixed(4)} Hz');
}
Output
naive estimate: 3.75 Hz
refined estimate: 3.6993 Hz

Signal processing guide

Low-pass FIR filterDesign a filter with firwin and apply it with lfilter to remove a high frequency.
import 'dart:math' as math;

import 'package:scidart/numdart.dart';
import 'package:scidart/scidart.dart';

void main() {
  var fs = 100.0;
  var t = linspace(0, 1, num: 100, endpoint: false);
  var slow = arraySin(arrayMultiplyToScalar(t, 2 * math.pi * 2));
  var fast = arraySin(arrayMultiplyToScalar(t, 2 * math.pi * 30));
  var x = slow + fast;

  // 31 taps, cutoff at 10 Hz
  Array b = firwin(31, Array([10]), fs: fs);
  var y = lfilter(b, Array([1]), x);

  // after the filter delay (15 samples), y follows the slow wave
  var error = 0.0;
  for (var i = 30; i < 100; i++) {
    error = math.max(error, (y[i] - slow[i - 15]).abs());
  }
  print('taps: ${b.length}, sum of taps: ${arraySum(b).toStringAsFixed(6)}');
  print('max difference to the 2 Hz wave: ${error.toStringAsFixed(4)}');
}
Output
taps: 31, sum of taps: 1.000000
max difference to the 2 Hz wave: 0.0017
Find peaksLocal maxima of a signal, optionally above a threshold.
import 'package:scidart/numdart.dart';
import 'package:scidart/scidart.dart';

void main() {
  var a = Array([0, 2, 1, 3, 0, 1, 5, 2, 0]);
  var all = findPeaks(a);
  print(
      'indexes: ${(all[0] as Array).toList()}, values: ${(all[1] as Array).toList()}');

  var tall = findPeaks(a, threshold: 3);
  print(
      'above 3: indexes ${(tall[0] as Array).toList()}, values ${(tall[1] as Array).toList()}');
}
Output
indexes: [1.0, 3.0, 6.0], values: [2.0, 3.0, 5.0]
above 3: indexes [3.0, 6.0], values [3.0, 5.0]
Window functionsHann, Hamming, Blackman and Kaiser windows, like scipy.signal.windows.
import 'package:scidart/numdart.dart';
import 'package:scidart/scidart.dart';

void main() {
  String show(Array w) => w.map((v) => v.toStringAsFixed(4)).join(', ');
  print('hann(5):     ${show(hann(5))}');
  print('hamming(5):  ${show(hamming(5))}');
  print('blackman(5): ${show(blackman(5))}');
  print('kaiser(5, 8): ${show(kaiser(5, 8))}');
}
Output
hann(5):     0.0000, 0.5000, 1.0000, 0.5000, 0.0000
hamming(5):  0.0800, 0.5400, 1.0000, 0.5400, 0.0800
blackman(5): -0.0000, 0.3400, 1.0000, 0.3400, -0.0000
kaiser(5, 8): 0.0023, 0.3690, 1.0000, 0.3690, 0.0023
Convolution and moving averageConvolve a signal with a kernel; a box kernel gives a moving average.
import 'package:scidart/numdart.dart';
import 'package:scidart/scidart.dart';

void main() {
  var x = Array([1, 2, 3, 4, 5]);
  print(convolution(x, Array([1, 1, 1])).toList());
  print(arrayDivisionToScalar(convolution(x, Array([1, 1, 1])), 3).toList());
  print(correlate(x, Array([0, 1, 0.5])).toList());
}
Output
[1.0, 3.0, 6.0, 9.0, 12.0, 9.0, 5.0]
[0.3333333333333333, 1.0, 2.0, 3.0, 4.0, 3.0, 1.6666666666666667]
[0.5, 2.0, 3.5, 5.0, 6.5, 5.0, 0.0]

Special functions guide

Special functionsError function, complementary error function and the modified Bessel function I0.
import 'package:scidart/scidart.dart';

void main() {
  print('erf(0.5) = ${erf(0.5)}');
  print('erfc(3) = ${erfc(3)}');
  // erfc keeps precision deep in the tail
  print('erfc(26.6) = ${erfc(26.6)}');
  print('I0(1) = ${besselI0(1)}');
}
Output
erf(0.5) = 0.5204998778130465
erfc(3) = 0.000022090496998585438
erfc(26.6) = 1.088512588544237e-309
I0(1) = 1.2660658480342601

Normal distribution guide

Normal distributionDensity, probabilities, quantiles and samples of a normal distribution, like scipy.stats.norm.
import 'dart:math' as math;

import 'package:scidart/numdart.dart';
import 'package:scidart/scidart.dart';

void main() {
  // adult height in cm
  var height = NormalDistribution(mean: 170, std: 8);

  print('density at 170: ${height.pdf(170)}');
  print('P(height < 180): ${height.cdf(180)}');
  print('P(height > 190): ${height.sf(190)}');
  print('95th percentile: ${height.ppf(0.95)}');
  print('central 95%: ${height.interval(0.95).toList()}');

  var s = height.sample(10000, random: math.Random(42));
  print(
      'sample mean: ${mean(s).toStringAsFixed(2)}, std: ${standardDeviation(s).toStringAsFixed(2)}');
}
Output
density at 170: 0.04986778505017909
P(height < 180): 0.8943502263331448
P(height > 190): 0.0062096653257761375
95th percentile: 183.1588290156118
central 95%: [154.32028812367957, 185.67971187632043]
sample mean: 169.93, std: 7.92

Root finding guide

Root of a functionSolve f(x) = 0 with Brent's method, bisection, Newton or the secant method.
import 'dart:math' as math;

import 'package:scidart/scidart.dart';

void main() {
  double f(double x) => math.cos(x) - x;

  var brent = rootScalar(f, bracket: [0, 1]);
  print('brentq: ${brent.root} after ${brent.iterations} iterations');

  var newton = rootScalar(f,
      method: RootScalarMethod.newton, x0: 1, fprime: (x) => -math.sin(x) - 1);
  print('newton: ${newton.root} after ${newton.iterations} iterations');

  var bisect = rootScalar(f, method: RootScalarMethod.bisect, bracket: [0, 1]);
  print('bisect: ${bisect.root} after ${bisect.iterations} iterations');
}
Output
brentq: 0.7390851332151559 after 7 iterations
newton: 0.7390851332151607 after 5 iterations
bisect: 0.7390851332147577 after 39 iterations
Solve a system of nonlinear equationsFind x where f(x) = 0 for f from R^n to R^n, like scipy.optimize.root.
import 'package:scidart/numdart.dart';
import 'package:scidart/scidart.dart';

void main() {
  // x^2 + y^2 = 4 and x y = 1
  Array f(Array v) => Array([
        v[0] * v[0] + v[1] * v[1] - 4,
        v[0] * v[1] - 1,
      ]);

  var result = root(f, Array([2, 0.5]));
  print('success: ${result.success}, ${result.message}');
  print('x = ${result.x.toList()}');
  print('f(x) = ${result.fun.toList()}');

  var broyden = root(f, Array([2, 0.5]), method: RootMethod.broyden1);
  print('broyden1: ${broyden.x.toList()} in ${broyden.iterations} iterations');
}
Output
success: true, converged
x = [1.931851652612349, 0.5176380901529665]
f(x) = [7.827427594975234e-11, -8.28915824868659e-11]
broyden1: [1.9318516525788239, 0.5176380901930494] in 5 iterations