-
Notifications
You must be signed in to change notification settings - Fork 122
FE-1500: Add example models and the read-only example page #9362
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,2 @@ | ||
| src/examples/generated/ | ||
| styled-system |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
86 changes: 86 additions & 0 deletions
86
apps/petrinaut-website/scripts/generate-example-artifacts.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| import { readFile, mkdir, writeFile } from "node:fs/promises"; | ||
| import { dirname, resolve } from "node:path"; | ||
| import { fileURLToPath } from "node:url"; | ||
|
|
||
| import { | ||
| compileScenario, | ||
| parseSDCPNFile, | ||
| type SDCPN, | ||
| } from "@hashintel/petrinaut-core"; | ||
| import { | ||
| compileHirArtifacts, | ||
| lowerScenarioToHir, | ||
| type ScenarioHir, | ||
| } from "@hashintel/petrinaut-core/hir"; | ||
|
|
||
| import { | ||
| exampleSlugs, | ||
| type ExampleSlug, | ||
| } from "../src/examples/catalog-metadata.ts"; | ||
| import { normalizeExampleDefinition } from "../src/examples/normalize-example.ts"; | ||
|
|
||
| const scriptDirectory = dirname(fileURLToPath(import.meta.url)); | ||
| const examplesDirectory = resolve(scriptDirectory, "../src/examples"); | ||
| const modelsDirectory = resolve(examplesDirectory, "models"); | ||
| const generatedDirectory = resolve(examplesDirectory, "generated"); | ||
|
|
||
| const parseDefinition = async (slug: ExampleSlug): Promise<SDCPN> => { | ||
| const input = JSON.parse( | ||
| await readFile(resolve(modelsDirectory, `${slug}.json`), "utf8"), | ||
| ) as unknown; | ||
| const parsed = parseSDCPNFile(input); | ||
| if (!parsed.ok) { | ||
| throw new Error(`${slug}: ${parsed.error}`); | ||
| } | ||
| const { title: _title, ...rawDefinition } = parsed.sdcpn; | ||
| return normalizeExampleDefinition(slug, rawDefinition); | ||
| }; | ||
|
|
||
| const generateRuntime = async (slug: ExampleSlug) => { | ||
| const definition = await parseDefinition(slug); | ||
| const { artifacts, failures } = compileHirArtifacts(definition); | ||
| if (failures.length > 0) { | ||
| throw new Error( | ||
| `${slug}: model HIR compilation failed:\n${failures | ||
| .map( | ||
| (failure) => `${failure.kind}:${failure.itemId}: ${failure.message}`, | ||
| ) | ||
| .join("\n")}`, | ||
| ); | ||
| } | ||
|
|
||
| const scenarioHirById: Record<string, ScenarioHir> = Object.create( | ||
| null, | ||
| ) as Record<string, ScenarioHir>; | ||
| for (const scenario of definition.scenarios ?? []) { | ||
| const hir = lowerScenarioToHir({ | ||
| parameterOverrides: scenario.parameterOverrides, | ||
| initialState: scenario.initialState, | ||
| }); | ||
| const outcome = compileScenario( | ||
| scenario, | ||
| hir, | ||
| definition.parameters, | ||
| definition.places, | ||
| definition.types, | ||
| ); | ||
| if (!outcome.ok) { | ||
| throw new Error( | ||
| `${slug}/${scenario.id}: scenario compilation failed:\n${outcome.errors | ||
| .map((error) => error.message) | ||
| .join("\n")}`, | ||
| ); | ||
| } | ||
| scenarioHirById[scenario.id] = hir; | ||
| } | ||
|
|
||
| return `${JSON.stringify({ hirArtifacts: artifacts, scenarioHirById }, null, 2)}\n`; | ||
| }; | ||
|
|
||
| await mkdir(generatedDirectory, { recursive: true }); | ||
|
|
||
| for (const slug of exampleSlugs) { | ||
| const outputPath = resolve(generatedDirectory, `${slug}.json`); | ||
| await writeFile(outputPath, await generateRuntime(slug), "utf8"); | ||
| process.stdout.write(`generated ${outputPath}\n`); | ||
| } |
111 changes: 111 additions & 0 deletions
111
apps/petrinaut-website/src/examples/catalog-metadata.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| /** | ||
| * Static example metadata shared by the browser catalog and server endpoints. | ||
| * | ||
| * Keep this module free of Petrinaut runtime imports and model loaders: Vercel | ||
| * functions that only need to validate a public URL should not bundle every | ||
| * example model and generated simulation artifact. | ||
| */ | ||
| export const exampleSlugs = [ | ||
| "gases-1-pn-consumption-trigger", | ||
| "gases-1-pn", | ||
| "gases-2-spn", | ||
| "gases-3-cpn", | ||
| "gases-4-dcpn", | ||
| "semiconductor-fab-drift", | ||
| "truck-fleet-predictive-maintenance", | ||
| ] as const; | ||
|
|
||
| export type ExampleSlug = (typeof exampleSlugs)[number]; | ||
|
|
||
| export type ExampleSimulationParameterBounds = Readonly<{ | ||
| min: number; | ||
| max: number; | ||
| step: number; | ||
| }>; | ||
|
|
||
| export type ExampleCatalogEntry = Readonly<{ | ||
| slug: ExampleSlug; | ||
| title: string; | ||
| /** Safe UI ranges for scenario parameters, keyed by identifier. */ | ||
| parameterBounds: Readonly<Record<string, ExampleSimulationParameterBounds>>; | ||
| }>; | ||
|
|
||
| const catalog = [ | ||
| { | ||
| slug: "gases-1-pn-consumption-trigger", | ||
| title: "Gases 1 β Consumption Trigger", | ||
| parameterBounds: { | ||
| draw_enabled: { min: 0, max: 1, step: 1 }, | ||
| }, | ||
| }, | ||
| { | ||
| slug: "gases-1-pn", | ||
| title: "Gases 1 β One Customer", | ||
| parameterBounds: { | ||
| draw_enabled: { min: 0, max: 1, step: 1 }, | ||
| }, | ||
| }, | ||
| { | ||
| slug: "gases-2-spn", | ||
| title: "Gases 2 β Shared Tanker", | ||
| parameterBounds: { | ||
| draw_enabled: { min: 0, max: 1, step: 1 }, | ||
| route_scale: { min: 0.5, max: 2, step: 0.1 }, | ||
| }, | ||
| }, | ||
| { | ||
| slug: "gases-3-cpn", | ||
| title: "Gases 3 β Mixed Fleet", | ||
| parameterBounds: { | ||
| route_scale: { min: 0.5, max: 2, step: 0.1 }, | ||
| }, | ||
| }, | ||
| { | ||
| slug: "gases-4-dcpn", | ||
| title: "Gases 4 β Dynamic Coloured Net", | ||
| parameterBounds: { | ||
| hire_enabled: { min: 0, max: 1, step: 1 }, | ||
| route_scale: { min: 0.5, max: 2, step: 0.1 }, | ||
| slow_draw: { min: 0, max: 0.1, step: 0.005 }, | ||
| }, | ||
| }, | ||
| { | ||
| slug: "semiconductor-fab-drift", | ||
| title: "Semiconductor Fab Drift", | ||
| parameterBounds: { | ||
| demand_rate: { min: 0.02, max: 0.3, step: 0.01 }, | ||
| maintenance_threshold: { min: 0.4, max: 0.99, step: 0.01 }, | ||
| wip_cap: { min: 10, max: 100, step: 5 }, | ||
| }, | ||
| }, | ||
| { | ||
| slug: "truck-fleet-predictive-maintenance", | ||
| title: "Truck Fleet Predictive Maintenance", | ||
| parameterBounds: { | ||
| base_severity_mean: { min: 0.5, max: 2, step: 0.05 }, | ||
| base_speed_mean: { min: 0.5, max: 1.5, step: 0.05 }, | ||
| bays: { min: 1, max: 4, step: 1 }, | ||
| drivers: { min: 1, max: 16, step: 1 }, | ||
| motorway_rate: { min: 0.01, max: 0.3, step: 0.005 }, | ||
| mountain_rate: { min: 0.01, max: 0.3, step: 0.005 }, | ||
| parts_lead_time: { min: 12, max: 168, step: 12 }, | ||
| recovery_units: { min: 0, max: 4, step: 1 }, | ||
| service_wear_limit: { min: 0.1, max: 10, step: 0.05 }, | ||
| severe_route_wear_limit: { min: 0.1, max: 1, step: 0.05 }, | ||
| spares: { min: 0, max: 30, step: 1 }, | ||
| technicians: { min: 1, max: 8, step: 1 }, | ||
| trucks: { min: 1, max: 20, step: 1 }, | ||
| urban_rate: { min: 0.01, max: 0.3, step: 0.005 }, | ||
| }, | ||
| }, | ||
| ] as const satisfies readonly ExampleCatalogEntry[]; | ||
|
|
||
| export const exampleCatalog: readonly ExampleCatalogEntry[] = catalog; | ||
|
|
||
| export const isExampleSlug = (value: string): value is ExampleSlug => | ||
| exampleSlugs.some((slug) => slug === value); | ||
|
|
||
| export const getExampleCatalogEntry = ( | ||
| slug: string, | ||
| ): ExampleCatalogEntry | null => | ||
| catalog.find((entry) => entry.slug === slug) ?? null; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
|
|
||
| import { | ||
| exampleCatalog, | ||
| exampleSlugs, | ||
| loadExample, | ||
| loadExampleRuntime, | ||
| } from "./catalog"; | ||
|
|
||
| describe("example catalog", () => { | ||
| it("has a catalog entry for every slug", () => { | ||
| // isExampleSlug gates the routes on exampleSlugs while loadExample | ||
| // resolves the entry with a non-null assertion; this pins the two lists | ||
| // to each other so a slug without an entry fails here, not at render. | ||
| expect(exampleCatalog.map((entry) => entry.slug).toSorted()).toEqual( | ||
| [...exampleSlugs].toSorted(), | ||
| ); | ||
| }); | ||
|
|
||
| it.each(exampleCatalog)( | ||
| "loads $slug with bounded scenario parameters and matching generated HIR", | ||
| async (entry) => { | ||
| const [example, runtime] = await Promise.all([ | ||
| loadExample(entry.slug), | ||
| loadExampleRuntime(entry.slug), | ||
| ]); | ||
|
|
||
| expect(example.catalog).toBe(entry); | ||
|
|
||
| for (const scenario of example.definition.scenarios ?? []) { | ||
| expect(runtime.scenarioHirById).toHaveProperty(scenario.id); | ||
|
|
||
| for (const parameter of scenario.scenarioParameters) { | ||
| const bounds = entry.parameterBounds[parameter.identifier]; | ||
| expect(bounds, parameter.identifier).toBeDefined(); | ||
| expect(bounds!.min).toBeLessThanOrEqual(parameter.default); | ||
| expect(bounds!.max).toBeGreaterThanOrEqual(parameter.default); | ||
| expect(bounds!.step).toBeGreaterThan(0); | ||
| } | ||
| } | ||
| }, | ||
| ); | ||
|
|
||
| it("caches one model/runtime load per example", async () => { | ||
| const entry = exampleCatalog[0]!; | ||
| const [firstExample, secondExample, firstRuntime, secondRuntime] = | ||
| await Promise.all([ | ||
| loadExample(entry.slug), | ||
| loadExample(entry.slug), | ||
| loadExampleRuntime(entry.slug), | ||
| loadExampleRuntime(entry.slug), | ||
| ]); | ||
|
|
||
| expect(secondExample).toBe(firstExample); | ||
| expect(secondRuntime).toBe(firstRuntime); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| import { | ||
| parseSDCPNFile, | ||
| type HirArtifacts, | ||
| type ScenarioHir, | ||
| type SDCPN, | ||
| } from "@hashintel/petrinaut-core"; | ||
|
|
||
| import { | ||
| getExampleCatalogEntry, | ||
| type ExampleCatalogEntry, | ||
| type ExampleSlug, | ||
| } from "./catalog-metadata"; | ||
| import { normalizeExampleDefinition } from "./normalize-example"; | ||
|
|
||
| export { | ||
| exampleCatalog, | ||
| exampleSlugs, | ||
| getExampleCatalogEntry, | ||
| isExampleSlug, | ||
| } from "./catalog-metadata"; | ||
| export type { | ||
| ExampleCatalogEntry, | ||
| ExampleSimulationParameterBounds, | ||
| ExampleSlug, | ||
| } from "./catalog-metadata"; | ||
|
|
||
| export type LoadedExample = Readonly<{ | ||
| catalog: ExampleCatalogEntry; | ||
| definition: SDCPN; | ||
| }>; | ||
|
|
||
| export type GeneratedExampleRuntime = Readonly<{ | ||
| hirArtifacts: HirArtifacts; | ||
| scenarioHirById: Readonly<Record<string, ScenarioHir>>; | ||
| }>; | ||
|
|
||
| const modelLoaders: Record<ExampleSlug, () => Promise<{ default: unknown }>> = { | ||
| "gases-1-pn-consumption-trigger": () => | ||
| import("./models/gases-1-pn-consumption-trigger.json"), | ||
| "gases-1-pn": () => import("./models/gases-1-pn.json"), | ||
| "gases-2-spn": () => import("./models/gases-2-spn.json"), | ||
| "gases-3-cpn": () => import("./models/gases-3-cpn.json"), | ||
| "gases-4-dcpn": () => import("./models/gases-4-dcpn.json"), | ||
| "semiconductor-fab-drift": () => | ||
| import("./models/semiconductor-fab-drift.json"), | ||
| "truck-fleet-predictive-maintenance": () => | ||
| import("./models/truck-fleet-predictive-maintenance.json"), | ||
| }; | ||
|
|
||
| const runtimeLoaders: Record<ExampleSlug, () => Promise<{ default: unknown }>> = | ||
| { | ||
| "gases-1-pn-consumption-trigger": () => | ||
| import("./generated/gases-1-pn-consumption-trigger.json"), | ||
| "gases-1-pn": () => import("./generated/gases-1-pn.json"), | ||
| "gases-2-spn": () => import("./generated/gases-2-spn.json"), | ||
| "gases-3-cpn": () => import("./generated/gases-3-cpn.json"), | ||
| "gases-4-dcpn": () => import("./generated/gases-4-dcpn.json"), | ||
| "semiconductor-fab-drift": () => | ||
| import("./generated/semiconductor-fab-drift.json"), | ||
| "truck-fleet-predictive-maintenance": () => | ||
| import("./generated/truck-fleet-predictive-maintenance.json"), | ||
| }; | ||
|
|
||
| const loadedExamples = new Map<ExampleSlug, Promise<LoadedExample>>(); | ||
| const loadedRuntimes = new Map<ExampleSlug, Promise<GeneratedExampleRuntime>>(); | ||
|
|
||
| export const loadExample = async ( | ||
| slug: ExampleSlug, | ||
| ): Promise<LoadedExample> => { | ||
| const existing = loadedExamples.get(slug); | ||
| if (existing) { | ||
| return existing; | ||
| } | ||
|
|
||
| const loaded = modelLoaders[slug]().then((module) => { | ||
| const parsed = parseSDCPNFile(module.default); | ||
| if (!parsed.ok) { | ||
| throw new Error(parsed.error); | ||
| } | ||
|
|
||
| const { title: _title, ...rawDefinition } = parsed.sdcpn; | ||
| return { | ||
| catalog: getExampleCatalogEntry(slug)!, | ||
| definition: normalizeExampleDefinition(slug, rawDefinition), | ||
| }; | ||
| }); | ||
| // A rejected import (a transient network failure, a stale chunk after a | ||
| // redeploy) must not poison the cache: evict so the next navigation retries. | ||
| loaded.catch(() => { | ||
| loadedExamples.delete(slug); | ||
| }); | ||
| loadedExamples.set(slug, loaded); | ||
| return loaded; | ||
| }; | ||
|
|
||
| export const loadExampleRuntime = async ( | ||
| slug: ExampleSlug, | ||
| ): Promise<GeneratedExampleRuntime> => { | ||
| const existing = loadedRuntimes.get(slug); | ||
| if (existing) { | ||
| return existing; | ||
| } | ||
|
|
||
| const loaded = runtimeLoaders[slug]().then( | ||
| (module) => module.default as GeneratedExampleRuntime, | ||
| ); | ||
| loaded.catch(() => { | ||
| loadedRuntimes.delete(slug); | ||
| }); | ||
| loadedRuntimes.set(slug, loaded); | ||
| return loaded; | ||
| }; | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.