s LearnSqueak.com

SMALLTALK LAB

Discrete convolution: combine every overlapping pair

Build full linear convolution in Squeak Smalltalk, trace its reversed kernel indexes, distinguish correlation, and reuse the same exact calculation for smoothing and polynomial multiplication.

8 tested checkpointsNative Squeak screenshotsComputed visual replay

Before you begin

Open a native Squeak 6.1 Workspace and select one complete checkpoint for Print it. Each checkpoint is independent. Inputs are finite, one-based numeric Arrays, with position 1 representing offset zero. Only built-in Arrays, blocks and arithmetic are needed. Examples use exact Integer and Fraction arithmetic; there is no signal-processing package or FFT dependency.

These are native Squeak 6.1 examples. Each checkpoint is independent: open the download as text, copy one complete expression into Workspace and choose Print it. Do not file in the checkpoint collection as a class definition.

01 - Send every pair to its output slot

Treat the first Array position as time zero. A sample at position i and a kernel entry at position j contribute to position i+j-1. For #(1 2 3) and #(2 3), output position 3 receives 2*3 and 3*2. These products add, rather than overwrite each other.

Independent Workspace expression - select all, then Print it
| signal kernel contributions |
signal := #(1 2 3). kernel := #(2 3).
contributions := OrderedCollection new.
1 to: signal size do: [:i |
 1 to: kernel size do: [:j |
  i + j - 1 = 3 ifTrue: [
   contributions add: ((signal at: i) * (kernel at: j))]]].
{contributions asArray.
 contributions inject: 0 into: [:sum :each | sum + each]}

Expected: #(#(6 6) 12)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 1: Send every pair to its output slot
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change the requested output position from 3 to 2. Its products become #(3 4) and its total is 7. Position 1 has only the product 1*2.

Download this checkpoint

02 - Build full linear convolution

The full result keeps every overlap, including the two ends. For nonempty lengths n and m its size is n+m-1. Starting with zeros lets each input pair add its contribution. This block returns a fresh Array and defines an empty result when either input is empty.

Independent Workspace expression - select all, then Print it
| convolve |
convolve := [:a :b | | out |
 (a isEmpty or: [b isEmpty])
  ifTrue: [#()]
  ifFalse: [
   out := Array new: a size + b size - 1 withAll: 0.
   1 to: a size do: [:i |
    1 to: b size do: [:j | | k |
     k := i + j - 1.
     out at: k put: (out at: k) + ((a at: i) * (b at: j))]].
   out]].
convolve value: #(1 2 3) value: #(2 3)

Expected: #(2 7 12 9)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 2: Build full linear convolution
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: By hand, the four totals are 1*2, 1*3+2*2, 2*3+3*2, and 3*3. Try a one-element kernel #(5): the result is #(5 10 15).

Download this checkpoint

03 - Read one output by reversing the kernel index

There is a second way to compute the same answer: visit each output k, scan the signal index i, and derive j=k-i+1. As i increases, j decreases. That reversal is why convolution is often described as flipping and sliding a kernel. Out-of-range entries act as zero; no array access is made for them.

Independent Workspace expression - select all, then Print it
| signal kernel output |
signal := #(1 2 3). kernel := #(2 3).
output := (1 to: signal size + kernel size - 1) collect: [:k |
 | total |
 total := 0.
 1 to: signal size do: [:i | | j |
  j := k - i + 1.
  (j between: 1 and: kernel size) ifTrue: [
   total := total + ((signal at: i) * (kernel at: j))]].
 total].
output asArray

Expected: #(2 7 12 9)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 3: Read one output by reversing the kernel index
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: For k=2, the signal entries at i=1 and i=2 pair with kernel entries j=2 and j=1. For k=4, only i=3, j=2 survives.

Download this checkpoint

04 - Separate convolution from correlation

For real-valued data, correlating against a pattern without reversing its left-to-right weights is convolution with that pattern reversed. Here full correlation is reported in lag order -1, 0, 1, 2, with c(lag)=sum over j of signal[j+lag]*kernel[j] and zero outside the signal. It is not the same result as convolution.

Independent Workspace expression - select all, then Print it
| convolve signal kernel |
convolve := [:a :b | | out |
 (a isEmpty or: [b isEmpty])
  ifTrue: [#()]
  ifFalse: [
   out := Array new: a size + b size - 1 withAll: 0.
   1 to: a size do: [:i |
    1 to: b size do: [:j | | k |
     k := i + j - 1.
     out at: k put: (out at: k) + ((a at: i) * (b at: j))]].
   out]].
signal := #(1 2 3). kernel := #(2 3).
{convolve value: signal value: kernel.
 convolve value: signal value: kernel reversed}

Expected: #(#(2 7 12 9) #(3 8 13 6))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 4: Separate convolution from correlation
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: At correlation lag 0 the weights stay in order: 1*2+2*3=8. A symmetric kernel such as #(1 2 1) hides the reversal, so use an asymmetric kernel when testing. Complex correlation additionally needs conjugation, which this lesson does not implement.

Download this checkpoint

05 - Keep fractions and choose a boundary policy

A three-sample averaging kernel has three exact weights of 1/3. Full convolution uses zero outside the finite signal, so edge totals are smaller. The valid section keeps only complete overlap: for n>=m, take positions m through n. That produces n-m+1 values without artificial zero neighbors.

Independent Workspace expression - select all, then Print it
| convolve full |
convolve := [:a :b | | out |
 (a isEmpty or: [b isEmpty])
  ifTrue: [#()]
  ifFalse: [
   out := Array new: a size + b size - 1 withAll: 0.
   1 to: a size do: [:i |
    1 to: b size do: [:j | | k |
     k := i + j - 1.
     out at: k put: (out at: k) + ((a at: i) * (b at: j))]].
   out]].
full := convolve value: #(3 6 9 12) value: {1/3. 1/3. 1/3}.
{full. full copyFrom: 3 to: 4}

Expected: #(#(1 3 6 9 7 4) #(6 9))

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 5: Keep fractions and choose a boundary policy
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Try #(1 2) with the same averaging kernel and inspect its full result: {1/3. 1. 1. 2/3}. A valid crop needs a separate n>=m check; do not blindly reuse the indexes 3 through 4.

Download this checkpoint

06 - Test identity, delay, and empty inputs

The impulse #(1) leaves the sequence unchanged. A leading zero in #(0 1) delays it by one position. Empty input is a separate API decision: this implementation returns #(), rather than allocating n+m-1 slots. Signed values and exact fractions need no special algorithm branch.

Independent Workspace expression - select all, then Print it
| convolve |
convolve := [:a :b | | out |
 (a isEmpty or: [b isEmpty])
  ifTrue: [#()]
  ifFalse: [
   out := Array new: a size + b size - 1 withAll: 0.
   1 to: a size do: [:i |
    1 to: b size do: [:j | | k |
     k := i + j - 1.
     out at: k put: (out at: k) + ((a at: i) * (b at: j))]].
   out]].
{convolve value: #(4 -2 7) value: #(1).
 convolve value: #(4 -2 7) value: #(0 1).
 convolve value: #() value: #(2 3).
 convolve value: #(2 3) value: #()}

Expected: #(#(4 -2 7) #(0 4 -2 7) #() #())

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 6: Test identity, delay, and empty inputs
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Add a fifth test with both inputs empty; it also returns #(). A zero-valued kernel #(0) instead returns an equally long Array of zeros, not an empty Array.

Download this checkpoint

07 - Multiply polynomials by combining degrees

Convolution also multiplies polynomial coefficients. Here coefficients run from constant term upward: #(2 1) means 2+x and #(3 4 1) means 3+4x+x squared. Degrees add just as time offsets do. This ascending order is explicit; other polynomial APIs may use the opposite order.

Independent Workspace expression - select all, then Print it
| convolve coefficients evaluate |
convolve := [:a :b | | out |
 (a isEmpty or: [b isEmpty])
  ifTrue: [#()]
  ifFalse: [
   out := Array new: a size + b size - 1 withAll: 0.
   1 to: a size do: [:i |
    1 to: b size do: [:j | | k |
     k := i + j - 1.
     out at: k put: (out at: k) + ((a at: i) * (b at: j))]].
   out]].
coefficients := convolve value: #(2 1) value: #(3 4 1).
evaluate := [:terms :x |
 terms reversed inject: 0 into: [:sum :coefficient |
  (sum * x) + coefficient]].
{coefficients. evaluate value: coefficients value: 2.
 (evaluate value: #(2 1) value: 2) *
  (evaluate value: #(3 4 1) value: 2)}

Expected: #(#(6 11 6 1) 60 60)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 7: Multiply polynomials by combining degrees
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: The coefficient 11 comes from 2*4+1*3. Repeat the evaluation at x=0 and x=-1. Equality at a few points is a useful check, but not by itself a proof for arbitrary polynomials.

Download this checkpoint

08 - Check an independent oracle and an invariant

The scatter implementation and gather oracle traverse contributions in different orders. Compare them on signed inputs, then test commutativity and the total-sum law: sum(convolution)=sum(a)*sum(b). The oracle here assumes nonempty inputs, which the preceding checkpoint tests separately.

Independent Workspace expression - select all, then Print it
| convolve signal kernel actual oracle sum |
convolve := [:a :b | | out |
 (a isEmpty or: [b isEmpty])
  ifTrue: [#()]
  ifFalse: [
   out := Array new: a size + b size - 1 withAll: 0.
   1 to: a size do: [:i |
    1 to: b size do: [:j | | k |
     k := i + j - 1.
     out at: k put: (out at: k) + ((a at: i) * (b at: j))]].
   out]].
signal := #(2 -1 0 3). kernel := #(4 2 -2).
actual := convolve value: signal value: kernel.
oracle := (1 to: signal size + kernel size - 1) collect: [:k |
 (1 to: signal size) inject: 0 into: [:total :i | | j |
  j := k - i + 1.
  total + ((j between: 1 and: kernel size)
   ifTrue: [(signal at: i) * (kernel at: j)] ifFalse: [0])]].
sum := [:items | items inject: 0 into: [:total :each | total + each]].
{actual. actual = oracle asArray.
 actual = (convolve value: kernel value: signal).
 (sum value: actual) = ((sum value: signal) * (sum value: kernel))}

Expected: #(#(8 0 -6 14 6 -6) true true true)

NATIVE SQUEAK CAPTURE
Native Squeak checkpoint 8: Check an independent oracle and an invariant
Actual native Squeak Workspace after Print it. The selected answer was evaluated from this code.

Try it: Change either Array and re-run all three checks. With Float data, compare within a justified tolerance: reversing the addition order can change the rounded answer even when the mathematics agrees.

Download this checkpoint

Watch the computed states

NATIVE SQUEAK CAPTURE
Discrete convolution: combine every overlapping pair native visual trace
Replay of actual Morphic window captures at successive computed stages; not mouse footage.

Download the visual experiment. Select the entire expression and Do it. Change stage := 0. to another supported stage, close the previous window, and run again. The GIF replays those native states. This example needs native Squeak; no new browser playground compatibility is claimed.

Reason about correctness and limits

This is full linear convolution with zero extension, not circular convolution. Never wrap indexes with remainder unless circular behavior is deliberately required. A same-length output is a chosen crop with an alignment convention, not a different convolution formula.

Both input Arrays must contain values that support numeric multiplication and addition. The compact block does not validate element types, reject NaN, or check numeric ranges. Empty input on either side intentionally gives an empty Array.

After processing the first r signal entries, each output slot contains exactly the sum of contributions from those entries and every kernel entry. Initializing the accumulator with zero and adding rather than replacing preserves this invariant.

For nonempty lengths n and m, the direct block performs n*m multiply-and-add contributions and allocates n+m-1 result slots: O(n*m) arithmetic operations and O(n+m) result space, with constant extra index state. Large-integer and Fraction operation costs depend on operand sizes. No fast-convolution performance claim is made.

Use parentheses around products before adding. In Smalltalk, binary messages have equal precedence and run left to right. The output index i+j-1 is a one-based translation of adding two zero-based offsets.

Correlation has multiple lag conventions. This lesson states one real-valued convention explicitly. Its kernel reversal is visible only with an asymmetric kernel; complex-valued cross-correlation would additionally conjugate one input.

Exact integer and fraction examples compare with =. Floating-point roundoff may differ between mathematically equivalent traversals. A normalized averaging kernel preserves a constant signal only where it fully overlaps; zero-padded edges are not full overlap.

Three practice challenges

Predict a discrete difference

Use kernel #(1 -1) with signal #(2 5 4). Predict the full result and explain its last entry.

Show solution

The result is #(2 3 -1 -4). Interior outputs subtract the previous sample from the current one. The last output is 0-4 because the signal is zero beyond its end. The total is zero, matching sum(signal)*sum(kernel)=11*0.

Recover a distribution of sums

Represent one fair three-sided die by {1/3. 1/3. 1/3}, with entry 1 meaning face 1. Convolve two copies. What probabilities result, and which sum does the first output mean?

Show solution

The exact result is {1/9. 2/9. 1/3. 2/9. 1/9}, representing sums 2 through 6. Array offsets add, but the physical origin also adds: face 1 plus face 1 is sum 2. The probabilities sum to 1, and the middle sum 4 is most likely.

Make the empty contract consistent

Extend the gather oracle so it agrees with the scatter block even when either input is empty. Why is merely allocating n+m-1 positions insufficient?

Show solution

Wrap the whole gather calculation in (a isEmpty or: [b isEmpty]) ifTrue: [#()] ifFalse: [the nonempty gather expression]. With both inputs empty, n+m-1 is -1; with only one empty, it may be positive despite there being no products. The explicit branch gives the chosen empty result in both cases.

Continue learning

Horner Polynomials | Fractions | Sliding Window

Environment reference: official Squeak documentation. This lesson and its examples are original. Verified using native Squeak 6.1 build 23976 on Linux.