IF YOU WOULD LIKE TO GET AN ACCOUNT, please write an email to s dot adaszewski at gmail dot com. User accounts are meant only to report issues and/or generate pull requests. This is a purpose-specific Git hosting for ADARED projects. Thank you for your understanding!
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

222 lines
7.8KB

  1. #
  2. # Copyright (C) Stanislaw Adaszewski, 2020
  3. # License: GPLv3
  4. #
  5. from collections import defaultdict
  6. from dataclasses import dataclass, field
  7. import torch
  8. from typing import List, \
  9. Dict, \
  10. Tuple, \
  11. Any, \
  12. Type
  13. from .decode import DEDICOMDecoder, \
  14. BilinearDecoder
  15. def _equal(x: torch.Tensor, y: torch.Tensor):
  16. if x.is_sparse ^ y.is_sparse:
  17. raise ValueError('Cannot mix sparse and dense tensors')
  18. if not x.is_sparse:
  19. return (x == y)
  20. x = x.coalesce()
  21. indices_x = list(map(tuple, x.indices().transpose(0, 1)))
  22. order_x = sorted(range(len(indices_x)), key=lambda idx: indices_x[idx])
  23. y = y.coalesce()
  24. indices_y = list(map(tuple, y.indices().transpose(0, 1)))
  25. order_y = sorted(range(len(indices_y)), key=lambda idx: indices_y[idx])
  26. if not indices_x == indices_y:
  27. return torch.tensor(0, dtype=torch.uint8)
  28. return (x.values()[order_x] == y.values()[order_y])
  29. @dataclass
  30. class NodeType(object):
  31. name: str
  32. count: int
  33. @dataclass
  34. class RelationTypeBase(object):
  35. name: str
  36. node_type_row: int
  37. node_type_column: int
  38. adjacency_matrix: torch.Tensor
  39. adjacency_matrix_backward: torch.Tensor
  40. @dataclass
  41. class RelationType(RelationTypeBase):
  42. pass
  43. @dataclass
  44. class RelationFamilyBase(object):
  45. data: 'Data'
  46. name: str
  47. node_type_row: int
  48. node_type_column: int
  49. is_symmetric: bool
  50. decoder_class: Type
  51. @dataclass
  52. class RelationFamily(RelationFamilyBase):
  53. relation_types: List[RelationType] = None
  54. def __post_init__(self) -> None:
  55. if not self.is_symmetric and \
  56. self.decoder_class != DEDICOMDecoder and \
  57. self.decoder_class != BilinearDecoder:
  58. raise TypeError('Family is assymetric but the specified decoder_class supports symmetric relations only')
  59. self.relation_types = []
  60. def add_relation_type(self,
  61. name: str, node_type_row: int, node_type_column: int,
  62. adjacency_matrix: torch.Tensor,
  63. adjacency_matrix_backward: torch.Tensor = None) -> None:
  64. name = str(name)
  65. node_type_row = int(node_type_row)
  66. node_type_column = int(node_type_column)
  67. if (node_type_row, node_type_column) != (self.node_type_row, self.node_type_column):
  68. raise ValueError('Specified node_type_row/node_type_column tuple does not belong to this family')
  69. if node_type_row < 0 or node_type_row >= len(self.data.node_types):
  70. raise ValueError('node_type_row outside of the valid range of node types')
  71. if node_type_column < 0 or node_type_column >= len(self.data.node_types):
  72. raise ValueError('node_type_column outside of the valid range of node types')
  73. if adjacency_matrix is None and adjacency_matrix_backward is None:
  74. raise ValueError('adjacency_matrix and adjacency_matrix_backward cannot both be None')
  75. if adjacency_matrix is not None and \
  76. not isinstance(adjacency_matrix, torch.Tensor):
  77. raise ValueError('adjacency_matrix must be a torch.Tensor')
  78. # if isinstance(adjacency_matrix_backward, str) and \
  79. # adjacency_matrix_backward == 'symmetric':
  80. # if self.is_symmetric:
  81. # adjacency_matrix_backward = None
  82. # else:
  83. # adjacency_matrix_backward = adjacency_matrix.transpose(0, 1)
  84. if adjacency_matrix_backward is not None \
  85. and not isinstance(adjacency_matrix_backward, torch.Tensor):
  86. raise ValueError('adjacency_matrix_backward must be a torch.Tensor')
  87. if adjacency_matrix is not None and \
  88. adjacency_matrix.shape != (self.data.node_types[node_type_row].count,
  89. self.data.node_types[node_type_column].count):
  90. raise ValueError('adjacency_matrix shape must be (num_row_nodes, num_column_nodes)')
  91. if adjacency_matrix_backward is not None and \
  92. adjacency_matrix_backward.shape != (self.data.node_types[node_type_column].count,
  93. self.data.node_types[node_type_row].count):
  94. raise ValueError('adjacency_matrix_backward shape must be (num_column_nodes, num_row_nodes)')
  95. if node_type_row == node_type_column and \
  96. adjacency_matrix_backward is not None:
  97. raise ValueError('Relation between nodes of the same type must be expressed using a single matrix')
  98. if self.is_symmetric and adjacency_matrix_backward is not None:
  99. raise ValueError('Cannot use a custom adjacency_matrix_backward in a symmetric relation family')
  100. if self.is_symmetric and node_type_row == node_type_column and \
  101. not torch.all(_equal(adjacency_matrix,
  102. adjacency_matrix.transpose(0, 1))):
  103. raise ValueError('Relation family is symmetric but adjacency_matrix is assymetric')
  104. if self.is_symmetric and node_type_row != node_type_column:
  105. adjacency_matrix_backward = adjacency_matrix.transpose(0, 1)
  106. self.relation_types.append(RelationType(name,
  107. node_type_row, node_type_column,
  108. adjacency_matrix, adjacency_matrix_backward))
  109. def node_name(self, index):
  110. return self.data.node_types[index].name
  111. def __repr__(self):
  112. s = 'Relation family %s' % self.name
  113. for r in self.relation_types:
  114. s += '\n - %s%s' % (r.name, ' (two-way)' \
  115. if (r.adjacency_matrix is not None \
  116. and r.adjacency_matrix_backward is not None) \
  117. or self.is_symmetric \
  118. else '%s <- %s' % (self.node_name(self.node_type_row),
  119. self.node_name(self.node_type_column)))
  120. return s
  121. def repr_indented(self):
  122. s = ' - %s' % self.name
  123. for r in self.relation_types:
  124. s += '\n - %s%s' % (r.name, ' (two-way)' \
  125. if (r.adjacency_matrix is not None \
  126. and r.adjacency_matrix_backward is not None) \
  127. or self.is_symmetric \
  128. else '%s <- %s' % (self.node_name(self.node_type_row),
  129. self.node_name(self.node_type_column)))
  130. return s
  131. class Data(object):
  132. node_types: List[NodeType]
  133. relation_families: List[RelationFamily]
  134. def __init__(self) -> None:
  135. self.node_types = []
  136. self.relation_families = []
  137. def add_node_type(self, name: str, count: int) -> None:
  138. name = str(name)
  139. count = int(count)
  140. if not name:
  141. raise ValueError('You must provide a non-empty node type name')
  142. if count <= 0:
  143. raise ValueError('You must provide a positive node count')
  144. self.node_types.append(NodeType(name, count))
  145. def add_relation_family(self, name: str, node_type_row: int,
  146. node_type_column: int, is_symmetric: bool,
  147. decoder_class: Type = DEDICOMDecoder):
  148. fam = RelationFamily(self, name, node_type_row, node_type_column,
  149. is_symmetric, decoder_class)
  150. self.relation_families.append(fam)
  151. return fam
  152. def __repr__(self):
  153. n = len(self.node_types)
  154. if n == 0:
  155. return 'Empty Icosagon Data'
  156. s = ''
  157. s += 'Icosagon Data with:\n'
  158. s += '- ' + str(n) + ' node type(s):\n'
  159. for nt in self.node_types:
  160. s += ' - ' + nt.name + '\n'
  161. if len(self.relation_families) == 0:
  162. s += '- No relation families\n'
  163. return s.strip()
  164. s += '- %d relation families:\n' % len(self.relation_families)
  165. for fam in self.relation_families:
  166. s += fam.repr_indented() + '\n'
  167. return s.strip()