{ "cells": [ { "cell_type": "markdown", "id": "opening", "metadata": {}, "source": [ "# Five tests for 28-day concrete\n", "\n", "Run the cells individually from the application directory with Aner 0.1.2 and local Ollama serving `qwen2.5:14b-instruct`. The offline companion `screen.aner` reproduces the scientific analysis directly. The published CSV files support a retrospective screening exercise." ] }, { "cell_type": "code", "id": "prepare", "metadata": {}, "source": [ "import aner.data\n", "import aner.math\n", "import aner.ml\n", "import aner.tensor\n", "\n", "let schema = data.schema()\n", " .column(\"row_id\", \"Int64\", false).column(\"split\", \"String\", false)\n", " .column(\"cement\", \"Float64\", false).column(\"slag\", \"Float64\", false)\n", " .column(\"fly_ash\", \"Float64\", false).column(\"water\", \"Float64\", false)\n", " .column(\"superplasticizer\", \"Float64\", false)\n", " .column(\"coarse\", \"Float64\", false).column(\"fine\", \"Float64\", false)\n", " .column(\"strength_mpa\", \"Float64\", true)\n", "let source = data.scan_csv(\"data/formulations.csv\", schema, \"NA\")\n", "let density = \"kg/m3\"\n", "let study = data.frame(source.collect(), \"row_id\", \"split\", \"strength_mpa\",\n", " List(\"\", \"\", density, density, density, density, density, density, density, \"MPa\"))\n", "let parts = study.partition_groups(List(\"train\"), List(), List(\"candidate\"))\n", "let model = ml.ridge(alpha: 1.0, standardize: true).fit(parts.train())\n", "let candidates = parts.test().features()\n", "let budget = 5\n", "let target_mpa = 50.0\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "id": "mask", "metadata": {}, "source": [ "The candidate response field is masked. Fit Ridge regression on the training recipes, with training-only standardization. Ingredient amounts are kg/m³ and strength is MPa." ] }, { "cell_type": "code", "id": "rank-functions", "metadata": {}, "source": [ "fn shortlist(forecast: ContextPrediction, slots: Int64) -> Result {\n", " let values = forecast.values()\n", " if slots < 1 || slots > values.rows() { return Result.err(\"Invalid test budget\") }\n", " let chosen = List()\n", " for slot in Range(slots) {\n", " var best = -1\n", " for i in Range(values.rows()) {\n", " if !chosen.contains(i) {\n", " if best < 0 || values.value(i, 0) > values.value(best, 0) ||\n", " (values.value(i, 0) == values.value(best, 0) && forecast.row_id(i) < forecast.row_id(best)) {\n", " best = i\n", " }\n", " }\n", " }\n", " chosen.append(best)\n", " }\n", " return Result.ok(chosen)\n", "}\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "id": "propose", "metadata": {}, "source": [ "## Request the screen\n", "\n", "The scientist grants one named population and one read-only function. The local language model receives the request and tool schema. Inspect its proposed function and scope below." ] }, { "cell_type": "code", "id": "proposal", "metadata": {}, "source": [ "import aner.agent\n", "import aner.llm\n", "\n", "fn predict_strength(model: FittedRidge, recipes: AdaptiveFrame) -> ContextPrediction {\n", " return model.predict(recipes)\n", "}\n", "let tool = agent.register_tool(predict_strength, \"read_only\")\n", "let local = llm.client(provider: \"ollama\", model: \"qwen2.5:14b-instruct\",\n", " endpoint: \"http://127.0.0.1:11434\", timeout_ms: 120000)\n", "let scope = \"candidate_28d\"\n", "let request = \"We have five lab slots. Screen the candidate 28-day concrete mixes for a 50 MPa target.\"\n", "let proposal = llm.tool_turn(local, tool, scope, request)\n", "print(proposal.model())\n", "print(proposal.text())\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "id": "review", "metadata": {}, "source": [ "## Review before dispatch\n", "\n", "Continue only if the proposal names `predict_strength` with scope `candidate_28d`. Stop here to withhold execution. The next cell supplies the fitted predictor and the seven candidate ingredients." ] }, { "cell_type": "code", "id": "dispatch", "metadata": {}, "source": [ "let forecast = agent.call_tool(tool, proposal, scope, model, candidates)\n", "print(forecast.unit())\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "id": "freeze", "metadata": {}, "source": [ "let queue = shortlist(forecast, budget).unwrap()\n", "print(\"Frozen shortlist (row IDs in testing order)\")\n", "for rank in Range(queue.len()) { print(forecast.row_id(cast(queue.get(rank)))) }\n" ], "execution_count": null, "outputs": [] }, { "id": "compare-queues", "cell_type": "markdown", "metadata": {}, "source": [ "## Ask a follow-up before opening the measurements\n", "\n", "Change just the question in the **Ask the lab** cell. The lab desk can compare the two shortlists in either direction or look up the lowest-cement mix in the five selected by Ridge. Ask about cost to try a question the case data cannot answer. For a different question, edit that cell, run it again, and review the new plan before dispatch. The fitted model and frozen queues remain available in the same session.\n", "\n", "Qwen interprets the question. Aner chooses the recipe from the frozen queues and ingredient data, prepares one proposed tool call, and lets the scientist inspect it before running the predictor." ] }, { "id": "follow-up-data", "cell_type": "code", "metadata": {}, "source": [ "let binder_schema = data.schema().column(\"rank\", \"Int64\", false)\n", " .column(\"row_id\", \"Int64\", false).column(\"water_to_binder\", \"Float64\", false)\n", "let binder_table = data.scan_csv(\"results/binder-queue.csv\", binder_schema, \"NA\").collect()\n", "let binder_ids = List()\n", "let ridge_ids = List()\n", "for i in Range(budget) {\n", " binder_ids.append(binder_table.integer(i, \"row_id\"))\n", " ridge_ids.append(forecast.row_id(cast(queue.get(i))))\n", "}\n", "let candidate_table = source.filter(data.col(\"split\") == \"candidate\").collect()\n" ], "execution_count": null, "outputs": [] }, { "id": "follow-up-policies", "cell_type": "code", "metadata": {}, "source": [ "fn first_exclusive(primary: List, other: List) -> Result {\n", " for i in Range(primary.len()) {\n", " let id = cast(primary.get(i))\n", " if !other.contains(id) { return Result.ok(id) }\n", " }\n", " return Result.err(\"The queues contain the same recipes\")\n", "}\n", "\n", "fn least_cement(queue_ids: List, recipes: DataTable) -> Result {\n", " var best_id = -1\n", " var best_dose = 0.0\n", " for i in Range(recipes.rows()) {\n", " let id = recipes.integer(i, \"row_id\")\n", " let dose = recipes.number(i, \"cement\")\n", " if queue_ids.contains(id) && (best_id < 0 || dose < best_dose ||\n", " (dose == best_dose && id < best_id)) {\n", " best_id = id\n", " best_dose = dose\n", " }\n", " }\n", " if best_id < 0 { return Result.err(\"No shortlisted recipe has a cement dose\") }\n", " return Result.ok(best_id)\n", "}\n", "\n", "fn resolve(policy: String, binder: List, ridge: List, recipes: DataTable) -> Result {\n", " if policy == \"binder_only\" { return first_exclusive(binder, ridge) }\n", " if policy == \"ridge_only\" { return first_exclusive(ridge, binder) }\n", " if policy == \"lowest_cement_in_ridge_queue\" { return least_cement(ridge, recipes) }\n", " return Result.err(\"No supported comparison for this question\")\n", "}\n" ], "execution_count": null, "outputs": [] }, { "id": "lab-desk", "cell_type": "code", "metadata": {}, "source": [ "class MixReview {\n", " let policy: String\n", " let row_id: Int64\n", " let cement: Float64\n", " let recipe: AdaptiveFrame\n", " let scope: String\n", " let proposal: LLMResponse\n", "\n", " fn predict(tool: AgentTool, model: FittedRidge) -> ContextPrediction {\n", " return agent.call_tool(tool, proposal, scope, model, recipe)\n", " }\n", "\n", " fn describe() -> String {\n", " return policy + \" | row \" + String(row_id) + \" | \" + String(cement) + \" kg/m3 cement\\n\" + proposal.text()\n", " }\n", "}\n", "\n", "class LabDesk {\n", " let client: LLMClient\n", " let tool: AgentTool\n", " let model: FittedRidge\n", " let pool: AdaptiveFrame\n", " let recipes: DataTable\n", " let binder: List\n", " let ridge: List\n", " var tool_requests: Int64\n", " var predictions: Int64\n", "\n", " fn ask(question: String) -> Result {\n", " tool_requests = 0\n", " predictions = 0\n", " let catalog = \"You route requests to lab software. Identify the requested operation. The software has the data and will compute the answer. Return one exact command.\\n\" +\n", " \"binder_only: Which mix is on the binder shortlist but missing from Ridge?\\n\" +\n", " \"ridge_only: Which mix is on the fitted model's shortlist but missing from the binder rule?\\n\" +\n", " \"lowest_cement_in_ridge_queue: Find the mix with the smallest cement dose (kg/m3) among the lab's five shortlisted recipes. The lab uses the Ridge shortlist.\\n\" +\n", " \"unsupported: All other operations. There are no prices or emissions factors.\"\n", " let turn = client.chat(List(llm.message(\"system\", catalog), llm.message(\"user\", question)),\n", " max_tokens: 32, temperature: 0.0)\n", " let policy = turn.text().trim()\n", " print(\"Interpreted policy: \" + policy)\n", " if turn.finish_reason() != \"stop\" { return Result.err(\"Incomplete interpretation\") }\n", " let id = resolve(policy, binder, ridge, recipes)?\n", " for i in Range(pool.rows()) {\n", " if pool.row_id(i) == id && recipes.integer(i, \"row_id\") == id {\n", " let scope = \"review_row_\" + String(id)\n", " tool_requests = tool_requests + 1\n", " let proposal = llm.tool_turn(client, tool, scope, \"Review this concrete formulation.\")\n", " return Result.ok(MixReview(policy, id, recipes.number(i, \"cement\"), pool.slice(i, i + 1), scope, proposal))\n", " }\n", " }\n", " return Result.err(\"Selected row is outside the aligned candidate pool\")\n", " }\n", "\n", " fn usage() -> String {\n", " return \"Follow-up tool requests: \" + String(tool_requests) + \" | predictions: \" + String(predictions)\n", " }\n", "\n", " fn run(review: MixReview) -> ContextPrediction {\n", " predictions = predictions + 1\n", " return review.predict(tool, model)\n", " }\n", "}\n", "let lab = LabDesk(local, tool, model, candidates, candidate_table, binder_ids, ridge_ids, 0, 0)\n" ], "execution_count": null, "outputs": [] }, { "id": "ask-the-lab", "cell_type": "markdown", "metadata": {}, "source": [ "## Ask the lab\n", "\n", "Edit the quoted question. Other examples from the recorded run include “Which mix did the fitted model promote that the binder rule would pass over?”, “Of the five mixes we would send to the lab, which uses the least cement per cubic metre?” and “Which mix costs least?”" ] }, { "id": "ask-question", "cell_type": "code", "metadata": {}, "source": [ "let question = \"Which mix does the ratio rule add that the fitted model leaves out?\"\n", "let plan = lab.ask(question)\n", "if plan.is_ok() { print(plan.unwrap().describe()) } else { print(plan.unwrap_err()) }\n" ], "execution_count": null, "outputs": [] }, { "id": "review-disagreement", "cell_type": "markdown", "metadata": {}, "source": [ "## Review and run\n", "\n", "Check the interpreted policy, the row, its cement dose and the proposed scope. Continue to request the model prediction for that one formulation. The existing five test slots stay fixed. The counters below cover follow-up requests since the latest question." ] }, { "id": "dispatch-disagreement", "cell_type": "code", "metadata": {}, "source": [ "if plan.is_ok() {\n", " let reviewed = lab.run(plan.unwrap())\n", " print(\"Reviewed row \" + String(reviewed.row_id(0)) + \" | Ridge \" +\n", " String(reviewed.values().value(0, 0)) + \" \" + reviewed.unit())\n", "}\n", "print(lab.usage())\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "id": "compare", "metadata": {}, "source": [ "## Check and unblind\n", "\n", "Compare the returned row identities, units and individual predictions to the native calculation. The retrospective evaluator first joins the answer key after the five selections are fixed." ] }, { "cell_type": "code", "id": "parity", "metadata": {}, "source": [ "fn matched_predictions(left: ContextPrediction, right: ContextPrediction) -> Result {\n", " let a = left.values()\n", " let b = right.values()\n", " if a.rows() != b.rows() || left.unit() != right.unit() { return Result.err(\"Population or unit differs\") }\n", " for i in Range(a.rows()) {\n", " if left.row_id(i) != right.row_id(i) || a.value(i, 0) != b.value(i, 0) {\n", " return Result.err(\"Agent and direct outputs differ at index \" + String(i))\n", " }\n", " }\n", " return Result.ok(a.rows())\n", "}\n", "let direct = model.predict(candidates)\n", "print(\"Exact agent/direct matches: \" + String(matched_predictions(forecast, direct).unwrap()))\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "id": "check-key", "metadata": {}, "source": [ "fn measured_key(forecast: ContextPrediction, table: DataTable) -> Result {\n", " let measured = Dictionary()\n", " if table.rows() != forecast.values().rows() { return Result.err(\"Outcome count differs\") }\n", " for i in Range(table.rows()) {\n", " let id = table.integer(i, \"row_id\")\n", " if measured.contains(id) { return Result.err(\"Duplicate outcome ID \" + String(id)) }\n", " measured.set(id, table.number(i, \"strength_mpa\"))\n", " }\n", " for i in Range(table.rows()) {\n", " if !measured.contains(forecast.row_id(i)) { return Result.err(\"Missing outcome ID\") }\n", " }\n", " return Result.ok(measured)\n", "}\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "id": "unblind", "metadata": {}, "source": [ "// Open the answer key only after freezing the ranking.\n", "let key_schema = data.schema().column(\"row_id\", \"Int64\", false).column(\"strength_mpa\", \"Float64\", false)\n", "let key = data.scan_csv(\"data/outcomes.csv\", key_schema, \"NA\").collect()\n", "let measured = measured_key(forecast, key).unwrap()\n", "let train_mean = source.filter(data.col(\"split\") == \"train\").summarize(1048576, 64).mean(\"strength_mpa\")\n", "let values = forecast.values()\n", "var eligible = 0\n", "var hits = 0\n", "var absolute_error = 0.0\n", "var baseline_error = 0.0\n", "for i in Range(values.rows()) {\n", " let observed = cast(measured.get(forecast.row_id(i)))\n", " if observed >= target_mpa { eligible = eligible + 1 }\n", " absolute_error = absolute_error + math.abs(values.value(i, 0) - observed)\n", " baseline_error = baseline_error + math.abs(train_mean - observed)\n", "}\n", "print(\"rank,row_id,predicted_mpa,observed_mpa\")\n", "for rank in Range(queue.len()) {\n", " let i = cast(queue.get(rank))\n", " let id = forecast.row_id(i)\n", " let observed = cast(measured.get(id))\n", " if observed >= target_mpa { hits = hits + 1 }\n", " print(String(rank + 1) + \",\" + String(id) + \",\" + String(values.value(i, 0)) + \",\" + String(observed))\n", "}\n", "let count = Float64(values.rows())\n", "print(\"Training recipes: \" + String(parts.train().rows()) + \"; candidates: \" + String(values.rows()))\n", "print(\"Measured at or above target: \" + String(eligible) + \"; shortlist hits: \" + String(hits))\n", "print(\"Blind expected hits: \" + String(Float64(budget * eligible) / count))\n", "print(\"Candidate MAE (MPa): ridge \" + String(absolute_error / count) + \"; training mean \" + String(baseline_error / count))\n" ], "execution_count": null, "outputs": [] } ], "metadata": { "aner": { "execution_mode": "persistent-session", "runtime_mode": "production" }, "kernelspec": { "display_name": "Aner", "language": "aner", "name": "aner" }, "language_info": { "name": "aner", "file_extension": ".aner" } }, "nbformat": 4, "nbformat_minor": 5 }