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!
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

220 Zeilen
7.6KB

  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 not self.is_symmetric and node_type_row != node_type_column and \
  92. adjacency_matrix_backward is None:
  93. raise ValueError('Relation is asymmetric but adjacency_matrix_backward is None')
  94. if self.is_symmetric and node_type_row != node_type_column:
  95. adjacency_matrix_backward = adjacency_matrix.transpose(0, 1)
  96. self.relation_types.append(RelationType(name,
  97. node_type_row, node_type_column,
  98. adjacency_matrix, adjacency_matrix_backward))
  99. def node_name(self, index):
  100. return self.data.node_types[index].name
  101. def __repr__(self):
  102. s = 'Relation family %s' % self.name
  103. for r in self.relation_types:
  104. s += '\n - %s%s' % (r.name, ' (two-way)' \
  105. if (r.adjacency_matrix is not None \
  106. and r.adjacency_matrix_backward is not None) \
  107. or self.node_type_row == self.node_type_column \
  108. else '%s <- %s' % (self.node_name(self.node_type_row),
  109. self.node_name(self.node_type_column)))
  110. return s
  111. def repr_indented(self):
  112. s = ' - %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.node_type_row == self.node_type_column \
  118. else '%s <- %s' % (self.node_name(self.node_type_row),
  119. self.node_name(self.node_type_column)))
  120. return s
  121. class Data(object):
  122. node_types: List[NodeType]
  123. relation_families: List[RelationFamily]
  124. def __init__(self) -> None:
  125. self.node_types = []
  126. self.relation_families = []
  127. def add_node_type(self, name: str, count: int) -> None:
  128. name = str(name)
  129. count = int(count)
  130. if not name:
  131. raise ValueError('You must provide a non-empty node type name')
  132. if count <= 0:
  133. raise ValueError('You must provide a positive node count')
  134. self.node_types.append(NodeType(name, count))
  135. def add_relation_family(self, name: str, node_type_row: int,
  136. node_type_column: int, is_symmetric: bool,
  137. decoder_class: Type = DEDICOMDecoder):
  138. name = str(name)
  139. node_type_row = int(node_type_row)
  140. node_type_column = int(node_type_column)
  141. is_symmetric = bool(is_symmetric)
  142. if node_type_row < 0 or node_type_row >= len(self.node_types):
  143. raise ValueError('node_type_row outside of the valid range of node types')
  144. if node_type_column < 0 or node_type_column >= len(self.node_types):
  145. raise ValueError('node_type_column outside of the valid range of node types')
  146. fam = RelationFamily(self, name, node_type_row, node_type_column,
  147. is_symmetric, decoder_class)
  148. self.relation_families.append(fam)
  149. return fam
  150. def __repr__(self):
  151. n = len(self.node_types)
  152. if n == 0:
  153. return 'Empty Icosagon Data'
  154. s = ''
  155. s += 'Icosagon Data with:\n'
  156. s += '- ' + str(n) + ' node type(s):\n'
  157. for nt in self.node_types:
  158. s += ' - ' + nt.name + '\n'
  159. if len(self.relation_families) == 0:
  160. s += '- No relation families\n'
  161. return s.strip()
  162. s += '- %d relation families:\n' % len(self.relation_families)
  163. for fam in self.relation_families:
  164. s += fam.repr_indented() + '\n'
  165. return s.strip()