You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

base_data_element.py 25 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import copy
  3. from typing import Any, Iterator, Optional, Tuple, Type, Union
  4. import numpy as np
  5. import torch
  6. # Modified from
  7. # https://github.com/open-mmlab/mmengine/blob/main/mmengine/structures/base_data_element.py
  8. class BaseDataElement:
  9. """A base data interface that supports Tensor-like and dict-like
  10. operations.
  11. A typical data elements refer to predicted results or ground truth labels
  12. on a task, such as predicted bboxes, instance masks, semantic
  13. segmentation masks, etc. Because groundtruth labels and predicted results
  14. often have similar properties (for example, the predicted bboxes and the
  15. groundtruth bboxes), MMEngine uses the same abstract data interface to
  16. encapsulate predicted results and groundtruth labels, and it is recommended
  17. to use different name conventions to distinguish them, such as using
  18. ``gt_instances`` and ``pred_instances`` to distinguish between labels and
  19. predicted results. Additionally, we distinguish data elements at instance
  20. level, pixel level, and label level. Each of these types has its own
  21. characteristics. Therefore, MMEngine defines the base class
  22. ``BaseDataElement``, and implement ``InstanceData``, ``PixelData``, and
  23. ``LabelData`` inheriting from ``BaseDataElement`` to represent different
  24. types of ground truth labels or predictions.
  25. Another common data element is data example. A data example consists of input
  26. data (such as an image) and its annotations and predictions. In general,
  27. an image can have multiple types of annotations and/or predictions at the
  28. same time (for example, both pixel-level semantic segmentation annotations
  29. and instance-level detection bboxes annotations). All labels and
  30. predictions of a training example are often passed between Dataset, Model,
  31. Visualizer, and Evaluator components. In order to simplify the interface
  32. between components, we can treat them as a large data element and
  33. encapsulate them. Such data elements are generally called XXDataSample in
  34. the OpenMMLab. Therefore, Similar to `nn.Module`, the `BaseDataElement`
  35. allows `BaseDataElement` as its attribute. Such a class generally
  36. encapsulates all the data of a example in the algorithm library, and its
  37. attributes generally are various types of data elements. For example,
  38. MMDetection is assigned by the BaseDataElement to encapsulate all the data
  39. elements of the example labeling and prediction of a example in the
  40. algorithm library.
  41. The attributes in ``BaseDataElement`` are divided into two parts,
  42. the ``metainfo`` and the ``data`` respectively.
  43. - ``metainfo``: Usually contains the
  44. information about the image such as filename,
  45. image_shape, pad_shape, etc. The attributes can be accessed or
  46. modified by dict-like or object-like operations, such as
  47. ``.`` (for data access and modification), ``in``, ``del``,
  48. ``pop(str)``, ``get(str)``, ``metainfo_keys()``,
  49. ``metainfo_values()``, ``metainfo_items()``, ``set_metainfo()`` (for
  50. set or change key-value pairs in metainfo).
  51. - ``data``: Annotations or model predictions are
  52. stored. The attributes can be accessed or modified by
  53. dict-like or object-like operations, such as
  54. ``.``, ``in``, ``del``, ``pop(str)``, ``get(str)``, ``keys()``,
  55. ``values()``, ``items()``. Users can also apply tensor-like
  56. methods to all :obj:`torch.Tensor` in the ``data_fields``,
  57. such as ``.cuda()``, ``.cpu()``, ``.numpy()``, ``.to()``,
  58. ``to_tensor()``, ``.detach()``.
  59. Args:
  60. metainfo (dict, optional): A dict contains the meta information
  61. of single image, such as ``dict(img_shape=(512, 512, 3),
  62. scale_factor=(1, 1, 1, 1))``. Defaults to None.
  63. kwargs (dict, optional): A dict contains annotations of single image or
  64. model predictions. Defaults to None.
  65. Examples:
  66. >>> import torch
  67. >>> from mmengine.structures import BaseDataElement
  68. >>> gt_instances = BaseDataElement()
  69. >>> bboxes = torch.rand((5, 4))
  70. >>> scores = torch.rand((5,))
  71. >>> img_id = 0
  72. >>> img_shape = (800, 1333)
  73. >>> gt_instances = BaseDataElement(
  74. ... metainfo=dict(img_id=img_id, img_shape=img_shape),
  75. ... bboxes=bboxes, scores=scores)
  76. >>> gt_instances = BaseDataElement(
  77. ... metainfo=dict(img_id=img_id, img_shape=(640, 640)))
  78. >>> # new
  79. >>> gt_instances1 = gt_instances.new(
  80. ... metainfo=dict(img_id=1, img_shape=(640, 640)),
  81. ... bboxes=torch.rand((5, 4)),
  82. ... scores=torch.rand((5,)))
  83. >>> gt_instances2 = gt_instances1.new()
  84. >>> # add and process property
  85. >>> gt_instances = BaseDataElement()
  86. >>> gt_instances.set_metainfo(dict(img_id=9, img_shape=(100, 100)))
  87. >>> assert 'img_shape' in gt_instances.metainfo_keys()
  88. >>> assert 'img_shape' in gt_instances
  89. >>> assert 'img_shape' not in gt_instances.keys()
  90. >>> assert 'img_shape' in gt_instances.all_keys()
  91. >>> print(gt_instances.img_shape)
  92. (100, 100)
  93. >>> gt_instances.scores = torch.rand((5,))
  94. >>> assert 'scores' in gt_instances.keys()
  95. >>> assert 'scores' in gt_instances
  96. >>> assert 'scores' in gt_instances.all_keys()
  97. >>> assert 'scores' not in gt_instances.metainfo_keys()
  98. >>> print(gt_instances.scores)
  99. tensor([0.5230, 0.7885, 0.2426, 0.3911, 0.4876])
  100. >>> gt_instances.bboxes = torch.rand((5, 4))
  101. >>> assert 'bboxes' in gt_instances.keys()
  102. >>> assert 'bboxes' in gt_instances
  103. >>> assert 'bboxes' in gt_instances.all_keys()
  104. >>> assert 'bboxes' not in gt_instances.metainfo_keys()
  105. >>> print(gt_instances.bboxes)
  106. tensor([[0.0900, 0.0424, 0.1755, 0.4469],
  107. [0.8648, 0.0592, 0.3484, 0.0913],
  108. [0.5808, 0.1909, 0.6165, 0.7088],
  109. [0.5490, 0.4209, 0.9416, 0.2374],
  110. [0.3652, 0.1218, 0.8805, 0.7523]])
  111. >>> # delete and change property
  112. >>> gt_instances = BaseDataElement(
  113. ... metainfo=dict(img_id=0, img_shape=(640, 640)),
  114. ... bboxes=torch.rand((6, 4)), scores=torch.rand((6,)))
  115. >>> gt_instances.set_metainfo(dict(img_shape=(1280, 1280)))
  116. >>> gt_instances.img_shape # (1280, 1280)
  117. >>> gt_instances.bboxes = gt_instances.bboxes * 2
  118. >>> gt_instances.get('img_shape', None) # (1280, 1280)
  119. >>> gt_instances.get('bboxes', None) # 6x4 tensor
  120. >>> del gt_instances.img_shape
  121. >>> del gt_instances.bboxes
  122. >>> assert 'img_shape' not in gt_instances
  123. >>> assert 'bboxes' not in gt_instances
  124. >>> gt_instances.pop('img_shape', None) # None
  125. >>> gt_instances.pop('bboxes', None) # None
  126. >>> # Tensor-like
  127. >>> cuda_instances = gt_instances.cuda()
  128. >>> cuda_instances = gt_instances.to('cuda:0')
  129. >>> cpu_instances = cuda_instances.cpu()
  130. >>> cpu_instances = cuda_instances.to('cpu')
  131. >>> fp16_instances = cuda_instances.to(
  132. ... device=None, dtype=torch.float16, non_blocking=False,
  133. ... copy=False, memory_format=torch.preserve_format)
  134. >>> cpu_instances = cuda_instances.detach()
  135. >>> np_instances = cpu_instances.numpy()
  136. >>> # print
  137. >>> metainfo = dict(img_shape=(800, 1196, 3))
  138. >>> gt_instances = BaseDataElement(
  139. ... metainfo=metainfo, det_labels=torch.LongTensor([0, 1, 2, 3]))
  140. >>> example = BaseDataElement(metainfo=metainfo,
  141. ... gt_instances=gt_instances)
  142. >>> print(example)
  143. <BaseDataElement(
  144. META INFORMATION
  145. img_shape: (800, 1196, 3)
  146. DATA FIELDS
  147. gt_instances: <BaseDataElement(
  148. META INFORMATION
  149. img_shape: (800, 1196, 3)
  150. DATA FIELDS
  151. det_labels: tensor([0, 1, 2, 3])
  152. ) at 0x7f0ec5eadc70>
  153. ) at 0x7f0fea49e130>
  154. >>> # inheritance
  155. >>> class DetDataSample(BaseDataElement):
  156. ... @property
  157. ... def proposals(self):
  158. ... return self._proposals
  159. ... @proposals.setter
  160. ... def proposals(self, value):
  161. ... self.set_field(value, '_proposals', dtype=BaseDataElement)
  162. ... @proposals.deleter
  163. ... def proposals(self):
  164. ... del self._proposals
  165. ... @property
  166. ... def gt_instances(self):
  167. ... return self._gt_instances
  168. ... @gt_instances.setter
  169. ... def gt_instances(self, value):
  170. ... self.set_field(value, '_gt_instances',
  171. ... dtype=BaseDataElement)
  172. ... @gt_instances.deleter
  173. ... def gt_instances(self):
  174. ... del self._gt_instances
  175. ... @property
  176. ... def pred_instances(self):
  177. ... return self._pred_instances
  178. ... @pred_instances.setter
  179. ... def pred_instances(self, value):
  180. ... self.set_field(value, '_pred_instances',
  181. ... dtype=BaseDataElement)
  182. ... @pred_instances.deleter
  183. ... def pred_instances(self):
  184. ... del self._pred_instances
  185. >>> det_example = DetDataSample()
  186. >>> proposals = BaseDataElement(bboxes=torch.rand((5, 4)))
  187. >>> det_example.proposals = proposals
  188. >>> assert 'proposals' in det_example
  189. >>> assert det_example.proposals == proposals
  190. >>> del det_example.proposals
  191. >>> assert 'proposals' not in det_example
  192. >>> with self.assertRaises(AssertionError):
  193. ... det_example.proposals = torch.rand((5, 4))
  194. """
  195. def __init__(self, *, metainfo: Optional[dict] = None, **kwargs) -> None:
  196. self._metainfo_fields: set = set()
  197. self._data_fields: set = set()
  198. if metainfo is not None:
  199. self.set_metainfo(metainfo=metainfo)
  200. if kwargs:
  201. self.set_data(kwargs)
  202. def set_metainfo(self, metainfo: dict) -> None:
  203. """Set or change key-value pairs in ``metainfo_field`` by parameter
  204. ``metainfo``.
  205. Args:
  206. metainfo (dict): A dict contains the meta information
  207. of image, such as ``img_shape``, ``scale_factor``, etc.
  208. """
  209. assert isinstance(metainfo, dict), f"metainfo should be a ``dict`` but got {type(metainfo)}"
  210. meta = copy.deepcopy(metainfo)
  211. for k, v in meta.items():
  212. self.set_field(name=k, value=v, field_type="metainfo", dtype=None)
  213. def set_data(self, data: dict) -> None:
  214. """Set or change key-value pairs in ``data_field`` by parameter
  215. ``data``.
  216. Args:
  217. data (dict): A dict contains annotations of image or
  218. model predictions.
  219. """
  220. assert isinstance(data, dict), f"data should be a `dict` but got {data}"
  221. for k, v in data.items():
  222. # Use `setattr()` rather than `self.set_field` to allow `set_data`
  223. # to set property method.
  224. setattr(self, k, v)
  225. def update(self, instance: "BaseDataElement") -> None:
  226. """The update() method updates the BaseDataElement with the elements
  227. from another BaseDataElement object.
  228. Args:
  229. instance (BaseDataElement): Another BaseDataElement object for
  230. update the current object.
  231. """
  232. assert isinstance(
  233. instance, BaseDataElement
  234. ), f"instance should be a `BaseDataElement` but got {type(instance)}"
  235. self.set_metainfo(dict(instance.metainfo_items()))
  236. self.set_data(dict(instance.items()))
  237. def new(self, *, metainfo: Optional[dict] = None, **kwargs) -> "BaseDataElement":
  238. """Return a new data element with same type. If ``metainfo`` and
  239. ``data`` are None, the new data element will have same metainfo and
  240. data. If metainfo or data is not None, the new result will overwrite it
  241. with the input value.
  242. Args:
  243. metainfo (dict, optional): A dict contains the meta information
  244. of image, such as ``img_shape``, ``scale_factor``, etc.
  245. Defaults to None.
  246. kwargs (dict): A dict contains annotations of image or
  247. model predictions.
  248. Returns:
  249. BaseDataElement: A new data element with same type.
  250. """
  251. new_data = self.__class__()
  252. if metainfo is not None:
  253. new_data.set_metainfo(metainfo)
  254. else:
  255. new_data.set_metainfo(dict(self.metainfo_items()))
  256. if kwargs:
  257. new_data.set_data(kwargs)
  258. else:
  259. new_data.set_data(dict(self.items()))
  260. return new_data
  261. def clone(self):
  262. """Deep copy the current data element.
  263. Returns:
  264. BaseDataElement: The copy of current data element.
  265. """
  266. clone_data = self.__class__()
  267. clone_data.set_metainfo(dict(self.metainfo_items()))
  268. clone_data.set_data(dict(self.items()))
  269. return clone_data
  270. def keys(self) -> list:
  271. """
  272. Returns:
  273. list: Contains all keys in data_fields.
  274. """
  275. # We assume that the name of the attribute related to property is
  276. # '_' + the name of the property. We use this rule to filter out
  277. # private keys.
  278. # TODO: Use a more robust way to solve this problem
  279. private_keys = {
  280. "_" + key
  281. for key in self._data_fields
  282. if isinstance(getattr(type(self), key, None), property)
  283. }
  284. return list(self._data_fields - private_keys)
  285. def metainfo_keys(self) -> list:
  286. """
  287. Returns:
  288. list: Contains all keys in metainfo_fields.
  289. """
  290. return list(self._metainfo_fields)
  291. def values(self) -> list:
  292. """
  293. Returns:
  294. list: Contains all values in data.
  295. """
  296. return [getattr(self, k) for k in self.keys()]
  297. def metainfo_values(self) -> list:
  298. """
  299. Returns:
  300. list: Contains all values in metainfo.
  301. """
  302. return [getattr(self, k) for k in self.metainfo_keys()]
  303. def all_keys(self) -> list:
  304. """
  305. Returns:
  306. list: Contains all keys in metainfo and data.
  307. """
  308. return self.metainfo_keys() + self.keys()
  309. def all_values(self) -> list:
  310. """
  311. Returns:
  312. list: Contains all values in metainfo and data.
  313. """
  314. return self.metainfo_values() + self.values()
  315. def all_items(self) -> Iterator[Tuple[str, Any]]:
  316. """
  317. Returns:
  318. iterator: An iterator object whose element is (key, value) tuple
  319. pairs for ``metainfo`` and ``data``.
  320. """
  321. for k in self.all_keys():
  322. yield (k, getattr(self, k))
  323. def items(self) -> Iterator[Tuple[str, Any]]:
  324. """
  325. Returns:
  326. iterator: An iterator object whose element is (key, value) tuple
  327. pairs for ``data``.
  328. """
  329. for k in self.keys():
  330. yield (k, getattr(self, k))
  331. def metainfo_items(self) -> Iterator[Tuple[str, Any]]:
  332. """
  333. Returns:
  334. iterator: An iterator object whose element is (key, value) tuple
  335. pairs for ``metainfo``.
  336. """
  337. for k in self.metainfo_keys():
  338. yield (k, getattr(self, k))
  339. @property
  340. def metainfo(self) -> dict:
  341. """dict: A dict contains metainfo of current data element."""
  342. return dict(self.metainfo_items())
  343. def __setattr__(self, name: str, value: Any):
  344. """setattr is only used to set data."""
  345. if name in ("_metainfo_fields", "_data_fields"):
  346. if not hasattr(self, name):
  347. super().__setattr__(name, value)
  348. else:
  349. raise AttributeError(
  350. f"{name} has been used as a " "private attribute, which is immutable."
  351. )
  352. else:
  353. self.set_field(name=name, value=value, field_type="data", dtype=None)
  354. def __delattr__(self, item: str):
  355. """Delete the item in dataelement.
  356. Args:
  357. item (str): The key to delete.
  358. """
  359. if item in ("_metainfo_fields", "_data_fields"):
  360. raise AttributeError(
  361. f"{item} has been used as a " "private attribute, which is immutable."
  362. )
  363. super().__delattr__(item)
  364. if item in self._metainfo_fields:
  365. self._metainfo_fields.remove(item)
  366. elif item in self._data_fields:
  367. self._data_fields.remove(item)
  368. # dict-like methods
  369. __delitem__ = __delattr__
  370. def get(self, key, default=None) -> Any:
  371. """Get property in data and metainfo as the same as python."""
  372. # Use `getattr()` rather than `self.__dict__.get()` to allow getting
  373. # properties.
  374. return getattr(self, key, default)
  375. def pop(self, *args) -> Any:
  376. """Pop property in data and metainfo as the same as python."""
  377. assert len(args) < 3, "``pop`` get more than 2 arguments"
  378. name = args[0]
  379. if name in self._metainfo_fields:
  380. self._metainfo_fields.remove(args[0])
  381. return self.__dict__.pop(*args)
  382. elif name in self._data_fields:
  383. self._data_fields.remove(args[0])
  384. return self.__dict__.pop(*args)
  385. # with default value
  386. elif len(args) == 2:
  387. return args[1]
  388. else:
  389. # don't just use 'self.__dict__.pop(*args)' for only popping key in
  390. # metainfo or data
  391. raise KeyError(f"{args[0]} is not contained in metainfo or data")
  392. def __contains__(self, item: str) -> bool:
  393. """Whether the item is in dataelement.
  394. Args:
  395. item (str): The key to inquire.
  396. """
  397. return item in self._data_fields or item in self._metainfo_fields
  398. def set_field(
  399. self,
  400. value: Any,
  401. name: str,
  402. dtype: Optional[Union[Type, Tuple[Type, ...]]] = None,
  403. field_type: str = "data",
  404. ) -> None:
  405. """Special method for set union field, used as property.setter
  406. functions."""
  407. assert field_type in ["metainfo", "data"]
  408. if dtype is not None:
  409. assert isinstance(value, dtype), f"{value} should be a {dtype} but got {type(value)}"
  410. if field_type == "metainfo":
  411. if name in self._data_fields:
  412. raise AttributeError(
  413. f"Cannot set {name} to be a field of metainfo "
  414. f"because {name} is already a data field"
  415. )
  416. self._metainfo_fields.add(name)
  417. else:
  418. if name in self._metainfo_fields:
  419. raise AttributeError(
  420. f"Cannot set {name} to be a field of data "
  421. f"because {name} is already a metainfo field"
  422. )
  423. self._data_fields.add(name)
  424. super().__setattr__(name, value)
  425. # Tensor-like methods
  426. def to(self, *args, **kwargs) -> "BaseDataElement":
  427. """Apply same name function to all tensors in data_fields."""
  428. new_data = self.new()
  429. for k, v in self.items():
  430. if hasattr(v, "to"):
  431. v = v.to(*args, **kwargs)
  432. data = {k: v}
  433. new_data.set_data(data)
  434. return new_data
  435. # Tensor-like methods
  436. def cpu(self) -> "BaseDataElement":
  437. """Convert all tensors to CPU in data."""
  438. new_data = self.new()
  439. for k, v in self.items():
  440. if isinstance(v, (torch.Tensor, BaseDataElement)):
  441. v = v.cpu()
  442. data = {k: v}
  443. new_data.set_data(data)
  444. return new_data
  445. # Tensor-like methods
  446. def cuda(self) -> "BaseDataElement":
  447. """Convert all tensors to GPU in data."""
  448. new_data = self.new()
  449. for k, v in self.items():
  450. if isinstance(v, (torch.Tensor, BaseDataElement)):
  451. v = v.cuda()
  452. data = {k: v}
  453. new_data.set_data(data)
  454. return new_data
  455. # Tensor-like methods
  456. def npu(self) -> "BaseDataElement":
  457. """Convert all tensors to NPU in data."""
  458. new_data = self.new()
  459. for k, v in self.items():
  460. if isinstance(v, (torch.Tensor, BaseDataElement)):
  461. v = v.npu()
  462. data = {k: v}
  463. new_data.set_data(data)
  464. return new_data
  465. def mlu(self) -> "BaseDataElement":
  466. """Convert all tensors to MLU in data."""
  467. new_data = self.new()
  468. for k, v in self.items():
  469. if isinstance(v, (torch.Tensor, BaseDataElement)):
  470. v = v.mlu()
  471. data = {k: v}
  472. new_data.set_data(data)
  473. return new_data
  474. # Tensor-like methods
  475. def detach(self) -> "BaseDataElement":
  476. """Detach all tensors in data."""
  477. new_data = self.new()
  478. for k, v in self.items():
  479. if isinstance(v, (torch.Tensor, BaseDataElement)):
  480. v = v.detach()
  481. data = {k: v}
  482. new_data.set_data(data)
  483. return new_data
  484. # Tensor-like methods
  485. def numpy(self) -> "BaseDataElement":
  486. """Convert all tensors to np.ndarray in data."""
  487. new_data = self.new()
  488. for k, v in self.items():
  489. if isinstance(v, (torch.Tensor, BaseDataElement)):
  490. v = v.detach().cpu().numpy()
  491. data = {k: v}
  492. new_data.set_data(data)
  493. return new_data
  494. def to_tensor(self) -> "BaseDataElement":
  495. """Convert all np.ndarray to tensor in data."""
  496. new_data = self.new()
  497. for k, v in self.items():
  498. data = {}
  499. if isinstance(v, np.ndarray):
  500. v = torch.from_numpy(v)
  501. data[k] = v
  502. elif isinstance(v, BaseDataElement):
  503. v = v.to_tensor()
  504. data[k] = v
  505. new_data.set_data(data)
  506. return new_data
  507. def to_dict(self) -> dict:
  508. """Convert BaseDataElement to dict."""
  509. return {
  510. k: v.to_dict() if isinstance(v, BaseDataElement) else v for k, v in self.all_items()
  511. }
  512. def __repr__(self) -> str:
  513. """Represent the object."""
  514. def _addindent(s_: str, num_spaces: int) -> str:
  515. """This func is modified from `pytorch` https://github.com/pytorch/
  516. pytorch/blob/b17b2b1cc7b017c3daaeff8cc7ec0f514d42ec37/torch/nn/modu
  517. les/module.py#L29.
  518. Args:
  519. s_ (str): The string to add spaces.
  520. num_spaces (int): The num of space to add.
  521. Returns:
  522. str: The string after add indent.
  523. """
  524. s = s_.split("\n")
  525. # don't do anything for single-line stuff
  526. if len(s) == 1:
  527. return s_
  528. first = s.pop(0)
  529. s = [(num_spaces * " ") + line for line in s]
  530. s = "\n".join(s) # type: ignore
  531. s = first + "\n" + s # type: ignore
  532. return s # type: ignore
  533. def dump(obj: Any) -> str:
  534. """Represent the object.
  535. Args:
  536. obj (Any): The obj to represent.
  537. Returns:
  538. str: The represented str.
  539. """
  540. _repr = ""
  541. if isinstance(obj, dict):
  542. for k, v in obj.items():
  543. _repr += f"\n{k}: {_addindent(dump(v), 4)}"
  544. elif isinstance(obj, BaseDataElement):
  545. _repr += "\n\n META INFORMATION"
  546. metainfo_items = dict(obj.metainfo_items())
  547. _repr += _addindent(dump(metainfo_items), 4)
  548. _repr += "\n\n DATA FIELDS"
  549. items = dict(obj.items())
  550. _repr += _addindent(dump(items), 4)
  551. classname = obj.__class__.__name__
  552. _repr = f"<{classname}({_repr}\n) at {hex(id(obj))}>"
  553. else:
  554. _repr += repr(obj)
  555. return _repr
  556. return dump(self)

An efficient Python toolkit for Abductive Learning (ABL), a novel paradigm that integrates machine learning and logical reasoning in a unified framework.