Guide 01 Build, index, broadcast

Getting started

patternsbroadcastingSimpson's rulecomputed at build time

Building a PatternVector

A PatternVector is built from a length and a pattern. All the values of a pattern must have the same type, and the length must be at least the minimum length of the pattern.

using PatternVectors
x = PatternVector(7, EvenOddPattern(0.2, 2.3))
7-element PatternVector{Float64, EvenOddPattern{Float64}}:
 0.2
 2.3
 0.2
 2.3
 0.2
 2.3
 0.2
initial_value, value_even, value_odd, final_value = 0.2, 2.3, -0.2, 1.3
PatternVector(7, PaddedEvenOddPattern(initial_value, value_even, value_odd, final_value))
7-element PatternVector{Float64, PaddedEvenOddPattern{Float64}}:
  0.2
  2.3
 -0.2
  2.3
 -0.2
  2.3
  1.3

Indexing

A PatternVector is closed under indexing with ranges:

apv = PatternVector(70, PaddedEvenOddPattern(0.2, -2.0, 4.0, 2.3))
apv[1:7:50]
8-element PatternVector{Float64, PaddedEvenOddPattern{Float64}}:
  0.2
 -2.0
  4.0
 -2.0
  4.0
 -2.0
  4.0
 -2.0

Broadcasting

A scalar function broadcast over a PatternVector is evaluated once per distinct value and returns a PatternVector:

av = PatternVector(10, EvenOddPattern(0.2, -2.0))
@. sin(av)
10-element PatternVector{Float64, EvenOddPattern{Float64}}:
  0.19866933079506122
 -0.9092974268256817
  0.19866933079506122
 -0.9092974268256817
  0.19866933079506122
 -0.9092974268256817
  0.19866933079506122
 -0.9092974268256817
  0.19866933079506122
 -0.9092974268256817

Broadcasting between PatternVectors returns a PatternVector; broadcasting a PatternVector with any other AbstractArray returns an array of the other type, computed in one fused loop:

x = PatternVector(10, EvenOddPattern(0.2, 2.3))
y = randn(10)
z = PatternVector(10, PaddedEvenOddPattern(0.2, -2.0, 4.0, 2.3))
@. sin(x) * y + z
10-element Vector{Float64}:
  0.06643056651716961
 -1.5170487675804198
  3.727156251824887
 -2.2073448474649107
  3.94962897338849
 -1.583259980381134
  4.171361398786801
 -1.2761234155848156
  3.893367400528016
  2.6103553303571854

In a mixed broadcast, a sub-expression on PatternVectors only is still evaluated on the patterns: in exp.(x) .* y, exp is called twice, not ten times.

Simpson's rule

Quadrature weights without index loops, on CPU and GPU alike:

simpson(f_x, h) = h * sum(PatternVector(length(f_x), PaddedEvenOddPattern(1/3, 4/3, 2/3, 1/3)) .* f_x)
h = 0.01
simpson(exp.(0:h:1), h) - (exp(1) - 1)
9.545941814792513e-11

dot(w, f_x) from LinearAlgebra gives the same result with broadcasts and a reduction only, so that it runs on the device of f_x.

Testing

using Pkg
Pkg.test("PatternVectors")

The tests cover the patterns and the broadcasts, then Zygote, ReverseDiff, Mooncake and Enzyme.