|
| 1 | +import json |
| 2 | +from typing import Any, Callable, Dict, List, Optional, Tuple, Union |
| 3 | + |
| 4 | +from mat3ra.utils.mixins import RoundNumericValuesMixin |
| 5 | +from pydantic import BaseModel, model_serializer |
| 6 | + |
| 7 | +from .value_with_id import RoundedValueWithId, ValueWithId |
| 8 | + |
| 9 | + |
| 10 | +class ArrayWithIds(BaseModel): |
| 11 | + values: List[Any] |
| 12 | + ids: List[int] |
| 13 | + |
| 14 | + @classmethod |
| 15 | + def from_values(cls, values: List[Any]) -> "ArrayWithIds": |
| 16 | + try: |
| 17 | + ids = list(range(len(values))) |
| 18 | + return cls(values=values, ids=ids) |
| 19 | + except KeyError: |
| 20 | + raise ValueError("Values must be a list") |
| 21 | + |
| 22 | + @classmethod |
| 23 | + def get_values_and_ids_from_list_of_dicts(cls, list_of_dicts: List[Dict[str, Any]]) -> Tuple[List[Any], List[int]]: |
| 24 | + try: |
| 25 | + values = [item["value"] for item in list_of_dicts] |
| 26 | + ids = [item["id"] for item in list_of_dicts] |
| 27 | + return values, ids |
| 28 | + except KeyError: |
| 29 | + raise ValueError("List of dictionaries must contain 'id' and 'value' keys") |
| 30 | + |
| 31 | + @classmethod |
| 32 | + def from_list_of_dicts(cls, list_of_dicts: List[Dict[str, Any]]) -> "ArrayWithIds": |
| 33 | + try: |
| 34 | + values, ids = cls.get_values_and_ids_from_list_of_dicts(list_of_dicts) |
| 35 | + return cls(values=values, ids=ids) |
| 36 | + except KeyError: |
| 37 | + raise ValueError("List of dictionaries must contain 'id' and 'value' keys") |
| 38 | + |
| 39 | + @model_serializer |
| 40 | + def to_dict(self) -> List[Dict[str, Any]]: |
| 41 | + return list(map(lambda x: x.to_dict(), self.to_array_of_values_with_ids())) |
| 42 | + |
| 43 | + def to_json(self, skip_rounding=True) -> str: |
| 44 | + return json.dumps(self.to_dict()) |
| 45 | + |
| 46 | + def to_array_of_values_with_ids(self) -> List[ValueWithId]: |
| 47 | + return [ValueWithId(id=id, value=item) for id, item in zip(self.ids, self.values)] |
| 48 | + |
| 49 | + def get_element_value_by_index(self, index: int) -> Any: |
| 50 | + return self.values[index] if index < len(self.values) else None |
| 51 | + |
| 52 | + def get_element_id_by_value(self, value: Any) -> Optional[int]: |
| 53 | + try: |
| 54 | + return self.ids[self.values.index(value)] |
| 55 | + except ValueError: |
| 56 | + return None |
| 57 | + |
| 58 | + def filter_by_values(self, values: Union[List[Any], Any]): |
| 59 | + def make_hashable(value): |
| 60 | + return tuple(value) if isinstance(value, list) else value |
| 61 | + |
| 62 | + values_to_keep = set(make_hashable(v) for v in values) if isinstance(values, list) else {make_hashable(values)} |
| 63 | + filtered_items = [(v, i) for v, i in zip(self.values, self.ids) if make_hashable(v) in values_to_keep] |
| 64 | + if filtered_items: |
| 65 | + values_unpacked, ids_unpacked = zip(*filtered_items) |
| 66 | + self.values = list(values_unpacked) |
| 67 | + self.ids = list(ids_unpacked) |
| 68 | + else: |
| 69 | + self.values = [] |
| 70 | + self.ids = [] |
| 71 | + |
| 72 | + def filter_by_indices(self, indices: Union[List[int], int]): |
| 73 | + index_set = set(indices) if isinstance(indices, list) else {indices} |
| 74 | + self.values = [self.values[i] for i in range(len(self.values)) if i in index_set] |
| 75 | + self.ids = [self.ids[i] for i in range(len(self.ids)) if i in index_set] |
| 76 | + |
| 77 | + def filter_by_ids(self, ids: Union[List[int], int], invert: bool = False): |
| 78 | + if isinstance(ids, int): |
| 79 | + ids = [ids] |
| 80 | + if not invert: |
| 81 | + ids_set = set(ids) |
| 82 | + else: |
| 83 | + ids_set = set(self.ids) - set(ids) |
| 84 | + keep_indices = [index for index, id_ in enumerate(self.ids) if id_ in ids_set] |
| 85 | + self.values = [self.values[index] for index in keep_indices] |
| 86 | + self.ids = [self.ids[index] for index in keep_indices] |
| 87 | + |
| 88 | + def __eq__(self, other: object) -> bool: |
| 89 | + return isinstance(other, ArrayWithIds) and self.values == other.values and self.ids == other.ids |
| 90 | + |
| 91 | + def map_array_in_place(self, func: Callable): |
| 92 | + self.values = list(map(func, self.values)) |
| 93 | + |
| 94 | + def add_item(self, element: Any, id: Optional[int] = None): |
| 95 | + if id is None: |
| 96 | + new_id = max(self.ids, default=-1) + 1 |
| 97 | + else: |
| 98 | + new_id = id |
| 99 | + self.values.append(element) |
| 100 | + self.ids.append(new_id) |
| 101 | + |
| 102 | + def remove_item(self, index: int, id: Optional[int] = None): |
| 103 | + if id is not None: |
| 104 | + try: |
| 105 | + index = self.ids.index(id) |
| 106 | + except ValueError: |
| 107 | + raise ValueError("ID not found in the list") |
| 108 | + if index < len(self.values): |
| 109 | + del self.values[index] |
| 110 | + del self.ids[index] |
| 111 | + else: |
| 112 | + raise IndexError("Index out of range") |
| 113 | + |
| 114 | + |
| 115 | +class RoundedArrayWithIds(RoundNumericValuesMixin, ArrayWithIds): |
| 116 | + def to_array_of_values_with_ids(self) -> List[ValueWithId]: |
| 117 | + class_reference = RoundedValueWithId |
| 118 | + class_reference.__round_precision__ = self.__round_precision__ |
| 119 | + return [class_reference(id=id, value=item) for id, item in zip(self.ids, self.values)] |
0 commit comments