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.

215 lines
7.7KB

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