graph

package
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 16, 2026 License: Apache-2.0 Imports: 11 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package graph builds a netlist-graph view of a design from the core IR alone, for formats that carry no schematic page (IPC-2581, a bare netlist, a board-only export). It is the fallback behind `agni render --layout=grid` and the other auto-layouts. See docsite/content/architecture/geometry-and-rendering.md#auto-layout-node-drawing.

The output is an ordinary geom.SchematicGeometry, so it feeds the same render backends as a real schematic sheet (SheetSVG, PackSheet) and nothing downstream is graph-specific. Layout stays in the Go core rather than a backend, so every surface reuses it (CONSTRAINTS C1).

A Strategy places nodes (see layout.go) and a shared assembler turns those positions into drawable geometry, so only placement differs between algorithms. This file holds the default grid placer and the helpers assembly shares.

Index

Constants

View Source
const (
	KindProvided   = "provided"   // the design's own symbol
	KindGlyph      = "glyph"      // a classified synthetic glyph
	KindBox        = "box"        // the generic box, no device glyph for this class
	KindUnresolved = "unresolved" // provided symbols requested, but none for this ref (fell back)
)

Report kinds: what a component's node was drawn as.

View Source
const (
	ClassResistor   = string(model.ClassResistor)
	ClassCapacitor  = string(model.ClassCapacitor)
	ClassInductor   = string(model.ClassInductor)
	ClassFerrite    = string(model.ClassFerrite)
	ClassDiode      = string(model.ClassDiode)
	ClassLED        = string(model.ClassLED)
	ClassTVS        = string(model.ClassTVS)
	ClassFuse       = string(model.ClassFuse)
	ClassConnector  = string(model.ClassConnector)
	ClassTestPoint  = string(model.ClassTestPoint)
	ClassCrystal    = string(model.ClassCrystal)
	ClassIC         = string(model.ClassIC)
	ClassTransistor = string(model.ClassTransistor)
	ClassGround     = "ground"
	ClassOther      = "" // generic box
)

Built-in device class ids. Class ids are open strings rather than a closed enum, so a new class is a rule plus a glyph (WS7-030) and users can extend classification without a code change. The empty id is the "no class" fallback that draws the generic node box.

Every id that names a class the engine stamps is BOUND to model's constant rather than spelled again, because a glyph is chosen from the stamped set and an id that drifted by one character would silently draw the box (agni issue 701). ClassGround and ClassOther have no model counterpart, since a power symbol is drawn as a component and classified as none.

View Source
const DefaultStrategy = "grid"

DefaultStrategy is the layout used when the caller does not request one.

Variables

This section is empty.

Functions

func GroundTruthResidual

func GroundTruthResidual(auto, truth map[string]*geom.Point) float64

GroundTruthResidual scores how closely an auto-layout reproduces a set of ground-truth node positions (e.g. a design's real schematic placement), as the normalized Procrustes residual. It matches nodes by ref_des, fits auto onto truth under translation, uniform scale and rotation, and returns the residual in [0,1], where 0 is the same arrangement up to a similarity transform and 1 is unrelated. It returns -1 when fewer than two nodes match or a set is degenerate.

func LayoutWith

func LayoutWith(d *ir.Design, name string, opts ...Option) (*geom.SchematicGeometry, error)

LayoutWith lays a design out with the named strategy and assembles the drawable geometry.

func PositionsByRef

func PositionsByRef(g *geom.SchematicGeometry) map[string]*geom.Point

PositionsByRef extracts a geometry's placement origins keyed by ref_des, across all sheets. Placements with no ref_des (power/flag virtuals) are skipped, so an auto-layout and faithful geometry join on the real components. It is the position form StressOf and GroundTruthResidual compare.

func StressOf

func StressOf(d *ir.Design, positions map[string]*geom.Point) float64

StressOf scores positions against the design's graph distances with Kruskal's normalized stress-1, sqrt(sum w (s*delta - t)^2 / sum w t^2) with the optimal uniform scale s applied before scoring, so the number is scale-invariant (a layout is not penalized for its units) and comparable across strategies on the same design. Pairs in different connected components are skipped (their graph distance is undefined). 0 is a perfect embedding; higher is worse. Returns 0 for designs with fewer than two connected nodes.

Types

type Choice

type Choice struct {
	Cell     string // the drawn symbol's cell_ref
	Class    string // device class id, empty for a provided symbol or a component with no class
	Provided bool   // a provided (the design's own) symbol was drawn
	Fallback bool   // a provided symbol was requested but unavailable for this ref, so it fell back
}

Choice is what a symbol source drew for a component and why. It is the per-component detail behind the conversion report: which cell, which device class, and whether the drawn symbol was the design's own (Provided) or a fallback because a provided one was requested but missing.

type ClassRule

type ClassRule struct {
	// Class is the class id assigned on a match (one of the Class* ids or a user-defined id).
	Class string
	// Symbol is a shell glob (path/filepath.Match) matched, case-insensitively, against the
	// resolved PartType name / section part_ref, i.e. the source symbol (xschem "res", KiCad
	// "Device:R"). This is the authoritative signal and should be tried before Prefix.
	Symbol string
	// Prefix matches when the component's ref-des letter run STARTS WITH it (uppercased), so
	// "R" catches "R1", "RE1", and "RC2" alike. A multi-letter prefix ("LED") is more specific
	// and must be ordered before its single-letter counterpart ("L").
	Prefix string
}

ClassRule maps a component to a device class when it matches. A rule matches when every one of its non-empty conditions matches (AND); an all-empty rule never matches. Rules are tried in order and the first match wins, so order is precedence: put the strongest signal (the source symbol/part-type) and the more specific patterns first.

type ComponentReport

type ComponentReport struct {
	RefDes string `json:"ref_des"`
	Symbol string `json:"symbol,omitempty"` // source part/symbol name (PartType.Name)
	Class  string `json:"class,omitempty"`  // assigned device class (empty for a provided symbol or no class)
	Cell   string `json:"cell"`             // drawn symbol cell_ref
	Kind   string `json:"kind"`             // provided | glyph | box | unresolved
}

ComponentReport is one component's entry in the conversion report.

func (ComponentReport) Label

func (c ComponentReport) Label() string

Label is how the component groups in the report summary: its device class for a glyph, else its kind (provided / box / unresolved).

type ConversionReport

type ConversionReport struct {
	Components []ComponentReport `json:"components"`
}

ConversionReport is how an auto-layout mapped each component to a drawn node: its device class, the symbol it drew, and whether that was a glyph, the box (unmapped class), a provided symbol, or an unresolved fallback. It is the visibility behind "why is this a box" (WS7-029).

func BuildReport

func BuildReport(d *ir.Design, source SymbolSource) *ConversionReport

BuildReport classifies and resolves each component through the symbol source (the same decisions assemble makes when drawing) and records them, in ref-des order for stable output. A nil source reports against the default registry (synthetic glyphs).

func (*ConversionReport) RefsByKind

func (r *ConversionReport) RefsByKind(kind string) []string

RefsByKind returns the ref-des of every component drawn as the given kind, in order.

type Explainer

type Explainer interface {
	Explain(ref string, c *ir.Component, parts map[string]*ir.PartType) Choice
}

Explainer is an optional SymbolSource capability: besides drawing a symbol, it explains the choice (class, provided/fallback) so the conversion report can attribute each node. Registry and FaithfulSource implement it; a source that does not is reported from its drawn symbol alone (provided-vs-synthetic inferred from the cell_ref).

type FaithfulSource

type FaithfulSource struct {
	// contains filtered or unexported fields
}

FaithfulSource draws each component with its real symbol from a design's geometry sidecar, keyed by ref_des, so an auto-layout can re-place the design's own artwork instead of synthetic glyphs (partial-faithful mode). Components with no faithful symbol fall back to a base source (normally the Registry, then the box), so a design that mixes provided and unknown parts still renders every node.

func NewFaithfulSource

func NewFaithfulSource(faithful *geom.SchematicGeometry, base SymbolSource) *FaithfulSource

NewFaithfulSource indexes a geometry sidecar by ref_des (via each placement's cell_ref) so a component resolves to the symbol the design actually drew it with. base supplies the fallback for refs the sidecar does not cover; a nil base uses DefaultRegistry.

func (*FaithfulSource) Covers

func (f *FaithfulSource) Covers() int

Covers reports how many placed ref_des the source has a real (non-placeholder) symbol for, so a caller can tell an empty/unresolved join from a real one.

func (*FaithfulSource) Explain

func (f *FaithfulSource) Explain(ref string, c *ir.Component, parts map[string]*ir.PartType) Choice

Explain implements Explainer for the FaithfulSource. It reports a provided symbol when the sidecar covers the ref, else the base source's choice marked as a fallback (the "unresolved" signal).

func (*FaithfulSource) Symbol

func (f *FaithfulSource) Symbol(ref string, c *ir.Component, parts map[string]*ir.PartType) *geom.SymbolDef

Symbol returns the component's faithful symbol, or the base source's symbol when the sidecar has none for that ref_des.

type Option

type Option func(*layoutConfig)

Option configures a layout call. With no options a layout draws nodes with DefaultRegistry (classified synthetic glyphs).

func WithRegistry

func WithRegistry(r *Registry) Option

WithRegistry draws nodes with the given classification/glyph registry, so a caller (the CLI/serve edge) can layer user classification rules on top of the defaults.

func WithSymbolSource

func WithSymbolSource(s SymbolSource) Option

WithSymbolSource draws nodes with the given symbol source: the Registry (synthetic glyphs) or a FaithfulSource (the design's own artwork, re-laid-out).

type Placement

type Placement struct {
	Positions map[string]*geom.Point
	// Route selects how assemble draws each net, as the default hyperedge star or as orthogonal
	// L-runs (WS7-010). It is a style rather than route points because assemble re-spaces positions
	// (compactBySize) after the strategy returns, so only assemble knows the final positions.
	Route RouteStyle
}

Placement is what a layout strategy produces, a position for each component node keyed by ref_des. Turning positions into drawable geometry is shared across all strategies (see assemble), so a new layout algorithm implements placement only.

type Quality

type Quality struct {
	Nodes        int     // placed component nodes
	Nets         int     // drawn net hyperedges
	Segments     int     // straight-line segments across all edges
	Crossings    int     // pairs of segments that properly cross (excludes shared endpoints)
	Bends        int     // direction changes within wire polylines (orthogonal routing's cost)
	TotalEdgeLen float64 // sum of segment lengths, in layout units
	Stress       float64 // normalized stress-1 vs graph distance (0 = perfect; MeasureWith only)
}

Quality scores a produced layout with numbers comparable across layout algorithms on the same design. It reads the finished geometry, so it works for every strategy unchanged.

Crossings is the headline readability metric and is scale-invariant. TotalEdgeLen is in layout units, so it is only comparable between layouts of the *same* design.

Stress is the gap between drawn distance and graph-theoretic distance (Kruskal's normalized stress-1, see StressOf). Graph distances live in the design, so Measure leaves it zero and MeasureWith fills it.

func Measure

func Measure(g *geom.SchematicGeometry) Quality

Measure scores the layout on sheet 0. Crossing detection is O(segments^2), so it is slow on a large board.

func MeasureWith

func MeasureWith(d *ir.Design, g *geom.SchematicGeometry) Quality

MeasureWith is Measure plus the design-aware Stress score (Measure alone reads finished geometry, which does not carry graph distances). Use it wherever the design is at hand, e.g. the --compare table, so every strategy gets stress-scored, not just the stress layout.

type Registry

type Registry struct {
	// UserRules are caller-supplied rules (the CLI's --class), tried FIRST and ahead of the
	// stamped class, because a user naming a glyph for a symbol is saying what to draw.
	UserRules []ClassRule
	// Rules is the built-in fallback table, tried only when a component carries no stamped class.
	Rules  []ClassRule
	Glyphs map[string]*geom.SymbolDef // class id -> glyph; a class with no entry draws the box
}

Registry is the data behind auto-layout node drawing: the rules that classify a component when nothing else has, and a class-id -> glyph map that supplies the artwork. It is injected into the layout (WithRegistry) rather than hardcoded, so callers can extend classification and glyphs. The zero value is not usable; build one with DefaultRegistry (optionally .With user rules).

A component the ingestion pass already stamped (ir.Component.device_classes) is drawn from that stamp, so the picture and the facts cannot disagree about what a part is (agni issue 701). UserRules win outright over the stamp, and Rules is the fallback for a component carrying none.

func DefaultRegistry

func DefaultRegistry() *Registry

DefaultRegistry is the built-in classifier and glyph set. Rules are ordered strongest-signal first: the source symbol/part-type name, then ref-des prefixes (multi-letter exceptions like LED before the single letters). Callers extend it with With; the CLI/serve edge layers user rules on top.

func (*Registry) Classify

func (r *Registry) Classify(c *ir.Component, parts map[string]*ir.PartType) string

Classify returns the device class id for a component. That is a matching user rule, else the class the ingestion pass stamped on it, else the first built-in rule that matches its source symbol/part-type name (preferred) or ref-des prefix, else ClassOther (the box). A resolved PartType's designator_prefix, when present, overrides the ref-des guess.

The stamp comes from classify.Stamp, which reads part text, the project's own lexicon.class patterns and refinements no glob can express, on every read. A second classifier here would answer "diode" for a part the engine calls a tvs, and the drawing would disagree with a query answer (agni issue 701).

func (*Registry) Explain

func (r *Registry) Explain(_ string, c *ir.Component, parts map[string]*ir.PartType) Choice

Explain implements Explainer for the Registry, giving the component's class and the cell it was drawn with. The two can differ and the report says both, so a thermistor drawn with the resistor glyph is still reported as a thermistor.

func (*Registry) GlyphClasses

func (r *Registry) GlyphClasses() []string

GlyphClasses returns the class ids the registry can DRAW, sorted, for validating user input and for error messages. That is the classes with a glyph of their own plus the ones that reach a glyph through glyphAliases, so a user rule may name "thermistor", which draws as a resistor.

func (*Registry) Symbol

func (r *Registry) Symbol(_ string, c *ir.Component, parts map[string]*ir.PartType) *geom.SymbolDef

Symbol implements SymbolSource: the glyph for the component's class (the box when its class reaches none), so the Registry is the synthetic-glyph symbol source for a layout.

func (*Registry) With

func (r *Registry) With(rules ...ClassRule) *Registry

With returns a copy of the registry with the given rules prepended to UserRules, so they take precedence over both the stamped class and the built-in defaults (first match wins). The glyph map is shared with r, so user rules map to the existing glyphs unless the caller also adds a glyph for a new class id.

type RouteStyle

type RouteStyle string

RouteStyle names how nets are drawn between placed nodes.

const (
	RouteStar       RouteStyle = ""
	RouteOrthogonal RouteStyle = "orthogonal"
)

Route styles: the straight hyperedge star (default) and axis-aligned orthogonal runs.

type Strategy

type Strategy struct {
	Name  string
	Doc   string
	Place func(*ir.Design) Placement
}

Strategy is a named layout algorithm. Place maps a design's components to node positions, and everything downstream of placement is shared. Strategies lists them and ByName selects one.

func ByName

func ByName(name string) (Strategy, error)

ByName returns the named strategy. The error lists the available names, so a CLI typo shows the valid choices.

func Strategies

func Strategies() []Strategy

Strategies returns the available layout strategies sorted by name. Every layout lives in this package, so the list is built per call rather than kept in a registry, and tests cannot leak strategies into one another.

type SymbolSource

type SymbolSource interface {
	Symbol(ref string, c *ir.Component, parts map[string]*ir.PartType) *geom.SymbolDef
}

SymbolSource supplies the drawable symbol for each component node in an auto-layout, so the layout stays fixed while what gets drawn at a node varies. The Registry (classified synthetic glyphs, WS7-030) is one implementation and FaithfulSource (the design's own symbol artwork, WS7-031) is another. Symbol is called once per placed component; the returned SymbolDef's CellRef keys the placement to the shipped symbol library, so a source must return a stable CellRef per distinct symbol. c may be nil when a placed ref has no matching component.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL