Skip to content

The map

modelmap.treemap

Squarified treemap layout: pure geometry, no drawing and no files.

The algorithm is the one in Bruls, Huizing and van Wijk, "Squarified Treemaps" (2000): take the items in decreasing order and fill the rectangle with rows laid along its shorter side, adding items to the current row for as long as that does not worsen the row's worst aspect ratio.

The area of every rectangle is its share of the total, exactly: nothing here insets, pads or rounds. A drawing layer that wants gaps must draw them on top of these rectangles, not shrink them.

Group(name, size, rect, tiles=list()) dataclass

A group of tiles and the rectangle they fill.

Item(key, group, size, label='') dataclass

One thing to place on the map.

Parameters:

Name Type Description Default
key str

Unique identity, for example a path.

required
group str

Name of the group the item belongs to.

required
size float

Size that sets the tile's area; must be positive.

required
label str

Text for sorting ties and for display.

''

Rect(x, y, w, h) dataclass

An axis-aligned rectangle; y grows downward, as in SVG.

aspect property

Long side over short side; 1 for a square, infinite when flat.

Tile(key, group, size, rect, label='', members=list()) dataclass

A placed item, or several small items merged into one tile.

Parameters:

Name Type Description Default
key str

The item's key; for a merged tile, a key made from the group.

required
group str

Group name.

required
size float

The item's size, or the sum for a merged tile.

required
rect Rect

Where the tile is.

required
label str

The item's label; empty for a merged tile.

''
members list[str]

Keys of the items a merged tile stands for; empty for a tile that is one item.

list()

layout(items, rect, *, min_fraction=0.0)

Lay out items in two levels: groups, then the items of each group.

Parameters:

Name Type Description Default
items Sequence[Item]

Items with positive sizes and unique keys.

required
rect Rect

The canvas.

required
min_fraction float

Items smaller than this share of the whole are merged into one tile per group, when a group has two or more of them, so that every tile drawn is large enough to see.

0.0

Returns:

Type Description
list[Group]

Groups from largest to smallest, each with its tiles from largest to smallest. Equal sizes are ordered by label, then key, so the same items always give the same layout.

Source code in src/modelmap/treemap.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def layout(items: Sequence[Item], rect: Rect, *, min_fraction: float = 0.0) -> list[Group]:
    """Lay out items in two levels: groups, then the items of each group.

    :param items: Items with positive sizes and unique keys.
    :param rect: The canvas.
    :param min_fraction: Items smaller than this share of the whole are
        merged into one tile per group, when a group has two or more of
        them, so that every tile drawn is large enough to see.
    :return: Groups from largest to smallest, each with its tiles from
        largest to smallest. Equal sizes are ordered by label, then key,
        so the same items always give the same layout.
    """
    total = sum(item.size for item in items)
    by_group: dict[str, list[Item]] = {}
    for item in items:
        by_group.setdefault(item.group, []).append(item)
    names = sorted(by_group, key=lambda name: (-sum(i.size for i in by_group[name]), name))
    group_sizes = [sum(i.size for i in by_group[name]) for name in names]
    groups = []
    for name, size, group_rect in zip(names, group_sizes, squarify(group_sizes, rect)):
        members = sorted(by_group[name], key=lambda i: (-i.size, i.label, i.key))
        small = [i for i in members if i.size < min_fraction * total]
        if len(small) < 2:
            small = []
        shown = members[: len(members) - len(small)]
        tiles = [Tile(i.key, name, i.size, group_rect, i.label) for i in shown]
        if small:
            merged = Tile(
                key=f"{name}\x00merged",
                group=name,
                size=sum(i.size for i in small),
                rect=group_rect,
                members=[i.key for i in small],
            )
            tiles.append(merged)
        for tile, tile_rect in zip(tiles, squarify([t.size for t in tiles], group_rect)):
            tile.rect = tile_rect
        tiles.sort(key=lambda t: (-t.size, bool(t.members), t.label, t.key))
        groups.append(Group(name, size, group_rect, tiles))
    return groups

squarify(sizes, rect)

Divide a rectangle among sizes, keeping the pieces close to square.

Parameters:

Name Type Description Default
sizes Sequence[float]

Positive sizes, in any order.

required
rect Rect

The rectangle to fill.

required

Returns:

Type Description
list[Rect]

One rectangle per size, in the order of sizes. Their areas are in proportion to the sizes and together they tile rect.

Raises:

Type Description
ValueError

If a size is not positive.

Source code in src/modelmap/treemap.py
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def squarify(sizes: Sequence[float], rect: Rect) -> list[Rect]:
    """Divide a rectangle among sizes, keeping the pieces close to square.

    :param sizes: Positive sizes, in any order.
    :param rect: The rectangle to fill.
    :return: One rectangle per size, in the order of ``sizes``. Their areas
        are in proportion to the sizes and together they tile ``rect``.
    :raises ValueError: If a size is not positive.
    """
    if any(not size > 0 for size in sizes):
        raise ValueError("sizes must be positive")
    if not sizes:
        return []
    order = sorted(range(len(sizes)), key=lambda i: (-sizes[i], i))
    scale = rect.area / sum(sizes)
    areas = [sizes[i] * scale for i in order]
    placed: list[Rect] = []
    x, y, w, h = rect.x, rect.y, rect.w, rect.h
    start = 0
    while start < len(areas):
        side = min(w, h)
        end = start + 1
        total = areas[start]
        ratio = worst(areas[start], areas[start], total, side)
        while end < len(areas):
            grown = total + areas[end]
            # The row is in decreasing order: the first is its largest.
            grown_ratio = worst(areas[start], areas[end], grown, side)
            if grown_ratio > ratio:
                break
            total, ratio, end = grown, grown_ratio, end + 1

        last_row = end == len(areas)
        if w >= h:
            # A column on the left; the last row takes all that is left,
            # so rounding never leaves a sliver uncovered.
            thick = w if last_row else total / h
            offset = y
            for k in range(start, end):
                length = (y + h - offset) if k == end - 1 else areas[k] / thick
                placed.append(Rect(x, offset, thick, length))
                offset += length
            x, w = x + thick, w - thick
        else:
            thick = h if last_row else total / w
            offset = x
            for k in range(start, end):
                length = (x + w - offset) if k == end - 1 else areas[k] / thick
                placed.append(Rect(offset, y, length, thick))
                offset += length
            y, h = y + thick, h - thick
        start = end

    result = [placed[0]] * len(sizes)
    for position, index in enumerate(order):
        result[index] = placed[position]
    return result

worst(largest, smallest, total, side)

The highest aspect ratio in a row, as the paper defines it.

Parameters:

Name Type Description Default
largest float

Largest area in the row.

required
smallest float

Smallest area in the row.

required
total float

Sum of the areas in the row.

required
side float

Length of the side the row is laid along.

required
Source code in src/modelmap/treemap.py
40
41
42
43
44
45
46
47
48
def worst(largest: float, smallest: float, total: float, side: float) -> float:
    """The highest aspect ratio in a row, as the paper defines it.

    :param largest: Largest area in the row.
    :param smallest: Smallest area in the row.
    :param total: Sum of the areas in the row.
    :param side: Length of the side the row is laid along.
    """
    return max(side * side * largest / (total * total), total * total / (side * side * smallest))

modelmap.render_html

Draw a scan as one interactive page that works offline.

The page is a set of views, every one laid out here in Python and written into the file as plain markup:

  • a top view per grouping (by store, format, family or kind);
  • a view per group, where the group's records fill the square;
  • a view per record, where its individual files fill the square.

Clicking a tile opens the view below it, down to the files. The script in the page only shows and hides views, moves a tooltip and copies text; it creates no markup, so a model name can never become code. The page loads nothing from the network.

The page deletes nothing itself. For each record it shows where the files are, which other records use them, and the modelmap rm command that removes the record, or why it cannot.

group_view(by, name)

A group's view id, from the grouping and the group's name.

Source code in src/modelmap/render_html.py
90
91
92
def group_view(by: str, name: str) -> str:
    """A group's view id, from the grouping and the group's name."""
    return f"grp-{by}-{_key(by, name)}"

record_view(record)

A record's view id: from its store and path, so it is the same in every scan.

A view named by position would open another record once one is removed.

Source code in src/modelmap/render_html.py
82
83
84
85
86
87
def record_view(record: ModelRecord) -> str:
    """A record's view id: from its store and path, so it is the same in every scan.

    A view named by position would open another record once one is removed.
    """
    return f"rec-{_key(record.provider, record.path)}"

render_html(scan, *, use_disk=False, served=False, removable=False)

Draw a scan as a self-contained interactive page.

Parameters:

Name Type Description Default
scan Scan

The scan to draw.

required
use_disk bool

Size tiles by bytes allocated on disk, not apparent size.

False
served bool

Add what modelmap serve needs: a Rescan button and the script that calls the server. Every addition is a line of its own, so the page is the file modelmap map writes plus those lines.

False
removable bool

With served, a Remove button in each record's panel and the dialog that confirms it. The server does the removing.

False

Returns:

Type Description
str

The HTML text, ending with a newline.

Source code in src/modelmap/render_html.py
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
def render_html(
    scan: Scan, *, use_disk: bool = False, served: bool = False, removable: bool = False
) -> str:
    """Draw a scan as a self-contained interactive page.

    :param scan: The scan to draw.
    :param use_disk: Size tiles by bytes allocated on disk, not apparent size.
    :param served: Add what ``modelmap serve`` needs: a Rescan button and
        the script that calls the server. Every addition is a line of its
        own, so the page is the file ``modelmap map`` writes plus those lines.
    :param removable: With ``served``, a Remove button in each record's
        panel and the dialog that confirms it. The server does the removing.
    :return: The HTML text, ending with a newline.
    """
    data = build(scan, use_disk=use_disk)
    # `ollama rm` acts on the running Ollama's store: its provider roots, not
    # an Ollama store that was only recognized by its layout somewhere else.
    live = [r.resolved for r in scan.roots if r.provider == "ollama" and r.source != "layout"]
    page = _Page(data, use_disk, live, removable=served and removable)
    parents: dict[int, dict[str, str]] = {i: {} for i in range(len(data.records))}
    drawn = {int(item.key) for item in data.items}
    for by in GROUPINGS:
        ids = page.top(by)
        for index in drawn:
            group = ids[_group_of(data.records[index], by)]
            parents[index][f"parent-{by}"] = group
    for index in range(len(data.records)):
        # A record with no tile is reached from the lists; it hangs off the top.
        links = parents[index] or {"parent": "top-provider"}
        page.record(index, links)

    models = sum(1 for r in data.records if r.kind in ("model", "auxiliary"))
    buttons = "".join(
        f'<button data-by="{by}" aria-pressed="false">{label}</button>'
        for by, label in GROUPINGS.items()
    )
    out = [
        "<!doctype html>",
        '<html lang="en">',
        "<head>",
        '<meta charset="utf-8">',
        '<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">',
        "<title>Local models</title>",
        # The icon is inline, so a browser does not go looking for one.
        '<link rel="icon" href="data:image/svg+xml;base64,'
        + base64.b64encode(_ICON.encode("utf-8")).decode("ascii")
        + '">',
        "<style>",
        _colors(),
        _CSS.strip(),
        _BRAND_CSS.strip(),
        *([_SERVED_CSS] if served else []),
        "</style>",
        "</head>",
        "<body>",
        *_banner(),
        "<header>",
        f'<div><h1>Local models</h1><div class="hero">{_xml(format_size(data.total))}</div>'
        f'<div class="sub">{_xml(_summary(data, models))}</div></div>',
        '<div class="controls">',
        f'<div class="seg" role="group" aria-label="Group by">{buttons}</div>',
        '<input type="search" id="search" placeholder="Filter by name" aria-label="Filter by name">',
        *(
            [
                '<button id="rescan" type="button">Rescan</button>',
                '<span id="served-status" class="sub" role="status"></span>',
            ]
            if served
            else []
        ),
        "</div>",
        "</header>",
        '<nav id="crumbs" aria-label="Where you are"></nav>',
        '<div class="layout">',
        '<div class="map"><svg viewBox="0 0 1000 1000" role="group" aria-label="Map of models by size">',
        *page.views,
        "</svg></div>",
        '<div class="panels">',
        *page.panels,
        "</div>",
        "</div>",
        "<footer>",
        *[f'<p class="sub">{_xml(note)}</p>' for note in _notes(data, use_disk)],
        '<p class="sub">Click a tile to open it, down to its files. Press Escape to go back up.</p>',
        "</footer>",
        '<div id="tip" hidden></div>',
        *([_DIALOG] if served and removable else []),
        "<script>",
        _JS.strip(),
        "</script>",
        *(["<script>", _SERVED_JS.strip(), "</script>"] if served else []),
        "</body>",
        "</html>",
    ]
    return "\n".join(out) + "\n"

modelmap.render_svg

Draw a scan as one static SVG: a square treemap with a header and legend.

The square is divided among the records by size. Tiles of one provider form one block. Each <rect> carries the exact layout geometry (to a thousandth of a unit); the gaps between tiles are strokes in the surface color drawn over the edges, so no tile is shrunk to make room.

The picture adapts to a light or dark setting through prefers-color-scheme. Hovering a tile in a browser shows its details (the SVG <title>).

label_markup(r, clip_id, ink, name, detail, extra='', tag='')

The label of a tile, clipped to it; nothing if no line fits.

Parameters:

Name Type Description Default
r Rect

The tile.

required
clip_id str

Document-unique id for the clip path.

required
ink str

Attribute text that sets the label color, such as class="ink-hf".

required
name str

First line, in bold.

required
detail str

Second line.

required
extra str

Third line.

''
tag str

A small heading above the name, such as the group's name.

''
Source code in src/modelmap/render_svg.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def label_markup(
    r: Rect, clip_id: str, ink: str, name: str, detail: str, extra: str = "", tag: str = ""
) -> list[str]:
    """The label of a tile, clipped to it; nothing if no line fits.

    :param r: The tile.
    :param clip_id: Document-unique id for the clip path.
    :param ink: Attribute text that sets the label color, such as
        ``class="ink-hf"``.
    :param name: First line, in bold.
    :param detail: Second line.
    :param extra: Third line.
    :param tag: A small heading above the name, such as the group's name.
    """
    font = 16 if r.w >= 220 and r.h >= 96 else 13 if r.w >= 110 and r.h >= 44 else 11
    width, room = r.w - 2 * _PAD, r.h - 2 * _PAD + 2
    lines: list[tuple[str, str, float, float]] = []  # class, text, font size, line height
    if tag and r.w >= 96:
        fitted_tag = _fit(tag, width, _TAG_FONT * 1.15)
        if fitted_tag and _TAG_LINE <= room:
            lines.append(("tag", fitted_tag, _TAG_FONT, _TAG_LINE))
    used = sum(line[3] for line in lines)
    for css, text, size in (
        ("name", name, font),
        ("", detail, font * 0.88),
        ("", extra, font * 0.88),
    ):
        fitted = _fit(text, width, size) if text else ""
        if not fitted or used + size * 1.3 > room:
            break  # a detail never appears without the lines above it
        lines.append((css, fitted, size, size * 1.3))
        used += size * 1.3
    if not lines:
        return []

    out = [
        f'<clipPath id="{clip_id}"><rect x="{_num(r.x)}" y="{_num(r.y)}" '
        f'width="{_num(r.w)}" height="{_num(r.h)}"/></clipPath>',
        f'<g clip-path="url(#{clip_id})" {ink} pointer-events="none">',
    ]
    y = r.y + _PAD
    for css, text, size, line_height in lines:
        y += line_height
        attrs = f' class="{css}"' if css else ""
        out.append(
            f'<text{attrs} x="{_num(r.x + _PAD)}" y="{_num(y - line_height * 0.28)}" '
            f'font-size="{_num(size)}">{_xml(text)}</text>'
        )
    out.append("</g>")
    return out

render_svg(scan, *, size=1000, use_disk=False)

Draw a scan as an SVG document.

Parameters:

Name Type Description Default
scan Scan

The scan to draw.

required
size int

Side of the square map, in SVG units.

1000
use_disk bool

Size tiles by bytes allocated on disk, not apparent size.

False

Returns:

Type Description
str

The SVG text, ending with a newline.

Source code in src/modelmap/render_svg.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def render_svg(scan: Scan, *, size: int = 1000, use_disk: bool = False) -> str:
    """Draw a scan as an SVG document.

    :param scan: The scan to draw.
    :param size: Side of the square map, in SVG units.
    :param use_disk: Size tiles by bytes allocated on disk, not apparent size.
    :return: The SVG text, ending with a newline.
    """
    data = build(scan, use_disk=use_disk)
    canvas = Rect(MARGIN, HEADER, size, size)
    groups = layout(data.items, canvas, min_fraction=MIN_FRACTION)
    rows = -(-len(groups) // LEGEND_COLUMNS)
    notes = _notes(data, use_disk)
    width = size + 2 * MARGIN
    height = HEADER + size + 18 + rows * LEGEND_ROW + len(notes) * 18 + MARGIN

    models = sum(1 for r in data.records if r.kind in ("model", "auxiliary"))
    out = [
        f'<svg xmlns="http://www.w3.org/2000/svg" class="modelmap" viewBox="0 0 {width} {height}" '
        f'width="{width}" height="{height}" role="img" '
        f'aria-label="{_xml(_summary(data, models))}">',
        *_css(groups),
        f'<rect class="bg" width="{width}" height="{height}"/>',
        f'<text class="hero" x="{MARGIN}" y="46">{_xml(format_size(data.total))}</text>',
        f'<text class="sub" x="{MARGIN}" y="68">{_xml(_summary(data, models))}</text>',
    ]

    index = 0
    for group_index, group in enumerate(groups):
        out.append(f'<g data-group="{_xml(group.name)}">')
        for position, tile in enumerate(group.tiles):
            out += _tile(tile, index, group_index, data, position == 0, group)
            index += 1
        out.append("</g>")
    for group in groups:
        g = group.rect
        out.append(
            f'<rect class="block" x="{_num(g.x)}" y="{_num(g.y)}" width="{_num(g.w)}" '
            f'height="{_num(g.h)}"/>'
        )

    y = HEADER + size + 18
    column = size / LEGEND_COLUMNS
    for position, group in enumerate(groups):
        x = MARGIN + (position % LEGEND_COLUMNS) * column
        row_y = y + (position // LEGEND_COLUMNS) * LEGEND_ROW
        count = sum(len(t.members) or 1 for t in group.tiles)
        share = 100 * group.size / data.total
        label = DISPLAY_NAMES.get(group.name, group.name)
        out.append(
            f'<rect x="{_num(x)}" y="{_num(row_y)}" width="12" height="12" rx="2" '
            f'style="fill:var(--c{position})"/>'
        )
        out.append(
            f'<text class="key" x="{_num(x + 18)}" y="{_num(row_y + 10.5)}">{_xml(label)}'
            f'<tspan class="key2" dx="8">{_xml(format_size(int(group.size)))}, {share:.0f}%, '
            f"{count} {'entry' if count == 1 else 'entries'}</tspan></text>"
        )
    y += rows * LEGEND_ROW + 6
    for note in notes:
        out.append(f'<text class="sub" x="{MARGIN}" y="{_num(y + 10)}">{_xml(note)}</text>')
        y += 18
    out.append("</svg>")
    return "\n".join(out) + "\n"