PYTHON · STEP-BY-STEP LESSON

Prepare the 2D field for the browser turtle

We write a small part, check it, and then add the next part.

Download the notebook Open in Colab

All Python notebook lessons

Can we follow a route without leaving the phase?

We start with a picture and a question. Each panel adds one idea before we turn to the equations, code and checks.

1

Choose the allowed region

Choose the allowed region: schematic panel 1

Which cells may the turtle enter?

A binary mask separates allowed and forbidden cells.

2

Follow neighboring occupied cells

Follow neighboring occupied cells: schematic panel 2

Every step needs a valid connection.

The route in the drawing stays inside one edge-connected group. A visual jump would not establish a path.

3

Distinguish an address from a journey

Distinguish an address from a journey: schematic panel 3

Wrapping the display is not the same as closing a route.

For a periodic field, the code keeps wrapped addresses and unwrapped route information. The notebook prepares or validates that data before an optional viewer displays it.

Panels 1–3 are explanatory schematics. Their scales and illustrative fields do not replace the parameters or numerical results in the notebook. Panel 4 shows the notebook’s recorded result or checks.

The calculation, one step at a time

We show the purpose of each notebook cell beside its code and recorded result. The controls move through those results; they do not execute Python in the browser. The notebook remains available for running or changing the calculation.

Loading the lesson…

We load the saved 256² field and convert c≥0.5 into a phase mask. c is dimensionless composition. The transpose and reversal match the screen coordinates. We save a JSON array of occupied pixels, not a predefined turtle route.

We develop this calculation in small steps. We run a cell, inspect its result and test it before adding the next part. Run the cells in order in Jupyter. A code cell defines a part of the calculation or carries it out; defining a function does not run it.

I permit free noncommercial teaching, learning and demonstrations with acknowledgment. Research and commercial use require my written permission. Earlier licensed releases retain their permissions. Read the code-use terms.

Copyright (c) 2026 Saswata Bhattacharyya.

Step 1: Prepare the Python environment

We install the packages listed in the next cell once in the same environment as the notebook. In Jupyter or Colab, remove the comment marker from the installation line below if a package is missing. NumPy stores arrays and evaluates numerical operations. Matplotlib displays plots. Pillow reads and writes images. This installation does not change the model parameters.

# %pip install numpy
import numpy as np
assert np.isfinite(np.array([0.0, 1.0])).all()
print("NumPy is ready:", np.__version__)
NumPy is ready: 2.1.3

Step 2: Read the saved composition

We use the original saved 256² field. We check its dimensions and mean before applying a threshold.

from pathlib import Path
from urllib.request import urlretrieve

work = Path("lesson-data")
work.mkdir(exist_ok=True)

def get_file(relative_path):
    # We download a public example only when its local copy is missing.
    destination = work / Path(relative_path).name
    if not destination.exists():
        urlretrieve("https://saswataiith.github.io/" + relative_path, destination)
    return destination

field_path = get_file("assets/examples/bicontinuity/composition-0.5.npy")
output_path = work / "turtle-field.json"

Step 3: Our check of this result

We check finite values, conservation or the known reference result as specified below. An assertion stops the notebook if the condition fails. Inspect the quantities and tolerance rather than suppressing a failure.

from pathlib import Path
import json
import sys
import numpy as np
composition = np.load(field_path)
assert composition.shape == (256, 256)
assert abs(composition.mean() - 0.5) < 1e-10
screen_field = composition.T[::-1]
result = {'size': 256, 'mean': float(composition.mean()), 'threshold': 0.5, 'source': 'bicontinuity.py, seed 20260921, time 400', 'mask': (screen_field >= 0.5).astype(int).ravel().tolist()}

Step 4: Prepare the next part of the calculation

We define the following operations. These are the same operations as in the original source, written on separate lines so their order is clear. Inspect their values before running the next cell.

Path(output_path).write_text(json.dumps(result, separators=(',', ':')))

Step 5: Review and extend the calculation

Then we change one input, predict its effect and compare the result with that prediction. A successful check establishes the tested property; it does not establish convergence or equilibrium.

Technical details

We first restart the kernel and run all the required cells. The notebook embeds the calculation directly and does not need that script to run.

Technical details

Read the notebook execution checks

More step-by-step Python lessons