|
| 1 | +from typing import Any, Dict, List, Optional, Union |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +from ciftools.binary.decoder import decode_cif_data |
| 5 | +from ciftools.binary.encoded_data import EncodedCIFCategory, EncodedCIFColumn, EncodedCIFFile |
| 6 | +from ciftools.models.data import CIFCategory, CIFColumn, CIFDataBlock, CIFFile, CIFValuePresenceEnum |
| 7 | + |
| 8 | + |
| 9 | +class BinaryCIFColumn(CIFColumn): |
| 10 | + def __init__( |
| 11 | + self, |
| 12 | + name: str, |
| 13 | + values: np.ndarray, |
| 14 | + value_presence: Optional[np.ndarray], |
| 15 | + ): |
| 16 | + self.name = name |
| 17 | + self._values = values |
| 18 | + self._value_presence = value_presence |
| 19 | + self._row_count = len(values) |
| 20 | + |
| 21 | + def get_string(self, row: int) -> str: |
| 22 | + return str(self._values[row]) |
| 23 | + |
| 24 | + def get_integer(self, row: int) -> int: |
| 25 | + return int(self._values[row]) |
| 26 | + |
| 27 | + def get_float(self, row: int) -> float: |
| 28 | + return float(self._values[row]) |
| 29 | + |
| 30 | + def get_value_presence(self, row: int) -> CIFValuePresenceEnum: |
| 31 | + if self._value_presence: |
| 32 | + return self._value_presence[row] |
| 33 | + return 0 # type: ignore |
| 34 | + |
| 35 | + def are_values_equal(self, row_a: int, row_b: int) -> bool: |
| 36 | + return self._values[row_a] == self._values[row_b] |
| 37 | + |
| 38 | + def string_equals(self, row: int, value: str) -> bool: |
| 39 | + return str(self._values[row]) == value |
| 40 | + |
| 41 | + def as_ndarray( |
| 42 | + self, *, dtype: Optional[Union[np.dtype, str]] = None, start: Optional[int] = None, end: Optional[int] = None |
| 43 | + ) -> np.ndarray: |
| 44 | + if dtype is None and start is None and end is None: |
| 45 | + return self._values |
| 46 | + if dtype is None: |
| 47 | + return self._values[start:end] |
| 48 | + return self._values[start:end].astype(dtype) |
| 49 | + |
| 50 | + def __getitem__(self, idx: Any) -> Any: |
| 51 | + if isinstance(idx, int) and self._value_presence and self._value_presence[idx]: |
| 52 | + return None |
| 53 | + return self._values[idx] |
| 54 | + |
| 55 | + def __len__(self): |
| 56 | + return self._row_count |
| 57 | + |
| 58 | + @property |
| 59 | + def value_presences(self) -> Optional[np.ndarray]: |
| 60 | + return self._value_presence |
| 61 | + |
| 62 | + |
| 63 | +def _decode_cif_column(column: EncodedCIFColumn) -> CIFColumn: |
| 64 | + values = decode_cif_data(column["data"]) |
| 65 | + value_mask = decode_cif_data(column["mask"]) if column["mask"] else None |
| 66 | + return BinaryCIFColumn(column["name"], values, value_mask) |
| 67 | + |
| 68 | + |
| 69 | +class BinaryCIFCategory(CIFCategory): |
| 70 | + def __getitem__(self, name: str) -> BinaryCIFColumn: |
| 71 | + if name not in self._field_cache: |
| 72 | + raise ValueError(f"{name} is not a valid category name") |
| 73 | + |
| 74 | + if not self._field_cache[name]: |
| 75 | + self._field_cache[name] = _decode_cif_column(self._columns[name]) |
| 76 | + |
| 77 | + return self._field_cache[name] # type: ignore |
| 78 | + |
| 79 | + def __contains__(self, key: str): |
| 80 | + return key in self._columns |
| 81 | + |
| 82 | + def __init__(self, category: EncodedCIFCategory, lazy: bool): |
| 83 | + self._field_names = [c["name"] for c in category["columns"]] |
| 84 | + self._field_cache = {c["name"]: None if lazy else _decode_cif_column(c) for c in category["columns"]} |
| 85 | + self._columns: dict[str, EncodedCIFColumn] = {c["name"]: c for c in category["columns"]} |
| 86 | + self._n_columns = len(category["columns"]) |
| 87 | + self._n_rows = category["rowCount"] |
| 88 | + self._name = category["name"][1:] |
| 89 | + |
| 90 | + @property |
| 91 | + def name(self) -> str: |
| 92 | + return self._name |
| 93 | + |
| 94 | + @property |
| 95 | + def n_rows(self) -> int: |
| 96 | + return self._n_rows |
| 97 | + |
| 98 | + @property |
| 99 | + def n_columns(self) -> int: |
| 100 | + return self._n_columns |
| 101 | + |
| 102 | + @property |
| 103 | + def field_names(self) -> List[str]: |
| 104 | + return self._field_names |
| 105 | + |
| 106 | + |
| 107 | +class BinaryCIFDataBlock(CIFDataBlock): |
| 108 | + def __getitem__(self, name: str) -> CIFCategory: |
| 109 | + return self._categories[name] |
| 110 | + |
| 111 | + def __contains__(self, key: str): |
| 112 | + return key in self._categories |
| 113 | + |
| 114 | + def __init__(self, header: str, categories: Dict[str, BinaryCIFCategory]): |
| 115 | + self._header = header |
| 116 | + self._categories = categories |
| 117 | + |
| 118 | + @property |
| 119 | + def header(self) -> str: |
| 120 | + return self._header |
| 121 | + |
| 122 | + @property |
| 123 | + def categories(self) -> Dict[str, CIFCategory]: |
| 124 | + return self._categories # type: ignore |
| 125 | + |
| 126 | + |
| 127 | +class BinaryCIFFile(CIFFile): |
| 128 | + def __getitem__(self, index_or_name: Union[int, str]): |
| 129 | + if isinstance(index_or_name, str): |
| 130 | + return self._block_map.get(index_or_name) |
| 131 | + else: |
| 132 | + return ( |
| 133 | + self.data_blocks[index_or_name] |
| 134 | + if index_or_name < len(self.data_blocks) and index_or_name >= 0 |
| 135 | + else None |
| 136 | + ) |
| 137 | + |
| 138 | + def __len__(self): |
| 139 | + return len(self._data_blocks) |
| 140 | + |
| 141 | + def __contains__(self, key: str): |
| 142 | + return key in self._block_map |
| 143 | + |
| 144 | + def __init__(self, data_blocks: List[BinaryCIFDataBlock]): |
| 145 | + self._data_blocks = data_blocks |
| 146 | + self._block_map: dict[str, CIFDataBlock] = {b.header: b for b in data_blocks} |
| 147 | + |
| 148 | + @staticmethod |
| 149 | + def from_data(data: EncodedCIFFile, *, lazy=True) -> "BinaryCIFFile": |
| 150 | + """ |
| 151 | + - lazy: |
| 152 | + - True: individual columns are decoded only when accessed |
| 153 | + - False: decode all columns immediately |
| 154 | + """ |
| 155 | + |
| 156 | + min_version = (0, 3, 0) |
| 157 | + version = tuple(map(int, data["version"].split("."))) |
| 158 | + if version < min_version: |
| 159 | + raise ValueError(f"Invalid version {data['version']}, expected >={'.'.join(map(str, min_version))}") |
| 160 | + |
| 161 | + data_blocks = [ |
| 162 | + BinaryCIFDataBlock( |
| 163 | + block["header"], |
| 164 | + {category["name"][1:]: BinaryCIFCategory(category, lazy) for category in block["categories"]}, |
| 165 | + ) |
| 166 | + for block in data["dataBlocks"] |
| 167 | + ] |
| 168 | + |
| 169 | + return BinaryCIFFile(data_blocks) |
| 170 | + |
| 171 | + @property |
| 172 | + def data_blocks(self) -> List[CIFDataBlock]: |
| 173 | + return self._data_blocks # type: ignore |
0 commit comments