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.

216 line
7.4KB

  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, adjacency_matrix: torch.Tensor,
  62. adjacency_matrix_backward: torch.Tensor = None) -> None:
  63. name = str(name)
  64. node_type_row = self.node_type_row
  65. node_type_column = self.node_type_column
  66. if adjacency_matrix is None and adjacency_matrix_backward is None:
  67. raise ValueError('adjacency_matrix and adjacency_matrix_backward cannot both be None')
  68. if adjacency_matrix is not None and \
  69. not isinstance(adjacency_matrix, torch.Tensor):
  70. raise ValueError('adjacency_matrix must be a torch.Tensor')
  71. if adjacency_matrix_backward is not None \
  72. and not isinstance(adjacency_matrix_backward, torch.Tensor):
  73. raise ValueError('adjacency_matrix_backward must be a torch.Tensor')
  74. if adjacency_matrix is not None and \
  75. adjacency_matrix.shape != (self.data.node_types[node_type_row].count,
  76. self.data.node_types[node_type_column].count):
  77. raise ValueError('adjacency_matrix shape must be (num_row_nodes, num_column_nodes)')
  78. if adjacency_matrix_backward is not None and \
  79. adjacency_matrix_backward.shape != (self.data.node_types[node_type_column].count,
  80. self.data.node_types[node_type_row].count):
  81. raise ValueError('adjacency_matrix_backward shape must be (num_column_nodes, num_row_nodes)')
  82. if node_type_row == node_type_column and \
  83. adjacency_matrix_backward is not None:
  84. raise ValueError('Relation between nodes of the same type must be expressed using a single matrix')
  85. if self.is_symmetric and adjacency_matrix_backward is not None:
  86. raise ValueError('Cannot use a custom adjacency_matrix_backward in a symmetric relation family')
  87. if self.is_symmetric and node_type_row == node_type_column and \
  88. not torch.all(_equal(adjacency_matrix,
  89. adjacency_matrix.transpose(0, 1))):
  90. raise ValueError('Relation family is symmetric but adjacency_matrix is assymetric')
  91. if self.is_symmetric and node_type_row != node_type_column:
  92. adjacency_matrix_backward = adjacency_matrix.transpose(0, 1)
  93. self.relation_types.append(RelationType(name,
  94. node_type_row, node_type_column,
  95. adjacency_matrix, adjacency_matrix_backward))
  96. def node_name(self, index):
  97. return self.data.node_types[index].name
  98. def __repr__(self):
  99. s = 'Relation family %s' % self.name
  100. for r in self.relation_types:
  101. s += '\n - %s%s' % (r.name, ' (two-way)' \
  102. if (r.adjacency_matrix is not None \
  103. and r.adjacency_matrix_backward is not None) \
  104. or self.node_type_row == self.node_type_column \
  105. else '%s <- %s' % (self.node_name(self.node_type_row),
  106. self.node_name(self.node_type_column)))
  107. return s
  108. def repr_indented(self):
  109. s = ' - %s' % self.name
  110. for r in self.relation_types:
  111. s += '\n - %s%s' % (r.name, ' (two-way)' \
  112. if (r.adjacency_matrix is not None \
  113. and r.adjacency_matrix_backward is not None) \
  114. or self.node_type_row == self.node_type_column \
  115. else '%s <- %s' % (self.node_name(self.node_type_row),
  116. self.node_name(self.node_type_column)))
  117. return s
  118. class Data(object):
  119. node_types: List[NodeType]
  120. relation_families: List[RelationFamily]
  121. def __init__(self) -> None:
  122. self.node_types = []
  123. self.relation_families = []
  124. def add_node_type(self, name: str, count: int) -> None:
  125. name = str(name)
  126. count = int(count)
  127. if not name:
  128. raise ValueError('You must provide a non-empty node type name')
  129. if count <= 0:
  130. raise ValueError('You must provide a positive node count')
  131. self.node_types.append(NodeType(name, count))
  132. def add_relation_family(self, name: str, node_type_row: int,
  133. node_type_column: int, is_symmetric: bool,
  134. decoder_class: Type = DEDICOMDecoder):
  135. name = str(name)
  136. node_type_row = int(node_type_row)
  137. node_type_column = int(node_type_column)
  138. is_symmetric = bool(is_symmetric)
  139. if node_type_row < 0 or node_type_row >= len(self.node_types):
  140. raise ValueError('node_type_row outside of the valid range of node types')
  141. if node_type_column < 0 or node_type_column >= len(self.node_types):
  142. raise ValueError('node_type_column outside of the valid range of node types')
  143. fam = RelationFamily(self, name, node_type_row, node_type_column,
  144. is_symmetric, decoder_class)
  145. self.relation_families.append(fam)
  146. return fam
  147. def __repr__(self):
  148. n = len(self.node_types)
  149. if n == 0:
  150. return 'Empty Icosagon Data'
  151. s = ''
  152. s += 'Icosagon Data with:\n'
  153. s += '- ' + str(n) + ' node type(s):\n'
  154. for nt in self.node_types:
  155. s += ' - ' + nt.name + '\n'
  156. if len(self.relation_families) == 0:
  157. s += '- No relation families\n'
  158. return s.strip()
  159. s += '- %d relation families:\n' % len(self.relation_families)
  160. for fam in self.relation_families:
  161. s += fam.repr_indented() + '\n'
  162. return s.strip()