[7823dd]: / pathaia / graphs / object_api.py

Download this file

506 lines (452 with data), 17.6 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
"""Classes used to represent graphs."""
from typing import List, Sequence, Optional, Union, Tuple
import json
import warnings
from scipy.sparse import spmatrix, dok_matrix
import numpy as np
from ordered_set import OrderedSet
from shapely.geometry import Polygon
from shapely.ops import unary_union
from shapely.affinity import translate
from pathlib import Path
from .types import (
Node,
NodeProperties,
BinaryNodeProperty,
NumericalNodeProperty,
Parenthood,
Childhood,
Edge,
UEdge,
EdgeProperties,
NumericalEdgeProperty,
)
from ..util.types import PathLike
from .errors import (
InvalidNodeProps,
UndefinedParenthood,
UndefinedChildhood,
UnknownNodeProperty,
)
from .functional_api import (
complete_tree as _complete_tree,
get_nodeprops_edgeprops,
get_root as _get_root,
get_root_path as _get_root_path,
get_leaves as _get_leaves,
tree_to_json as _tree_to_json,
kruskal_tree as _kruskal_tree,
cut_on_property as _cut_on_property,
common_ancestor as _common_ancestor,
edge_dist as _edge_dist,
weighted_dist as _weighted_dist,
get_kneighbors_graph,
)
from ..util.basic import ifnone
import ast
MAX_N_NODES = int(10e7)
class Graph:
"""Object to represent a directed graph."""
def __init__(
self,
nodes: Optional[Sequence[Node]] = None,
edges: Optional[Sequence[Edge]] = None,
A: Optional[spmatrix] = None,
nodeprops: Optional[NodeProperties] = None,
edgeprops: Optional[EdgeProperties] = None,
):
self.A_ = dok_matrix((MAX_N_NODES, MAX_N_NODES), dtype=bool)
if nodes is None:
self.nodes_ = OrderedSet()
if edges is not None:
self.edges_ = set(edges)
for x, y in edges:
i = self.nodes_.add(x)
j = self.nodes_.add(y)
self.A_[i, j] = True
elif A is not None:
self.nodes_ = OrderedSet(np.arange(A.shape[0]))
self.edges_ = set()
for i, j in zip(*A.nonzero()):
self.edges_.add((i, j))
self.A_[i, j] = True
else:
self.edges_ = set()
else:
self.nodes_ = OrderedSet(nodes)
if edges is not None:
self.edges_ = set(edges)
for x, y in edges:
i = self.nodes_.index(x)
j = self.nodes_.index(y)
self.A_[i, j] = True
elif A is not None:
self.edges_ = set()
for i, j in zip(*A.nonzero()):
self.edges_.add((self.nodes_[i], self.nodes_[j]))
self.A_[i, j] = True
else:
self.edges_ = set()
self.nodeprops = ifnone(nodeprops, {})
self.edgeprops = ifnone(edgeprops, {})
@property
def n_nodes(self):
return len(self.nodes_)
@property
def nodes(self):
return self.nodes_
@property
def edges(self):
return self.edges_
@property
def A(self):
return self.A_.tocsr()[: self.n_nodes, : self.n_nodes]
def add_node(self, node: Node):
self.nodes_.add(node)
def add_nodes(self, nodes: Sequence[Node]):
for node in nodes:
self.add_node(node)
def add_edge(self, edge: Edge):
self.add_nodes(edge)
self.edges_.add(edge)
n1, n2 = edge
i = self.nodes_.index(n1)
j = self.nodes_.index(n2)
self.A_[i, j] = True
def add_edges(self, edges: Sequence[Edge]):
for edge in edges:
self.add_edge(edge)
def remove_edge(self, edge: Edge):
try:
self.edges_.remove(edge)
except KeyError:
print(f"Edge {edge} was not found in graph")
n1, n2 = edge
i = self.nodes_.index(n1)
j = self.nodes_.index(n2)
self.A_[i, j] = False
def reset(self):
self.nodes_ = OrderedSet()
self.edges_ = set()
self.A_ = dok_matrix((MAX_N_NODES, MAX_N_NODES), dtype=bool)
self.nodeprops = {}
self.edgeprops = {}
class UGraph(Graph):
"""Class to represent an undirected graph."""
def __init__(
self,
nodes: Optional[Sequence[Node]] = None,
edges: Optional[Sequence[Edge]] = None,
A: Optional[spmatrix] = None,
nodeprops: Optional[NodeProperties] = None,
edgeprops: Optional[EdgeProperties] = None,
):
super().__init__(nodes, edges, A, nodeprops, edgeprops)
self.edges_ = {UEdge(edge, key=self.nodes_.index) for edge in self.edges_}
@property
def A(self):
A = self.A_.tocsr()[: self.n_nodes, : self.n_nodes]
return A + A.T
def add_edge(self, edge: Edge):
super().add_edge(UEdge(edge, key=self.nodes_.index))
def remove_edge(self, edge: Edge):
super().remove_edge(UEdge(edge, key=self.nodes_.index))
n1, n2 = edge
i = self.nodes_.index(n1)
j = self.nodes_.index(n2)
self.A_[j, i] = False
@classmethod
def from_hovernet_wsi_file(
cls,
wsi_file: PathLike,
n_farthest_samples: Union[int, float] = 0.3,
n_random_samples: Union[int, float] = 0.1,
dmax: int = 500,
n_neighbors: int = 5,
n_jobs: Optional[int] = None,
):
"""
Create a cell graph from a single hovernet json file generated from their WSI
script.
Args:
wsi_file: json_file generated by hovernet's run_wsi.sh.
n_farthest_samples: number of points to keep using farthest points sampling.
If a float is given, represents the proportion of points used instead.
n_random_samples: number of points to keep using random sampling. If a float
is given, represents the proportion of points used instead.
dmax: maximum distance in pixels between two adjacent nodes.
n_neighbors: number of neighbors to use for KNN algorithm.
n_jobs: number of parallel jobs to run for neighbors search. None means 1.
Returns:
A UGraph representing cell nuclei connections.
"""
with open(wsi_file, "r") as f:
nuc_dict = json.load(f)
centroids = []
for k in nuc_dict["nuc"]:
x, y = nuc_dict["nuc"][k]["centroid"]
centroids.append((x, y))
centroids = np.array(centroids)
A = get_kneighbors_graph(
centroids,
n_farthest_samples=n_farthest_samples,
n_random_samples=n_random_samples,
dmax=dmax,
n_neighbors=n_neighbors,
n_jobs=n_jobs,
)
nodeprops, edgeprops = get_nodeprops_edgeprops(A, centroids)
return cls(A=A, nodeprops=nodeprops, edgeprops=edgeprops)
@classmethod
def from_hovernet_patch_file(
cls,
patch_folder: PathLike,
n_farthest_samples: Union[int, float] = 0.3,
n_random_samples: Union[int, float] = 0.1,
dmax: int = 500,
n_neighbors: int = 5,
n_jobs: Optional[int] = None,
):
"""
Create a cell graph from a folder containing hovernet json files generated from
their tile script.
Args:
patch_folder: folder containing json_files generated by hovernet's
run_tile.sh. Files must be named with x_y_level.json formatting.
n_farthest_samples: number of points to keep using farthest points sampling.
If a float is given, represents the proportion of points used instead.
n_random_samples: number of points to keep using random sampling. If a float
is given, represents the proportion of points used instead.
dmax: maximum distance in pixels between two adjacent nodes.
n_neighbors: number of neighbors to use for KNN algorithm.
n_jobs: number of parallel jobs to run for neighbors search. None means 1.
Returns:
A UGraph representing cell nuclei connections.
"""
patch_folder = Path(patch_folder)
polygons = []
for json_file in patch_folder.iterdir():
with open(json_file, "r") as f:
nuc_dict = json.load(f)
x, y = map(int, json_file.stem.split("_")[:2])
for k in nuc_dict["nuc"]:
contour = nuc_dict["nuc"][k]["contour"]
polygon = Polygon(contour)
polygon = translate(polygon, xoff=x, yoff=y)
polygons.append(polygon)
polygons = unary_union(polygons)
centroids = [(polygon.centroid.x, polygon.centroid.y) for polygon in polygons]
centroids = np.array(centroids, dtype=np.int32)
A = get_kneighbors_graph(
centroids,
n_farthest_samples=n_farthest_samples,
n_random_samples=n_random_samples,
dmax=dmax,
n_neighbors=n_neighbors,
n_jobs=n_jobs,
)
nodeprops, edgeprops = get_nodeprops_edgeprops(A, centroids)
return cls(A=A, edgeprops=edgeprops, nodeprops=nodeprops)
class Tree(Graph):
"""Object to handle trees."""
def __init__(
self,
nodes: Optional[Sequence[Node]] = None,
edges: Optional[Sequence[Edge]] = None,
parents: Optional[Parenthood] = None,
children: Optional[Childhood] = None,
nodeprops: Optional[NodeProperties] = None,
edgeprops: Optional[EdgeProperties] = None,
jsonfile: Optional[str] = None,
):
"""Init tree object."""
if jsonfile is not None:
self.from_json(jsonfile)
edges = set()
for parent in self.children_:
for child in self.children_[parent]:
edges.add((parent, child))
else:
if edges is not None and (parents is not None or children is not None):
warnings.warn(
"Be careful when specifying both edges and parents/children,"
"consistency will not be checked and edges will be prioritized."
)
if edges is None:
edges = set()
self.parents_, self.children_ = _complete_tree(parents, children)
for parent in self.children_:
for child in self.children_[parent]:
edges.add((parent, child))
else:
edges = set(edges)
self.parents_ = {}
self.children_ = {}
for parent, child in edges:
self.parents_[child] = parent
try:
self.children_[parent].add(child)
except KeyError:
self.children_[parent] = {child}
super().__init__(
nodes=nodes, edges=edges, nodeprops=nodeprops, edgeprops=edgeprops
)
@property
def parents(self) -> Parenthood:
return self.parents_
@property
def children(self) -> Childhood:
return self.children_
def add_edge(self, parent: Node, child: Node):
self.parents_[child] = parent
try:
self.children_[parent].add(child)
except KeyError:
self.children_[parent] = {child}
super().add_edge((parent, child))
def add_children(self, parent: Node, children: Sequence[Node]):
for child in children:
self.parents_[child] = parent
super().add_edge((parent, child))
try:
self.children_[parent] |= set(children)
except KeyError:
self.children_[parent] = set(children)
def add_edges(self, edges: Sequence[Tuple[Node, Union[Node, Sequence[Node]]]]):
for p, c in edges:
if isinstance(c, Node):
self.add_edge(p, c)
else:
self.add_children(p, c)
def reset(self):
super().reset()
self.parents_ = {}
self.children_ = {}
def get_root(self, node: Node = None) -> Node:
"""Give root of the tree."""
if self.parents_ is not None:
return _get_root(self.parents_, node)
raise UndefinedParenthood(
"Parenthood of the tree was not defined, "
"please build the tree before use."
)
def get_root_path(self, node: Node) -> List[Node]:
"""Get path to root of the tree."""
if self.parents_ is not None:
return _get_root_path(self.parents_, node)
raise UndefinedParenthood(
"Parenthood of the tree was not defined, "
"please build the tree before use."
)
def get_leaves(
self, node: Node, prop: Optional[BinaryNodeProperty] = None
) -> List[Node]:
"""Get leaves of a node."""
if self.children_ is not None:
return _get_leaves(self.children_, node, prop)
raise UndefinedChildhood(
"Childhood of the tree was not defined, "
"please build the tree before use."
)
def to_json(self, jsonfile):
"""Store the tree to json file."""
_tree_to_json(
self.nodes_,
self.parents_,
self.children_,
jsonfile,
self.nodeprops,
self.edgeprops,
)
def from_json(self, jsonfile):
"""Create the tree from a json file."""
# Keep in mind that json keys have to be str.
# In treez framework, they can be python object as well
# We use ast to parse the str to a python object before
# This behaviour might limit even more the types of
# parenthood/childhood/props keys when using treez...
with open(jsonfile, "r") as jf:
json_dict = json.load(jf)
self.reset()
for parent, children in json_dict["children"].items():
try:
parentkey = ast.literal_eval(parent)
self.add_children(parentkey, children)
except (ValueError, SyntaxError):
self.add_children(parent, children)
self.edgeprops = dict()
for name, edgeprop in json_dict["edgeprops"].item():
self.edgeprops[name] = dict()
for edgein, edgeout in edgeprop.items():
try:
edgekey = ast.literal_eval(edgein)
self.edgeprops[name][edgekey] = edgeout
except (ValueError, SyntaxError):
self.edgeprops[name][edgein] = edgeout
for name, nodeprop in json_dict["nodeprops"].items():
for nodein, nodeout in nodeprop.items():
try:
nodekey = ast.literal_eval(nodein)
self.nodeprops[name][nodekey] = nodeout
except (ValueError, SyntaxError):
self.nodeprops[name][nodein] = nodeout
def build_kruskal(
self,
edges: Sequence[Edge],
weights: NumericalEdgeProperty,
size: NumericalNodeProperty,
):
"""Build tree with kruskal algorithm from graph edges."""
_, k_children, k_props = _kruskal_tree(edges, weights, size)
for parent in k_children:
self.add_children(parent, k_children)
self.nodeprops = k_props
def cut_on_property(self, cut_name: str, prop: str, threshold: Union[int, float]):
"""
Produce a list of authorized nodes given a property threshold.
Set a new property to these nodes.
"""
if prop in self.nodeprops:
node_of_interest = _cut_on_property(
self.parents_, self.children_, self.nodeprops[prop], threshold
)
cut = dict()
for node in self.nodes:
if node in node_of_interest:
cut[node] = True
else:
cut[node] = False
self.nodeprops[cut_name] = cut
else:
raise UnknownNodeProperty(
"Property {}"
" is not in the tree properties: {}".format(
prop, list(self.nodeprops.keys())
)
)
def common_ancestor(self, node1: Node, node2: Node) -> Node:
"""Return the common ancestor of node1 and node2."""
return _common_ancestor(self.parents_, node1, node2)
def edge_dist(self, node1: Node, node2: Node) -> int:
"""Return the number of edges to go from node1 to node2 (by common ancestor)."""
return _edge_dist(self.parents_, node1, node2)
def weighted_dist(
self, weights: Union[NumericalNodeProperty, str], node1: Node, node2: Node
) -> float:
"""Return the number of edges to go from node1 to node2 (by common ancestor)."""
if isinstance(weights, str):
if weights in self.nodeprops:
return _weighted_dist(
self.parents_, self.nodeprops[weights], node1, node2
)
raise InvalidNodeProps(
"Property {} is not in tree properties: {}".format(
weights, self.nodeprops
)
)
if isinstance(weights, dict):
return _weighted_dist(self.parents_, weights, node1, node2)
raise InvalidNodeProps(
"Provided property is not a valid property. "
"Expected {} or {}, got {}".format(dict, str, type(weights))
)