Groovy® Notebooks with groovy-jupyter

Author:  Paul King
PMC Member

Published: 2026-12-02 08:00AM


Introduction

groovy-jupyter is a new Jupyter kernel for Groovy. In this post we take a tour: cells and sessions, tables and charts, then a whisky tasting with the Matrix and jitNN libraries working together in one notebook.

Groovy notebook cells grabbing a library and running a GINQ query, with the resulting table and chart

Notebooks suit Groovy well. The language is concise, scripts need no ceremony, and @Grab brings in libraries without a build file. Several of our earlier data science posts came with Groovy notebooks for BeakerX, but BeakerX’s Groovy kernel hasn’t had a release since 2020 and predates current versions of JupyterLab.

groovy-jupyter fills that gap. It’s a small kernel built on the protocol layer from JJava, and runs Groovy 6 on JDK 17 or later. Version 0.1.0 is its first release. If you spot any rough edges, feedback is very welcome.

All the examples below were run with version 0.1.0 of the kernel, Groovy 6.0.1 and JDK 25.

Getting started

The quickest way to try it is on Binder, which opens JupyterLab in your browser with the kernel and example notebooks ready to go.

To install it locally, you need Jupyter and a JDK. Download the kernelspec zip from the releases page, then:

unzip groovy-jupyter-kernelspec-0.1.0.zip
jupyter kernelspec install groovy-jupyter-kernelspec-0.1.0 --user --name groovy

Then pick "Groovy 6.0.1" as the kernel. The kernel runs on JDK 17+, but some of the libraries you grab may need more. The Matrix and jitNN examples in this post need JDK 22+.

Cells and sessions

In an ordinary Groovy script, a variable declared with def is local to the script. In a notebook, you’d expect to use it in the next cell. The kernel takes care of this, so variables, methods, classes, records and imports all persist for the session:

record Flavor(String name, int score) {
    boolean isStrong() { score >= 3 }
}

def describe(f) { "$f.name is ${f.strong ? 'strong' : 'mild'}" }

def smoky = new Flavor('Smoky', 4)

In a later cell:

describe(smoky)
Smoky is strong

When something goes wrong, you get the diagnostics you’re used to, including power asserts:

def limit = 3
assert smoky.score() < limit
assert smoky.score() < limit
       |     |       | |
       |     4       | 3
       |             false
       Flavor[name=Smoky, score=4]

And if you accidentally run while (true) {}, interrupting the kernel really does stop it. The JDK no longer lets one thread forcibly stop another, so the kernel compiles each cell with Groovy’s ThreadInterrupt transformation, which adds checks to your loops, closures and methods. Your variables survive the interrupt. Code inside third-party libraries doesn’t have those checks, so a runaway loop there may still need a kernel restart.

Tables and charts

The groovy-csv and groovy-ginq modules ship with the kernel. Lists of maps, maps and GINQ results all show as tables. For charts, displayVegaLite takes a Vega-Lite spec, which JupyterLab renders natively. A Vega-Lite spec is JSON, so in Groovy it can be written as a map literal. Here are all three, using the flavor scores of 86 Scotch whisky distilleries that we’ve used in several earlier posts:

JupyterLab showing a CSV file as a table, the result of a GINQ query as a table, and a Vega-Lite chart

The HIDDEN at the end of the last cell suppresses the cell’s own result, in this case the id of the chart, which we’ll have a use for later. There are similar methods for HTML, Markdown, SVG and PNG. SVG images are also sent as PNG, since JupyterLab won’t show SVG in a notebook you haven’t marked as trusted.

Exploring flavors with Matrix

The kernel doesn’t come with a data science library. You grab the ones you want. Our first is Matrix, a Groovy library for tabular data, which featured in Whisky flavor profiles revisited.

@Grab('se.alipsa.matrix:matrix-jupyter:0.1.0')
@Grab('se.alipsa.matrix:matrix-csv:2.5.0')
@Grab('se.alipsa.matrix:matrix-pict:0.6.0')
@Grab('se.alipsa.matrix:matrix-stats:2.5.3')
@Grab('org.slf4j:slf4j-simple:2.0.20')
import se.alipsa.matrix.csv.CsvReader
import se.alipsa.matrix.jupyter.RenderOptions
import se.alipsa.matrix.pict.CorrelationHeatmapChart
import se.alipsa.matrix.pict.RadarChart

RenderOptions.defaults = new RenderOptions(10, 50, true, [:], 760, 500) // max rows and columns, chart size
m = CsvReader.read(new File('whisky.csv')).drop('RowID')

The important one is matrix-jupyter. When it’s grabbed, the kernel finds it using Java’s ServiceLoader and it registers its own renderers. From then on, a matrix as the last line of a cell shows as a table, and a chart shows as a chart, with no registration code in the notebook. In the earlier post we displayed our charts in Swing windows; here they become part of the document.

The values read from the CSV file are strings. We convert them to numbers, and divide by the highest score of 4, so they run from 0 to 1. Then we can look for whiskies that are both fruity and sweet:

features = m.columnNames() - 'Distillery'
features.each { feature -> m.apply(feature) { it.toDouble() / 4 } }
m.subset { it.Fruity > 0.5 && it.Sweetness > 0.5 }

That gives us six whiskies: Aberlour, AnCnoc, Linkwood, Macallan, RoyalBrackla and Strathmill.

Are any of the flavors redundant? In the earlier post, we built a correlation heatmap by hand. Now Matrix has one:

CorrelationHeatmapChart.create('Flavor correlations', m, features)

Heatmap of correlations between the 12 flavors

Smoky and Medicinal go together (0.69), and Medicinal and Floral pull in opposite directions (-0.51), but most of the flavors are reasonably independent.

Adding machine learning with jitNN

jitNN is a machine learning and deep learning library built on TornadoVM, which we looked at in Running Groovy on the GPU with TornadoVM. It can run on a GPU, but we’ll start with the CPU.

It’s an alpha release that isn’t on Maven Central, so the notebook has a cell that downloads its jar and adds it to the session. The TornadoVM API that it needs is available, so for that we can use @Grab. See the notebook for more details. With the jar in place, the next cell can import its classes:

import ai.beestream.jitnn.JitnnRuntime
import ai.beestream.jitnn.Tensor
...

"backend: ${JitnnRuntime.backend()}"
backend: CPU

The CPU backend uses Java’s Vector API, so it needs --add-modules jdk.incubator.vector in the argv of the kernel’s kernel.json file. Without that, jitNN uses slower scalar code, which is fine for 86 whiskies.

Clustering

Matrix and jitNN don’t know about each other, but it doesn’t take much Groovy to go from a matrix to a tensor:

names = m['Distillery'].toList()
rows = m.select(features).rows()*.toList()
flavors = Tensor.of(rows.flatten() as float[], rows.size(), features.size())
Tensor[86, 12] F32

The result of k-means can depend on its random start, so we try 20 seeds and keep the tightest clusters. Those go back into the matrix as a new column, and GINQ can query the matrix directly:

best = (1..20).collect { seed ->
    def kmeans = new KMeans(3, seed).fit(flavors)
    [inertia: kmeans.inertia(), clusters: kmeans.predict(flavors).toList()]
}.min { it.inertia }
m['Cluster'] = best.clusters

GQ {
    from w in m
    groupby w.Cluster into g
    orderby g.key
    select g.key as cluster, g.count() as distilleries, g.avg(w -> w.Smoky).round(2) as smoky,
           g.avg(w -> w.Honey).round(2) as honey, g.avg(w -> w.Body).round(2) as body
}
cluster distilleries smoky honey body

0

35

0.39

0.46

0.62

1

11

0.73

0.11

0.73

2

40

0.28

0.23

0.37

Cluster 1 has the big smoky whiskies, cluster 2 has the lighter ones, and cluster 0 has the fuller-bodied whiskies with more honey.

If you like this, try…​

Next, let’s compare every pair of whiskies. We subtract the average profile, scale each row to length 1, and multiply by the transpose, which gives all 86 x 86 cosine similarities. topk then picks the closest matches for each whisky. We ask for six, since a whisky is always its own best match:

unit = F.lpNormalize(flavors.sub(flavors.mean(0, true)), 2, 1, 1e-8f)
(scores, matches) = unit.matmul(unit.t()).topk(6)
scores = scores.toFloatArray().toList().collate(6)
matches = matches.toIntArray().toList().collate(6)

similarTo = { name ->
    def i = names.indexOf(name)
    [matches[i], scores[i]].transpose().findAll { j, score -> j != i }.collect { j, score ->
        [distillery: names[j], similarity: score.round(2), cluster: m['Cluster'][j]]
    }
}
similarTo('Lagavulin')
distillery similarity cluster

Laphroig

0.94

1

Ardbeg

0.89

1

Clynelish

0.83

1

Caol Ila

0.79

1

Talisker

0.72

1

All five are from the smoky cluster. A Matrix radar chart (also called a spider plot) shows how close the best match is:

pair = m.subset { it.Distillery in ['Lagavulin', 'Laphroig'] }
RadarChart.create('Lagavulin and its closest match', pair, 'Distillery', features)

Radar chart comparing the flavor profiles of Lagavulin and Laphroig

Watching a network train

An autoencoder is a neural network trained to reproduce its input after squeezing it through a narrow middle. Ours squeezes 12 flavors down to just 2 numbers, so the middle gives us a map of the whiskies.

Training is a good use for the kernel’s in-place updates. Each display method returns an id, and the matching update method redraws that output. Here we redraw the loss chart every 25 steps:

encoder = new Sequential(new Linear(12, 16, 1), new Tanh(), new Linear(16, 2, 2))
decoder = new Sequential(new Linear(2, 16, 3), new Tanh(), new Linear(16, 12, 4))
autoencoder = new Sequential(encoder, decoder)
adam = new Adam(autoencoder.parameters(), 0.01f)

history = []
lossChart = { [
    title: 'Autoencoder training', width: 520, height: 200, data: [values: history],
    mark: 'line',
    encoding: [x: [field: 'step', type: 'quantitative', scale: [domain: [0, 1500]]],
               y: [field: 'error', type: 'quantitative', scale: [type: 'log']]]
] }
id = displayVegaLite(lossChart())
(0..1500).each { step ->
    def loss = F.mseLoss(autoencoder.forward(flavors), flavors)
    loss.backward()
    adam.step()
    adam.zeroGrad()
    if (step % 25 == 0) {
        history << [step: step, error: loss.item()]
        updateVegaLite(id, lossChart())
    }
}
HIDDEN

Line chart of the autoencoder error falling over 1500 training steps

This is a tiny network, so don’t blink: all 1501 steps took less than a second on the CPU of my laptop.

Principal component analysis (PCA) also summarizes the flavors as 2 numbers, so we can compare the two maps:

pca = new Pca(2).fit(flavors)
mapOf = { title, points -> [
    title: title, width: 280, height: 240,
    data: [values: points.withIndex().collect { p, i ->
        [distillery: names[i], cluster: m['Cluster'][i], x: p[0], y: p[1]]
    }],
    mark: [type: 'circle', size: 50, tooltip: [content: 'data']],
    encoding: [x: [field: 'x', type: 'quantitative', axis: [title: '']],
               y: [field: 'y', type: 'quantitative', axis: [title: '']],
               color: [field: 'cluster', type: 'nominal']]
] }
points = { it.toFloatArray().toList().collate(2) }
displayVegaLite(hconcat: [mapOf('PCA', points(pca.transform(flavors))),
                          mapOf('Autoencoder', points(encoder.forward(flavors)))])
HIDDEN

Side by side maps of the whiskies from PCA and from the autoencoder, colored by cluster

The clusters came from all 12 flavors, and both maps keep the smoky whiskies (cluster 1) apart from most of the others. In the notebook, hovering over a point shows the distillery.

Moving to the GPU

To use a GPU, replace the tornado-api line with TornadoVM’s runtime and a driver for your hardware. For an NVIDIA GPU:

@Grab('io.github.beehive-lab:tornado-runtime:8.2.0-jdk22plus')
@Grab('io.github.beehive-lab:tornado-drivers-cuda:8.2.0-jdk22plus')

There’s no separate TornadoVM install. You don’t need your own GPU either. Google Colab doesn’t offer Groovy as a runtime, but the kernel can be installed into a Colab session using this bootstrap notebook. On a T4 GPU, multiplying two 2048 x 2048 matrices with jitNN (and summing the result) took a median of 15.3 ms. The CPU backend took 168.7 ms, but Colab’s CPU has few cores, so don’t read too much into the ratio. The first GPU run took 1.6 seconds, which includes compiling the GPU kernel. That run used Groovy 6.0.0.

For 86 whiskies, the CPU is plenty.

More notebooks

The repo has these example notebooks and more:

  • Classification of iris flowers, house price regression and whisky clustering using Smile (JDK 25+, and note Smile’s GPL or commercial licensing)

  • The Matrix and jitNN notebooks that the examples here are based on

  • Natural language processing, including Apache OpenNLP™

  • Review trends for scented candles, read using Apache POI™

  • Apache Spark™, both running inside the kernel and using Spark Connect

  • Local AI models using Ollama4j and LangChain4j, with responses streamed into the notebook

If you have old BeakerX notebooks, there’s a migration guide. Most of the changes are mechanical, like replacing %%classpath add mvn with @Grab. BeakerX’s plotting classes are the exception, and need to be replaced with one of the approaches above.

The kernel also works with other Jupyter clients, such as VS Code and jupyter console, and from Apache Zeppelin™ using its Jupyter bridge.

Current limitations

  • Tuple declarations like def (a, b) = [1, 2] stay local to their cell. Leave off the def, as we did with (scores, matches), and they persist.

  • A @Grab needs to be attached to an import or a declaration. On a plain assignment, it makes that variable local to the cell. That’s also why version in our jitNN cell isn’t available in later cells.

  • Interrupts can’t stop loops inside third-party libraries.

  • Completion doesn’t follow chains of calls.

  • GitHub and nbviewer don’t render Vega-Lite charts.

Conclusion

We’ve seen how groovy-jupyter lets you mix code, tables and charts using Groovy. The kernel stays small and leaves the rest to libraries: Matrix registered its own tables and charts, jitNN provided the machine learning, and Groovy glued them together with a few lines of code. Give it a try on Binder, and let us know what you build!