Investigate a small monitoring dataset

Goal: find missing data and a suspicious spike before reporting a daily average. This notebook makes its own eight-row CSV; no download or extra data package is needed. Run Python cells in order.

Investigate a small monitoring dataset

Goal: find missing data and a suspicious spike before reporting a daily average. This notebook makes its own eight-row CSV; no download or extra data package is needed. Run Python cells in order.

To try the AI questions, connect a provider in Configure AI and run each separately. AI answers are text. They do not assign Python variables or save a report. Save this notebook to keep any answers.

The final code cell saves a Markdown evidence report and SVG chart in a new nbinlineai-results/data-… folder under the kernel’s current directory. A copy of the original CSV is kept beside the report; the temporary working CSV is disposable. Keep answers are on by default; turn Keep off only when you mean to rerun a question and its tools.

Saved worked run (2026-10-21)

The Python cells and inline AI questions were executed in an isolated kernel against this notebook’s disposable fabricated inputs, using the live ChatGPT connection. The saved answers and tool tables record actual calls. Generated drafts remain unexecuted unless a later cell explicitly checks them.

from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4
import csv
import statistics
import shutil
from nbinlineai.tools import inspect_value, search_value, insert_code

data_scratch = TemporaryDirectory(prefix="nbinlineai-data-")
data_file = Path(data_scratch.name) / "daily_readings.csv"
seed_rows = [
    ("08:00", "north", "18.2"), ("09:00", "north", "18.5"),
    ("10:00", "north", ""), ("11:00", "north", "18.7"),
    ("12:00", "north", "41.0"), ("13:00", "north", "18.9"),
    ("14:00", "south", "17.8"), ("15:00", "south", "18.0"),
]
with data_file.open("w", newline="", encoding="utf-8") as stream:
    writer = csv.writer(stream)
    writer.writerow(["time", "station", "temperature_c"])
    writer.writerows(seed_rows)
with data_file.open(newline="", encoding="utf-8") as stream:
    readings = list(csv.DictReader(stream))
# Flat strings let bounded value tools show/search the actual nested record fields.
reading_lines = [
    f'{row["time"]} {row["station"]}: {row["temperature_c"] or "[missing]"} °C'
    for row in readings
]
print(f"Loaded {len(readings)} fabricated readings from {data_file}")
Loaded 8 fabricated readings from [temporary local path]

Inspect live values

The CSV is the saved input, and readings holds the current kernel records. The list reading_lines gives a flat, readable view of those records for bounded inspection and search. The custom tool below reads it without changing it. A blank value stays missing. Values above 30 °C are flagged for review, not silently corrected.

def audit_station(station: str) -> str:
    """Count missing and above-30 C readings for one station, without changing data."""
    rows = [row for row in readings if row["station"] == station]
    missing = [row["time"] for row in rows if row["temperature_c"] == ""]
    spikes = [(row["time"], row["temperature_c"]) for row in rows
              if row["temperature_c"] and float(row["temperature_c"]) > 30]
    return f"{station}: {len(rows)} rows; missing at {missing}; above 30 C at {spikes}"

north_audit = audit_station("north")
print(north_audit)
print(inspect_value("reading_lines", start=0, limit=5))
print(search_value("reading_lines", "41.0"))
north: 6 rows; missing at ['10:00']; above 30 C at [('12:00', '41.0')]
reading_lines: list, length 8, start 0
0: '08:00 north: 18.2 °C'
1: '09:00 north: 18.5 °C'
2: '10:00 north: [missing] °C'
3: '11:00 north: 18.7 °C'
4: '12:00 north: 41.0 °C'
Matches in reading_lines (list, length 8):
4: '12:00 north: 41.0 °C'

Tools offered to lower questions

  • &audit_station: run the custom read-only audit in this kernel.
  • &inspect_value: inspect a bounded slice of the live reading_lines list.
  • &search_value: find the 41.0 reading in live reading_lines.
  • &insert_code: optionally insert an editable, unexecuted code draft.

Keep this ordinary Markdown cell’s Tools checkbox on. Each $ reference in a question reads a live kernel value. insert_code is a model-only live editor action; calling it directly in Python raises an error. Its acknowledgement means the open notebook changed, not that the file was saved.

Call audit_station(station="north"), inspect the first five items in reading_lines, and search reading_lines for 41.0. Compare those actual results with $north_audit. Which observation is missing, which is suspicious, and why could a mean including the spike mislead? Do not change or invent a measurement.

The results match the quoted audit: north’s 10:00 reading is missing, and its 12:00 reading of 41.0 °C is suspicious. Including that spike would pull the mean upward, potentially misrepresenting typical temperatures. Leave the missing value blank and flag the spike for review rather than changing either measurement.

Observed live tool calls for the answer above (actual subscription events; private fields shortened).

Tool Result state Submitted arguments Observed result
audit_station completed {“station”:“north”} “north: 6 rows; missing at [‘10:00’]; above 30 C at [(‘12:00’, ‘41.0’)]”
inspect_value completed {“name”:“reading_lines”,“start”:0,“limit”:5} “reading_lines: list, length 8, start 0\n0: ‘08:00 north: 18.2 °C’\n1: ‘09:00 north: 18.5 °C’\n2: ‘10:00 north: [missing] °C’\n3: ‘11:00 north: 18.7 °C’\n4: ‘12:00 north: 41.0 °C’”
search_value completed {“name”:“reading_lines”,“query”:“41.0”} “Matches in reading_lines (list, length 8):\n4: ‘12:00 north: 41.0 °C’”

Compute and save evidence

This code works even without an AI answer. It copies the original CSV beside the report and compares the mean of observed North values with a sensitivity mean that excludes only the flagged spike. It does not claim that the spike is wrong or impute the missing value. Re-running creates a fresh result folder; retain the path you want.

north_rows = [row for row in readings if row["station"] == "north"]
observed = [float(row["temperature_c"]) for row in north_rows if row["temperature_c"]]
reviewed = [value for value in observed if value <= 30]
assert (len(north_rows), len(observed), len(reviewed)) == (6, 5, 4)
assert audit_station("north") == north_audit
raw_mean, reviewed_mean = statistics.mean(observed), statistics.mean(reviewed)
report_dir = Path.cwd() / "nbinlineai-results" / f"data-{uuid4().hex[:8]}"
report_dir.mkdir(parents=True, exist_ok=False)
report_path, chart_path = report_dir / "evidence-report.md", report_dir / "mean-comparison.svg"
shutil.copy2(data_file, report_dir / data_file.name)
report = f"""# North station: daily reading review

Source: fabricated [daily_readings.csv](daily_readings.csv) ({len(readings)} rows); North has {len(north_rows)} rows.

- Missing: 10:00 has an empty temperature; excluded from both means.
- Review flag: 12:00 is 41.0 °C, above this demonstration's 30 °C threshold. Validity unresolved.
- Mean of all {len(observed)} observed North values: {raw_mean:.2f} °C.
- Sensitivity mean without the flagged value ({len(reviewed)} values): {reviewed_mean:.2f} °C.
- Difference: {raw_mean-reviewed_mean:.2f} °C. No value was imputed or overwritten.

![Comparison of the two North means](mean-comparison.svg)

The threshold is a teaching rule, not a calibrated instrument limit. Verify the source before using the sensitivity mean for a real decision.
"""
report_path.write_text(report, encoding="utf-8")
bar1, bar2 = round(raw_mean*12), round(reviewed_mean*12)
chart_path.write_text(f"""<svg xmlns="http://www.w3.org/2000/svg" width="600" height="150" viewBox="0 0 600 150">
<title>North mean temperature sensitivity</title><rect width="600" height="150" fill="white"/>
<text x="10" y="25" font-family="sans-serif">Observed mean: {raw_mean:.2f} C</text>
<rect x="220" y="10" width="{bar1}" height="24" fill="#b85c38"/>
<text x="10" y="80" font-family="sans-serif">Without review flag: {reviewed_mean:.2f} C</text>
<rect x="220" y="65" width="{bar2}" height="24" fill="#307f91"/>
<text x="10" y="130" font-family="sans-serif">One missing value excluded from both means</text></svg>""", encoding="utf-8")
print(report)
print("Saved report:", report_path)
print("Saved chart:", chart_path)
print("Saved source CSV:", report_dir / data_file.name)
# North station: daily reading review

Source: fabricated [daily_readings.csv](daily_readings.csv) (8 rows); North has 6 rows.

- Missing: 10:00 has an empty temperature; excluded from both means.
- Review flag: 12:00 is 41.0 °C, above this demonstration's 30 °C threshold. Validity unresolved.
- Mean of all 5 observed North values: 23.06 °C.
- Sensitivity mean without the flagged value (4 values): 18.57 °C.
- Difference: 4.48 °C. No value was imputed or overwritten.

![Comparison of the two North means](mean-comparison.svg)

The threshold is a teaching rule, not a calibrated instrument limit. Verify the source before using the sensitivity mean for a real decision.

Saved report: [temporary local path]
Saved chart: [temporary local path]
Saved source CSV: [temporary local path]

Optional: call insert_code once to add an unexecuted Python draft after your answer that prints the first three readings and the report_path. Explain that I should inspect the new cell, run it manually, and save the notebook if I want to keep it. Do not claim the draft ran or the insertion saved the notebook.

The unexecuted draft was inserted. Inspect the new cell, run it manually, and save the notebook if you want to keep it. The insertion did not run the code or save the notebook.

Observed live tool calls for the answer above (actual subscription events; private fields shortened).

Tool Result state Submitted arguments Observed result
insert_code completed {“content”:“print(readings[:3])\nprint(report_path)”} Inserted unexecuted code cell f8cf429e-db42-49b5-b7a5-9d4621c16ef5 in the live notebook model (not saved to disk).
print(readings[:3])
print(report_path)

Keep or clean up

Open the printed report and chart paths to review them. The report, linked SVG chart, and copied source CSV remain together in nbinlineai-results after the kernel stops. When done with the disposable input, run data_scratch.cleanup() in a new code cell; that leaves the report and chart intact. If an insertion reply fails, inspect the live notebook before retrying to avoid duplicate drafts.

← Examples guide · Download this notebook