File: integer.py

package info (click to toggle)
python-asdf 4.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 7,032 kB
  • sloc: python: 24,068; makefile: 123
file content (44 lines) | stat: -rw-r--r-- 1,095 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import numpy as np

from asdf.extension import Converter


class IntegerConverter(Converter):
    tags = [
        "tag:stsci.edu:asdf/core/integer-1.0.0",
        "tag:stsci.edu:asdf/core/integer-1.1.0",
    ]
    types = ["asdf.tags.core.integer.IntegerType"]

    def to_yaml_tree(self, obj, tag, ctx):
        abs_value = int(np.abs(obj._value))

        # pack integer value into 32-bit words
        words = []
        value = abs_value
        while value > 0:
            words.append(value & 0xFFFFFFFF)
            value >>= 32

        array = np.array(words, dtype=np.uint32)

        tree = {}
        ctx.set_array_storage(array, obj._storage)
        tree["words"] = array
        tree["sign"] = obj._sign
        tree["string"] = str(int(obj._value))

        return tree

    def from_yaml_tree(self, node, tag, ctx):
        from asdf.tags.core.integer import IntegerType

        value = 0
        for x in node["words"][::-1]:
            value <<= 32
            value |= int(x)

        if node["sign"] == "-":
            value = -value

        return IntegerType(value)