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 24 kB

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