Skip to content

Formatting of objects

Reference

measured.formatting

dimension_mathml(dimension: Dimension) -> str

Formats the given Dimension as a MathML expression

Source code in src/measured/formatting.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def dimension_mathml(dimension: "Dimension") -> str:
    """Formats the given Dimension as a MathML expression"""
    numerator, denominator = dimension.as_ratio()

    n = (
        "<mo>⋅</mo>".join(
            (
                "<msup>"
                f"<mi>{dimension.symbol}</mi>"
                "<mn>"
                f"{numerator.exponents[i] if numerator.exponents[i] != 1 else ''}"
                "</mn>"
                "</msup>"
            )
            for i, dimension in enumerate(dimension._fundamental)
            if numerator.exponents[i] != 0
        )
        or "<mi>1</mi>"
    )

    d = "<mo>⋅</mo>".join(
        (
            "<msup>"
            f"<mi>{dimension.symbol}</mi>"
            "<mn>"
            f"{denominator.exponents[i] if denominator.exponents[i] != 1 else ''}"
            "</mn>"
            "</msup>"
        )
        for i, dimension in enumerate(dimension._fundamental)
        if denominator.exponents[i] != 0
    )

    if n and not d:
        return f"<mrow>{n}</mrow>"

    return f"<mfrac><mrow>{n}</mrow><mrow>{d}</mrow></mfrac>"

dimension_pretty(dimension: Dimension, pretty: RepresentationPrinter, cycle: bool) -> None

Formats the given Dimension to the provided pretty printer

Source code in src/measured/formatting.py
 98
 99
100
101
102
103
104
105
106
107
108
109
def dimension_pretty(
    dimension: "Dimension", pretty: "RepresentationPrinter", cycle: bool
) -> None:
    """Formats the given Dimension to the provided pretty printer"""
    with pretty.group():
        pretty.text(str(dimension))
        with pretty.group(indent=2):
            pretty.break_()
            if dimension.name:
                pretty.text(dimension.name)
                pretty.break_()
            pretty.text(repr(dimension))

dimension_repr(dimension: Dimension) -> str

Formats the given Dimension as a Python repr

Source code in src/measured/formatting.py
73
74
75
76
77
78
79
80
def dimension_repr(dimension: "Dimension") -> str:
    """Formats the given Dimension as a Python `repr`"""
    return (
        "Dimension("
        f"exponents={dimension.exponents!r}, "
        f"name={dimension.name!r}, symbol={dimension.symbol!r}"
        ")"
    )

dimension_str(dimension: Dimension) -> str

Formats the given Dimension as a plaintext string

Source code in src/measured/formatting.py
83
84
85
86
87
88
89
90
91
92
93
94
95
def dimension_str(dimension: "Dimension") -> str:
    """Formats the given Dimension as a plaintext string"""
    if dimension.symbol:
        return dimension.symbol

    return (
        "⋅".join(
            f"{fundamental.symbol}{superscript(dimension.exponents[i])}"
            for i, fundamental in enumerate(dimension._fundamental)
            if dimension.exponents[i] != 0
        )
        or "?"
    )

from_superscript(string: str) -> int

Given a Unicode superscript string, return it as an integer.

Source code in src/measured/formatting.py
53
54
55
def from_superscript(string: str) -> int:
    """Given a Unicode superscript string, return it as an integer."""
    return int("".join(DIGITS[c] for c in string))

level_mathml(level: Level) -> str

Formats the given Level as a MathML expression

Source code in src/measured/formatting.py
520
521
522
523
524
525
526
527
528
def level_mathml(level: "Level") -> str:
    """Formats the given Level as a MathML expression"""
    return (
        "<mrow>"
        f"<mn>{level.magnitude}</mn>"
        "<mo>⋅</mo>"
        f"{logarithmic_unit_mathml(level.unit)}"
        "</mrow>"
    )

level_pretty(level: Level, pretty: RepresentationPrinter, cycle: bool) -> None

Formats the given Level to the provided pretty printer

Source code in src/measured/formatting.py
507
508
509
510
511
512
513
514
515
516
517
def level_pretty(level: "Level", pretty: "RepresentationPrinter", cycle: bool) -> None:
    """Formats the given Level to the provided pretty printer"""
    with pretty.group():
        pretty.text(str(level))
        with pretty.group(indent=2):
            pretty.break_()
            pretty.pretty(level.magnitude)
            pretty.break_()
            pretty.pretty(level.unit)
            pretty.break_()
            pretty.text(repr(level))

level_repr(level: Level) -> str

Formats the given Level as a Python repr

Source code in src/measured/formatting.py
497
498
499
def level_repr(level: "Level") -> str:
    """Formats the given Level as a Python `repr`"""
    return f"Level(magnitude={level.magnitude!r}, unit={level.unit!r})"

level_str(level: Level) -> str

Formats the given Level as a plaintext string

Source code in src/measured/formatting.py
502
503
504
def level_str(level: "Level") -> str:
    """Formats the given Level as a plaintext string"""
    return f"{level.magnitude} {level.unit}"

logarithm_mathml(logarithm: Logarithm) -> str

Formats the given Logarithm as a MathML expression

Source code in src/measured/formatting.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
def logarithm_mathml(logarithm: "Logarithm") -> str:
    """Formats the given Logarithm as a MathML expression"""
    if logarithm.symbol:
        return f"<mi>{logarithm.symbol}</mi>"

    prefix = (
        f"<mn>{logarithm.prefix.quantify()}</mn>" if logarithm.prefix.exponent else ""
    )
    function = "ln" if logarithm.base == math.e else f"log{logarithm.base}"
    return (
        "<mrow>"
        f"{prefix}"
        f"<mi>{function}</mi>"
        "<mo>(</mo>"
        "<mfrac>"
        f"<mi>x</mi>"
        f"<mi>x₀</mi>"
        "</mfrac>"
        "<mo>)</mo>"
        "</mrow>"
    )

logarithm_pretty(logarithm: Logarithm, pretty: RepresentationPrinter, cycle: bool) -> None

Formats the given Logarithm to the provided pretty printer

Source code in src/measured/formatting.py
420
421
422
423
424
425
426
427
428
def logarithm_pretty(
    logarithm: "Logarithm", pretty: "RepresentationPrinter", cycle: bool
) -> None:
    """Formats the given Logarithm to the provided pretty printer"""
    with pretty.group():
        pretty.text(str(logarithm))
        with pretty.group(indent=2):
            pretty.break_()
            pretty.text(repr(logarithm))

logarithm_repr(logarithm: Logarithm) -> str

Formats the given Logarithm as a Python repr

Source code in src/measured/formatting.py
399
400
401
402
403
404
405
406
407
408
def logarithm_repr(logarithm: "Logarithm") -> str:
    """Formats the given Logarithm as a Python `repr`"""
    return (
        "Logarithm("
        f"prefix={logarithm.prefix!r}, "
        f"base={logarithm.base!r}, "
        f"name={logarithm.name!r}, "
        f"symbol={logarithm.symbol!r}"
        ")"
    )

logarithm_str(logarithm: Logarithm) -> str

Formats the given Logarithm as a plaintext string

Source code in src/measured/formatting.py
411
412
413
414
415
416
417
def logarithm_str(logarithm: "Logarithm") -> str:
    """Formats the given Logarithm as a plaintext string"""
    if logarithm.symbol:
        return logarithm.symbol

    function = "ln" if logarithm.base == math.e else f"log{logarithm.base}"
    return f"{logarithm.prefix.quantify()} {function}(x/x₀)"

logarithmic_unit_mathml(logarithmic_unit: LogarithmicUnit) -> str

Formats the given LogarithmicUnit as a MathML expression

Source code in src/measured/formatting.py
483
484
485
486
487
488
489
490
491
492
493
494
def logarithmic_unit_mathml(logarithmic_unit: "LogarithmicUnit") -> str:
    """Formats the given LogarithmicUnit as a MathML expression"""
    if logarithmic_unit.symbol:
        return f"<mi>{logarithmic_unit.symbol}</mi>"

    return (
        "<mrow>"
        f"{logarithm_mathml(logarithmic_unit.logarithm)}"
        "<mo>of</mo>"
        f"{quantity_mathml(logarithmic_unit.reference)}"
        "</mrow>"
    )

logarithmic_unit_pretty(logarithmic_unit: LogarithmicUnit, pretty: RepresentationPrinter, cycle: bool) -> None

Formats the given LogarithmicUnit to the provided pretty printer

Source code in src/measured/formatting.py
472
473
474
475
476
477
478
479
480
def logarithmic_unit_pretty(
    logarithmic_unit: "LogarithmicUnit", pretty: "RepresentationPrinter", cycle: bool
) -> None:
    """Formats the given LogarithmicUnit to the provided pretty printer"""
    with pretty.group():
        pretty.text(str(logarithmic_unit))
        with pretty.group(indent=2):
            pretty.break_()
            pretty.text(repr(logarithmic_unit))

logarithmic_unit_repr(logarithmic_unit: LogarithmicUnit) -> str

Formats the given LogarithmicUnit as a Python repr

Source code in src/measured/formatting.py
454
455
456
457
458
459
460
461
def logarithmic_unit_repr(logarithmic_unit: "LogarithmicUnit") -> str:
    """Formats the given LogarithmicUnit as a Python `repr`"""
    return (
        "LogarithmicUnit("
        f"logarithm={logarithmic_unit.logarithm!r}, "
        f"reference={logarithmic_unit.reference!r}"
        ")"
    )

logarithmic_unit_str(logarithmic_unit: LogarithmicUnit) -> str

Formats the given LogarithmicUnit as a plaintext string

Source code in src/measured/formatting.py
464
465
466
467
468
469
def logarithmic_unit_str(logarithmic_unit: "LogarithmicUnit") -> str:
    """Formats the given LogarithmicUnit as a plaintext string"""
    if logarithmic_unit.symbol:
        return logarithmic_unit.symbol

    return f"{logarithmic_unit.logarithm} of {logarithmic_unit.reference}"

mathml(function: Callable[[M], str]) -> Callable[[M], str]

Wraps the given MathML-producing function to produce a self-contained MathML tag. This allows for composable MathML functions that can produce both expressions and root MathML tag.

Source code in src/measured/formatting.py
61
62
63
64
65
66
67
68
69
70
def mathml(function: Callable[[M], str]) -> Callable[[M], str]:
    """Wraps the given MathML-producing function to produce a self-contained
    MathML tag.  This allows for composable MathML functions that can produce both
    expressions and root MathML tag."""

    @wraps(function)
    def inner(measured_object: M) -> str:
        return f"<math>{function(measured_object)}</math>"

    return inner

measurement_format(measurement: Measurement, format_specifier: str) -> str

Formats the given Measurement as a plaintext string, using the provided format specifier to control the output

Source code in src/measured/formatting.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
def measurement_format(measurement: "Measurement", format_specifier: str) -> str:
    """Formats the given Measurement as a plaintext string, using the provided format
    specifier to control the output"""
    uncertainty_format, _, quantity_format = format_specifier.partition(":")

    style, magnitude_format = "", ""
    if uncertainty_format:
        style, magnitude_format = uncertainty_format[0], uncertainty_format[1:]

    if style in ("", "+", "±"):
        magnitude = measurement.uncertainty.magnitude.__format__(magnitude_format)
        uncertainty = f{magnitude}"
    elif style == "%":
        magnitude_format = magnitude_format or ".2f"
        percent = measurement.uncertainty_percent.__format__(magnitude_format)
        uncertainty = f{percent}%"
    else:
        raise ValueError(f"Unrecognized uncertainty style {style!r}")

    magnitude_format, _, unit_format = quantity_format.partition(":")
    magnitude = measurement.measurand.magnitude.__format__(magnitude_format)
    unit = measurement.measurand.unit.__format__(unit_format)
    return f"{magnitude}{uncertainty} {unit}"

measurement_mathml(measurement: Measurement) -> str

Formats the given Measurement as a MathML expression

Source code in src/measured/formatting.py
588
589
590
591
592
593
594
595
596
597
598
def measurement_mathml(measurement: "Measurement") -> str:
    """Formats the given Measurement as a MathML expression"""
    return (
        "<mrow>"
        f"<mn>{measurement.measurand.magnitude}</mn>"
        "<mo>±</mo>"
        f"<mn>{measurement.uncertainty.magnitude}</mn>"
        "<mo></mo>"
        f"{unit_mathml(measurement.measurand.unit)}"
        "</mrow>"
    )

measurement_pretty(measurement: Measurement, pretty: RepresentationPrinter, cycle: bool) -> None

Formats the given Measurement to the provided pretty printer

Source code in src/measured/formatting.py
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
def measurement_pretty(
    measurement: "Measurement", pretty: "RepresentationPrinter", cycle: bool
) -> None:
    """Formats the given Measurement to the provided pretty printer"""
    with pretty.group():
        pretty.text(f"{measurement:::/}")
        with pretty.group(indent=2):
            pretty.break_()
            pretty.pretty(measurement.measurand.magnitude)
            pretty.text(" ±")
            pretty.pretty(measurement.uncertainty.magnitude)
            pretty.break_()
            pretty.pretty(measurement.measurand.unit)
            pretty.break_()
            pretty.text(repr(measurement))

measurement_repr(measurement: Measurement) -> str

Formats the given Measurement as a Python repr

Source code in src/measured/formatting.py
531
532
533
534
535
536
537
538
def measurement_repr(measurement: "Measurement") -> str:
    """Formats the given Measurement as a Python `repr`"""
    return (
        f"Measurement("
        f"measurand={measurement.measurand!r}, "
        f"uncertainty={measurement.uncertainty.magnitude!r}"
        ")"
    )

measurement_str(measurement: Measurement) -> str

Formats the given Measurement as a plaintext string

Source code in src/measured/formatting.py
541
542
543
def measurement_str(measurement: "Measurement") -> str:
    """Formats the given Measurement as a plaintext string"""
    return measurement_format(measurement, "")

prefix_mathml(prefix: Prefix) -> str

Formats the given Prefix as a MathML expression

Source code in src/measured/formatting.py
178
179
180
181
182
183
184
185
186
def prefix_mathml(prefix: "Prefix") -> str:
    """Formats the given Prefix as a MathML expression"""
    if prefix.symbol:
        return f"<mi>{prefix.symbol}</mi>"

    if prefix.exponent == 0:
        return ""

    return f"<msup><mn>{prefix.base}</mn><mn>{prefix.exponent}</mn></msup>"

prefix_pretty(prefix: Prefix, pretty: RepresentationPrinter, cycle: bool) -> None

Formats the given Prefix to the provided pretty printer

Source code in src/measured/formatting.py
165
166
167
168
169
170
171
172
173
174
175
def prefix_pretty(
    prefix: "Prefix", pretty: "RepresentationPrinter", cycle: bool
) -> None:
    """Formats the given Prefix to the provided pretty printer"""
    with pretty.group():
        pretty.text(str(prefix))
        with pretty.group(indent=2):
            pretty.break_()
            pretty.text(f"{prefix.base}{superscript(prefix.exponent)}")
            pretty.break_()
            pretty.text(repr(prefix))

prefix_repr(prefix: Prefix) -> str

Formats the given Prefix as a Python repr

Source code in src/measured/formatting.py
151
152
153
def prefix_repr(prefix: "Prefix") -> str:
    """Formats the given Prefix as a Python `repr`"""
    return f"Prefix(base={prefix.base!r}, exponent={prefix.exponent!r})"

prefix_str(prefix: Prefix) -> str

Formats the given Prefix as a plaintext string

Source code in src/measured/formatting.py
156
157
158
159
160
161
162
def prefix_str(prefix: "Prefix") -> str:
    """Formats the given Prefix as a plaintext string"""
    if prefix.symbol:
        return prefix.symbol
    if prefix.exponent == 0:
        return ""
    return f"{prefix.base}{superscript(prefix.exponent)}"

quantity_format(quantity: Quantity, format_specifier: str) -> str

Formats the given Quantity as a plaintext string, using the provided format specifier to control the output

Source code in src/measured/formatting.py
353
354
355
356
357
358
359
def quantity_format(quantity: "Quantity", format_specifier: str) -> str:
    """Formats the given Quantity as a plaintext string, using the provided format
    specifier to control the output"""
    magnitude_format, _, unit_format = format_specifier.partition(":")
    magnitude = quantity.magnitude.__format__(magnitude_format)
    unit = quantity.unit.__format__(unit_format)
    return f"{magnitude} {unit}"

quantity_mathml(quantity: Quantity) -> str

Formats the given Quantity as a MathML expression

Source code in src/measured/formatting.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def quantity_mathml(quantity: "Quantity") -> str:
    """Formats the given Quantity as a MathML expression"""
    if quantity.unit.symbol:
        return (
            "<mrow>"
            f"<mn>{quantity.magnitude}</mn>"
            "<mo></mo>"
            f"<mi>{quantity.unit.symbol}</mi>"
            "</mrow>"
        )

    unit_magnitude, unit_terms = _unit_to_magnitude_and_terms(quantity.unit)
    quantity = quantity * unit_magnitude
    return (
        "<mrow>"
        f"<mn>{quantity.magnitude}</mn>"
        "<mo></mo>"
        f"{_unit_terms_mathml(1, unit_terms)}"
        "</mrow>"
    )

quantity_pretty(quantity: Quantity, pretty: RepresentationPrinter, cycle: bool) -> None

Formats the given Quantity to the provided pretty printer

Source code in src/measured/formatting.py
362
363
364
365
366
367
368
369
370
371
372
373
374
def quantity_pretty(
    quantity: "Quantity", pretty: "RepresentationPrinter", cycle: bool
) -> None:
    """Formats the given Quantity to the provided pretty printer"""
    with pretty.group():
        pretty.text(f"{quantity::/}")
        with pretty.group(indent=2):
            pretty.break_()
            pretty.pretty(quantity.magnitude)
            pretty.break_()
            pretty.pretty(quantity.unit)
            pretty.break_()
            pretty.text(repr(quantity))

quantity_repr(quantity: Quantity) -> str

Formats the given Quantity as a Python repr

Source code in src/measured/formatting.py
333
334
335
def quantity_repr(quantity: "Quantity") -> str:
    """Formats the given Quantity as a Python `repr`"""
    return f"Quantity(magnitude={quantity.magnitude!r}, unit={quantity.unit!r})"

quantity_str(quantity: Quantity) -> str

Formats the given Quantity as a plaintext string

Source code in src/measured/formatting.py
338
339
340
341
342
343
344
345
346
347
348
349
350
def quantity_str(quantity: "Quantity") -> str:
    """Formats the given Quantity as a plaintext string"""
    if quantity.unit.symbol:
        return f"{quantity.magnitude} {quantity.unit.symbol}"

    unit_magnitude, unit_terms = _unit_to_magnitude_and_terms(quantity.unit)
    quantity = quantity * unit_magnitude
    return f"{quantity.magnitude} " + (
        "⋅".join(
            f"{prefix}{symbol}{superscript(exponent)}"
            for prefix, symbol, exponent in unit_terms
        )
    )

superscript(exponent: Numeric) -> str

Given a signed integer exponent, returns the Unicode superscript string for it

Examples:

>>> f"x{superscript(123)}"
'x¹²³'
>>> f"x{superscript(0)}"
'x⁰'
>>> f"x{superscript(-1)}"
'x⁻¹'
>>> f"x{superscript(1)}"
'x'
Source code in src/measured/formatting.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def superscript(exponent: "Numeric") -> str:
    """Given a signed integer exponent, returns the Unicode superscript string for it

    Examples:

        >>> f"x{superscript(123)}"
        'x¹²³'
        >>> f"x{superscript(0)}"
        'x⁰'
        >>> f"x{superscript(-1)}"
        'x⁻¹'
        >>> f"x{superscript(1)}"
        'x'
    """
    if exponent == 1:
        return ""

    return "".join(SUPERSCRIPTS[c] for c in str(exponent))

unit_format(unit: Unit, format_specifier: str) -> str

Formats the given Unit as a plaintext string, using the provided format specifier to control the output

Source code in src/measured/formatting.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def unit_format(unit: "Unit", format_specifier: str) -> str:
    """Formats the given Unit as a plaintext string, using the provided format
    specifier to control the output"""
    from measured import One

    if not format_specifier:
        return unit_str(unit)

    if format_specifier == "/":
        numerator, denominator = unit.as_ratio()
        if denominator == One:
            return unit_str(unit)
        return str(numerator) + "/" + str(denominator)

    raise ValueError(f"Unrecognized format specifier {format_specifier!r}")

unit_mathml(unit: Unit) -> str

Formats the given Unit as a MathML expression

Source code in src/measured/formatting.py
324
325
326
327
328
329
330
def unit_mathml(unit: "Unit") -> str:
    """Formats the given Unit as a MathML expression"""
    if unit.symbol:
        return f"<mi>{unit.symbol}</mi>"

    magnitude, terms = _unit_to_magnitude_and_terms(unit)
    return _unit_terms_mathml(magnitude, terms)

unit_pretty(unit: Unit, pretty: RepresentationPrinter, cycle: bool) -> None

Formats the given Unit to the provided pretty printer

Source code in src/measured/formatting.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def unit_pretty(unit: "Unit", pretty: "RepresentationPrinter", cycle: bool) -> None:
    """Formats the given Unit to the provided pretty printer"""
    with pretty.group():
        if unit.symbol:
            pretty.text(f"{unit.symbol} ({unit:/})")
        else:
            pretty.text(f"{unit:/}")

        with pretty.group(indent=2):
            pretty.break_()
            if unit.name:
                pretty.text(unit.name)
                pretty.break_()
            pretty.pretty(unit.dimension)
            pretty.break_()
            pretty.text(repr(unit))

unit_repr(unit: Unit) -> str

Formats the given Unit as a Python repr

Source code in src/measured/formatting.py
189
190
191
192
193
194
195
196
197
198
199
200
201
def unit_repr(unit: "Unit") -> str:
    """Formats the given Unit as a Python `repr`"""
    if unit.name:
        return f"Unit.named({unit.name!r})"

    return (
        "Unit("
        f"prefix={unit.prefix!r}, "
        f"factors={unit.factors!r}, "
        f"dimension={unit.dimension!r}, "
        f"name={unit.name!r}, symbol={unit.symbol!r}"
        ")"
    )

unit_str(unit: Unit) -> str

Formats the given Unit as a plaintext string

Source code in src/measured/formatting.py
236
237
238
239
240
241
242
243
244
245
246
247
def unit_str(unit: "Unit") -> str:
    """Formats the given Unit as a plaintext string"""
    if unit.symbol:
        return unit.symbol

    magnitude, terms = _unit_to_magnitude_and_terms(unit)
    return (str(magnitude) + " " if magnitude != 1 else "") + (
        "⋅".join(
            f"{prefix}{symbol}{superscript(exponent)}"
            for prefix, symbol, exponent in terms
        )
    )