Skip to content

sankey_mermaid

MermaidSankeyConfiguration

Bases: Viewer, WidgetBase

An interactive Widget for editing the Mermaid JS configuration for Sankey diagram.

See https://mermaid.js.org/schemas/config.schema.json See https://mermaid.js.org/config/schema-docs/config.html#definitions-group-sankeydiagramconfig

Example:

sankey_config = MermaidSankeyConfiguration()

You can use it as a reference value for the MermaidDiagram:

sankey_diagram = MermaidDiagram( ... object="sankey-beta\n\n%% source,target,value\n...", ... configuration=sankey_config, ... )

Source code in src/diffinsights_web/views/plots/sankey_mermaid.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
class MermaidSankeyConfiguration(pn.viewable.Viewer, pn.widgets.WidgetBase):
    """An interactive Widget for editing the Mermaid JS configuration for Sankey diagram.

    See https://mermaid.js.org/schemas/config.schema.json
    See https://mermaid.js.org/config/schema-docs/config.html#definitions-group-sankeydiagramconfig

    Example:

    >>> sankey_config = MermaidSankeyConfiguration()

    You can use it as a *reference value* for the MermaidDiagram:

    >>> sankey_diagram = MermaidDiagram(
    ...    object="sankey-beta\\n\\n%% source,target,value\\n...",
    ...    configuration=sankey_config,
    ... )
    """
    # based on MermaidConfiguration from panel_mermaid
    # https://github.com/awesome-panel/panel-mermaid/blob/main/src/panel_mermaid/mermaid.py
    value: dict = param.Dict(
        constant=True,
        doc="""The Mermaid JS configuration for Sankey diagram.""",
    )

    showValues: bool = param.Boolean(
        default=True,
        doc="""Toggle to display or hide values along with title."""
    )
    linkColor: str = param.Selector(
        default="gradient",
        objects=["source", "target", "gradient"],
        doc=dedent(
            """
            The color of the links in the Sankey diagram:

            - `source` - link will be of a source node color
            - `target` - link will be of a target node color
            - `gradient` - link color will be smoothly transient between source and target node colors
            - hex code of color, like `#a1a1a1` (unsupported)
            """
        )
    )
    nodeAlignment: str = param.Selector(
        default="justify",
        objects=["left", "right", "center", "justify"],
        doc=dedent(
            """
            Defines graph layout of Sankey diagram:

            - `left` - Align all inputs to the left.
            - `right` - Align all outputs to the right.
            - `center` - Like `left`, except that nodes without any incoming links are moved as right as possible.
            - `justify` - Like `left`, except that nodes without any outgoing links are moved to the far right.
            """
        )
    )
    width: int = param.Integer(
        default=600,
        bounds=(0, None),
        doc="""Height of the diagram""",
    )
    height: int = param.Integer(
        default=400,
        bounds=(0, None),
        doc="""Width of the diagram""",
    )
    useMaxWidth: bool = param.Boolean(
        default=False,
        doc=dedent(
            """\
            When this flag is set to `True`, the height and width is set to 100%
            and is then scaled with the available space.
            If set to `False`, the absolute space required is used.
            """
        ),
    )
    prefix: str = param.String(
        default="",
        doc="""The prefix to use for values""",
    )
    suffix: str = param.String(
        default="",
        doc="""The suffix to use for values""",
    )

    def __init__(self, **params):
        super().__init__(**params)

    @param.depends(
        "showValues", "linkColor", "nodeAlignment",
        "useMaxWidth", "width", "height", "prefix", "suffix",
        watch=True, on_init=True
    )
    def _update_value(self):
        value = {
            'sankey': {
                "showValues": self.showValues,
                "linkColor": self.linkColor,
                "nodeAlignment": self.nodeAlignment,
                "useMaxWidth": self.useMaxWidth,
                "width": self.width,
                "height": self.height,
                "prefix": self.prefix,
                "suffix": self.suffix,
            },
        }
        value['sankey'] = {
            key: val
            for key, val in value['sankey'].items()
            if val is not None and val != self.param[key].default
        }
        if not value['sankey']:
            value = {}

        with param.edit_constant(self):
            self.value = value

    def widgets(self) -> list[pn.viewable.Viewable]:
        return [
            self.param.showValues,
            self.param.linkColor,
            self.param.nodeAlignment,
            self.param.useMaxWidth,
            self.param.width,
            self.param.height,
            self.param.prefix,
            self.param.suffix,
        ]

    def __panel__(self):
        return pn.Column(
            *self.widgets()
        )

path_depth

path_depth(path: str) -> int

Return number of components in UNIX path stored as string

Treat '.' as root, with depth 0. Treat any path without '/' as having depth 1; each subsequent '/' means new component.

Parameters:

Name Type Description Default
path str

relative UNIX pathname

required

Returns:

Type Description
int

depth of pathname

Source code in src/diffinsights_web/views/plots/sankey_mermaid.py
119
120
121
122
123
124
125
126
127
128
129
130
131
def path_depth(path: str) -> int:
    """Return number of components in UNIX path stored as string

    Treat '.' as root, with depth 0.  Treat any path without '/' as having
    depth 1; each subsequent '/' means new component.

    :param path: relative UNIX pathname
    :return: depth of pathname
    """
    if path == ".":
        return 0
    else:
        return path.count('/') + 1

path_depth_adj

path_depth_adj(path: str) -> int

Like path_depth, but consider depth of 'path' and 'path/*' to be the same

Parameters:

Name Type Description Default
path str

relative UNIX pathname

required

Returns:

Type Description
int

adjusted depth of pathname

Source code in src/diffinsights_web/views/plots/sankey_mermaid.py
134
135
136
137
138
139
140
141
142
143
def path_depth_adj(path: str) -> int:
    """Like `path_depth`, but consider depth of 'path' and 'path/*' to be the same

    :param path: relative UNIX pathname
    :return: adjusted depth of pathname
    """
    if path == ".":
        return 0
    else:
        return path.count('/') + 1 - int(path.endswith('/*'))

path_parent

path_parent(path: str) -> str

Same as str(PurePath(path).parent), but without wrapping.

Assumes path is POSIX pathname, with '/' as directory separators.

Source code in src/diffinsights_web/views/plots/sankey_mermaid.py
166
167
168
169
170
171
172
173
174
175
def path_parent(path: str) -> str:
    """Same as str(PurePath(path).parent), but without wrapping.

    Assumes `path` is POSIX pathname, with '/' as directory separators.
    """
    last_slash = path.rfind('/')
    if last_slash < 0:
        return '.'
    else:
        return path[:last_slash]

shorten_path_repl

shorten_path_repl(path: str, max_len: int) -> str

Shorten path to max_len components, suffix with '/**' it if it was shortened

Examples:

shorten_path_repl('A/B/C/D/E/F', 2) 'A/B/**' shorten_path_repl('A/B', 2) 'A/B'

Parameters:

Name Type Description Default
path str

relative UNIX pathname

required
max_len int

maximum number of components

required

Returns:

Type Description
str

pathname with up to max_len components

Source code in src/diffinsights_web/views/plots/sankey_mermaid.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
def shorten_path_repl(path: str, max_len: int) -> str:
    """Shorten path to `max_len` components, suffix with '/**' it if it was shortened

    Examples:

    >>> shorten_path_repl('A/B/C/D/E/F', 2)
    'A/B/**'
    >>> shorten_path_repl('A/B', 2)
    'A/B'

    :param path: relative UNIX pathname
    :param max_len: maximum number of components
    :return: pathname with up to `max_len` components
    """
    if path.count('/') >= max_len:
        return '/'.join(path.split(sep='/', maxsplit=max_len)[:max_len] + ['**'])
    else:
        return path