edgeable 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
edgeable/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ import logging
2
+
3
+ from edgeable.threadlock import GraphModifyLock, GraphReadLock
4
+
5
+ from edgeable.edge import GraphEdge
6
+ from edgeable.node import GraphNode
7
+ from edgeable.database import GraphDatabase
8
+
9
+ # A library must not configure logging for the application using it.
10
+ logging.getLogger("edgeable").addHandler(logging.NullHandler())
edgeable/database.py ADDED
@@ -0,0 +1,425 @@
1
+ import gzip
2
+ import importlib
3
+ import logging
4
+ import numbers
5
+ import os
6
+ import pickle
7
+ import stat
8
+ import tempfile
9
+ import threading
10
+ import uuid
11
+
12
+ from edgeable.threadlock import GraphModifyLock, GraphReadLock
13
+ from edgeable.edge import GraphEdge
14
+ from edgeable.node import GraphNode
15
+
16
+ logger = logging.getLogger("edgeable")
17
+
18
+ # Marker and version of the persisted file layout. Files are a gzip compressed
19
+ # pickle of the tuple (_FORMAT_MARKER, _FORMAT_VERSION, graph, properties).
20
+ # Files written by earlier releases are a gzip compressed pickle of just the
21
+ # graph dict, and are still readable.
22
+ _FORMAT_MARKER = "edgeable"
23
+ _FORMAT_VERSION = 2
24
+
25
+ # Persistent id standing in for the owning database inside a persisted file.
26
+ _DATABASE_PERSISTENT_ID = "edgeable.GraphDatabase"
27
+
28
+ # Attributes of a database which are never pickled.
29
+ _TRANSIENT_ATTRIBUTES = frozenset(
30
+ ["_on_create_node", "_on_delete_node", "_on_create_edge", "_on_delete_edge"]
31
+ + ["_lock"]
32
+ )
33
+
34
+ # The only globals a persisted file may reference, as (module, name). Anything
35
+ # else is refused when loading, rather than imported and called.
36
+ _SAFE_GLOBALS = frozenset(
37
+ [
38
+ ("builtins", "set"),
39
+ ("builtins", "frozenset"),
40
+ ("builtins", "complex"),
41
+ ("builtins", "bytearray"),
42
+ ("builtins", "range"),
43
+ ("builtins", "slice"),
44
+ ("collections", "OrderedDict"),
45
+ ("collections", "deque"),
46
+ ("collections", "Counter"),
47
+ ("datetime", "datetime"),
48
+ ("datetime", "date"),
49
+ ("datetime", "time"),
50
+ ("datetime", "timedelta"),
51
+ ("datetime", "timezone"),
52
+ ("decimal", "Decimal"),
53
+ ("fractions", "Fraction"),
54
+ ("uuid", "UUID"),
55
+ ]
56
+ )
57
+
58
+
59
+ class _LegacyDatabaseReference:
60
+ """Inert stand-in for the GraphDatabase instances embedded in files written
61
+ by earlier releases. The real class is never instantiated while loading;
62
+ nodes and edges are re-bound to the loading database afterwards."""
63
+
64
+ def __new__(cls, *args, **kwargs):
65
+ return object.__new__(cls)
66
+
67
+ def __init__(self, *args, **kwargs):
68
+ pass
69
+
70
+
71
+ class _GraphPickler(pickle.Pickler):
72
+ """Pickler which writes a reference in place of any database object, and
73
+ refuses to write anything that could not be loaded again."""
74
+
75
+ def persistent_id(self, obj):
76
+ if isinstance(obj, GraphDatabase):
77
+ return _DATABASE_PERSISTENT_ID
78
+ return None
79
+
80
+ # Called for everything which is not a plain None, bool,
81
+ # int, float, str, bytes, tuple, list, dict, set, frozenset or bytearray.
82
+ def reducer_override(self, obj):
83
+ cls = obj if isinstance(obj, type) else type(obj)
84
+ if cls not in _SAFE_CLASSES:
85
+ raise pickle.PicklingError(
86
+ "Cannot save a value of type '%s.%s', which is not a type that "
87
+ "is permitted in a database file."
88
+ % (getattr(cls, "__module__", "?"), getattr(cls, "__qualname__", cls))
89
+ )
90
+ return NotImplemented
91
+
92
+
93
+ class _GraphUnpickler(pickle.Unpickler):
94
+ """Unpickler which only resolves an allowlist of classes, and resolves the
95
+ database reference to the database which is loading the file."""
96
+
97
+ def __init__(self, file, database):
98
+ super().__init__(file)
99
+ self._database = database
100
+
101
+ def persistent_load(self, pid):
102
+ if pid == _DATABASE_PERSISTENT_ID:
103
+ return self._database
104
+ raise pickle.UnpicklingError(
105
+ "Unsupported persistent reference in database file."
106
+ )
107
+
108
+ def find_class(self, module, name):
109
+ if (module, name) == ("edgeable.node", "GraphNode"):
110
+ return GraphNode
111
+ if (module, name) == ("edgeable.edge", "GraphEdge"):
112
+ return GraphEdge
113
+ if (module, name) == ("edgeable.database", "GraphDatabase"):
114
+ return _LegacyDatabaseReference
115
+ if (module, name) in _SAFE_GLOBALS:
116
+ return super().find_class(module, name)
117
+ raise pickle.UnpicklingError(
118
+ "Database file references '%s.%s', which is not a type that is "
119
+ "permitted in a database file." % (module, name)
120
+ )
121
+
122
+
123
+ _SAFE_CLASSES = frozenset(
124
+ [GraphNode, GraphEdge]
125
+ + [getattr(importlib.import_module(m), n) for (m, n) in _SAFE_GLOBALS]
126
+ )
127
+
128
+
129
+ def _is_filter(fn):
130
+ return callable(fn)
131
+
132
+
133
+ class GraphDatabase:
134
+ """Class representing the graph database."""
135
+
136
+ def __init__(self, filename="graph.db", properties=None):
137
+ if type(filename) is not str:
138
+ raise RuntimeError("Filename must be a string.")
139
+ if properties is not None and type(properties) is not dict:
140
+ raise RuntimeError("Properties be a dict.")
141
+ if properties is not None and any(type(key) is not str for key in properties):
142
+ raise RuntimeError("Key must be a string.")
143
+
144
+ self._graph = {}
145
+ self._properties = {}
146
+ self._filename = filename
147
+
148
+ if os.path.exists(filename):
149
+ self.reload()
150
+
151
+ # explicitly provided properties take precedence over loaded ones
152
+ if properties:
153
+ self._properties.update(properties)
154
+
155
+ def __new__(cls, *args, **kwargs):
156
+ self = super().__new__(cls)
157
+
158
+ # callbacks and lock, also initialized for unpickled objects
159
+ self._on_create_node = {}
160
+ self._on_delete_node = {}
161
+ self._on_create_edge = {}
162
+ self._on_delete_edge = {}
163
+ self._lock = threading.RLock()
164
+ return self
165
+
166
+ def __getstate__(self):
167
+ return {
168
+ k: v for (k, v) in self.__dict__.items() if k not in _TRANSIENT_ATTRIBUTES
169
+ }
170
+
171
+ def __enter__(self):
172
+ return self
173
+
174
+ def __exit__(self, exc_type, exc_val, exc_tb):
175
+ self.save()
176
+
177
+ @GraphReadLock
178
+ def get_nodes(self, filter_fn=lambda node: True):
179
+ """Return all nodes, or nodes which match the optional filter function."""
180
+ if not _is_filter(filter_fn):
181
+ raise RuntimeError("Filter must be a function.")
182
+
183
+ # iterate a snapshot, the filter is allowed to modify the graph
184
+ return [node for node in list(self._graph.values()) if filter_fn(node)]
185
+
186
+ @GraphReadLock
187
+ def get_edges(
188
+ self, edge_filter_fn=lambda edge: True, node_filter_fn=lambda node: True
189
+ ):
190
+ """Return all edges, or edges which match the optional filter function."""
191
+ if not _is_filter(edge_filter_fn) or not _is_filter(node_filter_fn):
192
+ raise RuntimeError("Filter must be a function.")
193
+
194
+ return [
195
+ edge
196
+ for edges in [
197
+ node.get_edges() for node in self.get_nodes() if node_filter_fn(node)
198
+ ]
199
+ for edge in edges
200
+ if edge_filter_fn(edge)
201
+ ]
202
+
203
+ @GraphReadLock
204
+ def get_node(self, id):
205
+ """Get the node with the provided id, or None if it does not exist."""
206
+ return self._graph[id] if self.has_node(id) else None
207
+
208
+ @GraphReadLock
209
+ def has_node(self, id):
210
+ """Boolean indicating if the node is defined."""
211
+ return id in self._graph
212
+
213
+ @GraphModifyLock
214
+ def put_node(self, id, properties={}):
215
+ """Create a node, or update it if it already exists. Returns the node."""
216
+ if type(id) is not str and not isinstance(id, numbers.Number):
217
+ raise RuntimeError("Node id must be a string or number.")
218
+ if type(properties) is not dict:
219
+ raise RuntimeError("Properties must be a dict.")
220
+
221
+ if not self.has_node(id):
222
+ logger.debug("create node '%s' (%s)", id, properties)
223
+ node = GraphNode(self, id)
224
+ node._properties = properties.copy()
225
+
226
+ # run every create node event callback, any of them may cancel
227
+ cancel = False
228
+ for fn in list(self._on_create_node.values()):
229
+ if fn(node) is False:
230
+ cancel = True
231
+
232
+ if not cancel:
233
+ self._graph[id] = node
234
+ else:
235
+ return None
236
+
237
+ else:
238
+ self._graph[id]._properties = {**self._graph[id]._properties, **properties}
239
+
240
+ return self._graph[id]
241
+
242
+ def _set_callback(self, callbacks, fn, id):
243
+ """Register, replace or (when fn is None) remove an event callback."""
244
+ if fn is not None and not callable(fn):
245
+ raise RuntimeError("Callback must be a function or None.")
246
+
247
+ if fn is None:
248
+ # removal, which is a no-op for an id which is not registered
249
+ if id is not None:
250
+ callbacks.pop(id, None)
251
+ return id
252
+
253
+ if id is None:
254
+ id = uuid.uuid1()
255
+ callbacks[id] = fn
256
+ return id
257
+
258
+ @GraphModifyLock
259
+ def on_create_node(self, fn, id=None):
260
+ """Set, change or (with fn=None) remove a node creation callback."""
261
+ return self._set_callback(self._on_create_node, fn, id)
262
+
263
+ @GraphModifyLock
264
+ def on_delete_node(self, fn, id=None):
265
+ """Set, change or (with fn=None) remove a node deletion callback."""
266
+ return self._set_callback(self._on_delete_node, fn, id)
267
+
268
+ @GraphModifyLock
269
+ def on_create_edge(self, fn, id=None):
270
+ """Set, change or (with fn=None) remove an edge creation callback."""
271
+ return self._set_callback(self._on_create_edge, fn, id)
272
+
273
+ @GraphModifyLock
274
+ def on_delete_edge(self, fn, id=None):
275
+ """Set, change or (with fn=None) remove an edge deletion callback."""
276
+ return self._set_callback(self._on_delete_edge, fn, id)
277
+
278
+ @GraphModifyLock
279
+ def set_property(self, key, value):
280
+ """Set a database property."""
281
+ if type(key) is not str:
282
+ raise RuntimeError("Key must be a string.")
283
+ self._properties[key] = value
284
+
285
+ @GraphModifyLock
286
+ def set_properties(self, properties):
287
+ """Set multiple properties from the provided dict. Properties not in the dict are not removed."""
288
+ if type(properties) is not dict:
289
+ raise RuntimeError("Properties be a dict.")
290
+ if any(type(key) is not str for key in properties):
291
+ raise RuntimeError("Key must be a string.")
292
+ self._properties = {**self._properties, **properties}
293
+
294
+ @GraphReadLock
295
+ def get_property(self, key):
296
+ """Get the property value."""
297
+ if type(key) is not str:
298
+ raise RuntimeError("Key must be a string.")
299
+ return self._properties[key] if self.has_property(key) else None
300
+
301
+ @GraphReadLock
302
+ def get_properties(self):
303
+ """Get a dict containing all properties and values."""
304
+ return self._properties.copy()
305
+
306
+ @GraphReadLock
307
+ def has_property(self, key):
308
+ """Boolean value indicating if the property is defined."""
309
+ if type(key) is not str:
310
+ raise RuntimeError("Key must be a string.")
311
+ return key in self._properties
312
+
313
+ @GraphModifyLock
314
+ def delete_property(self, key):
315
+ """Delete a property if it is defined. Returns the previous value, or None."""
316
+ if type(key) is not str:
317
+ raise RuntimeError("Key must be a string.")
318
+ value = self.get_property(key)
319
+ if self.has_property(key):
320
+ del self._properties[key]
321
+ return value
322
+
323
+ @GraphReadLock
324
+ def get_node_count(self):
325
+ """Return the number of nodes."""
326
+ return len(self._graph)
327
+
328
+ @GraphReadLock
329
+ def get_edge_count(self):
330
+ """Return the number of edges."""
331
+ return sum([len(self._graph[node]._edges) for node in self._graph])
332
+
333
+ @GraphModifyLock
334
+ def reload(self):
335
+ """Reload the database from the local filesystem, replacing the nodes,
336
+ edges and database properties held in memory. Registered callbacks are
337
+ kept.
338
+
339
+ Only edgeable's own classes and a fixed set of plain data types are
340
+ permitted in the file; pickle.UnpicklingError is raised for anything
341
+ else, and the database in memory is left unchanged."""
342
+
343
+ logger.debug("load from file '%s'", self._filename)
344
+ with gzip.open(self._filename, "rb") as f:
345
+ content = _GraphUnpickler(f, self).load()
346
+
347
+ if (
348
+ type(content) is tuple
349
+ and len(content) == 4
350
+ and content[0] == _FORMAT_MARKER
351
+ ):
352
+ _, version, graph, properties = content
353
+ if version != _FORMAT_VERSION:
354
+ raise pickle.UnpicklingError(
355
+ "Unsupported database file version '%s'." % (version,)
356
+ )
357
+ else:
358
+ # Written by an earlier release: only the graph was persisted, so
359
+ # the properties of this database are left as they are.
360
+ graph, properties = content, None
361
+
362
+ if type(graph) is not dict or (
363
+ properties is not None and type(properties) is not dict
364
+ ):
365
+ raise pickle.UnpicklingError("File is not an edgeable database.")
366
+
367
+ # Bind everything loaded to this database. Earlier releases persisted a
368
+ # copy of the database with the nodes, which they stayed attached to.
369
+ for node in graph.values():
370
+ if (
371
+ type(node) is not GraphNode
372
+ or type(vars(node).get("_edges")) is not dict
373
+ ):
374
+ raise pickle.UnpicklingError("File is not an edgeable database.")
375
+ for edge in node._edges.values():
376
+ if type(edge) is not GraphEdge:
377
+ raise pickle.UnpicklingError("File is not an edgeable database.")
378
+ edge._db = self
379
+ node._db = self
380
+
381
+ self._graph = graph
382
+ if properties is not None:
383
+ self._properties = properties
384
+
385
+ @GraphReadLock
386
+ def save(self):
387
+ """Save the database to the local filesystem.
388
+
389
+ The content is written to a temporary file in the same directory, which
390
+ then atomically replaces the database file."""
391
+
392
+ logger.debug("save to file '%s'", self._filename)
393
+ directory = os.path.dirname(self._filename) or os.curdir
394
+ fd, temp_filename = tempfile.mkstemp(
395
+ prefix=os.path.basename(self._filename) + ".", suffix=".tmp", dir=directory
396
+ )
397
+ try:
398
+ with os.fdopen(fd, "wb") as temp_file:
399
+ with gzip.GzipFile(fileobj=temp_file, mode="wb") as f:
400
+ _GraphPickler(f, protocol=4).dump(
401
+ (
402
+ _FORMAT_MARKER,
403
+ _FORMAT_VERSION,
404
+ self._graph,
405
+ self._properties,
406
+ )
407
+ )
408
+ temp_file.flush()
409
+ os.fsync(temp_file.fileno())
410
+
411
+ # keep the permissions of a database file which is being replaced
412
+ try:
413
+ mode = stat.S_IMODE(os.stat(self._filename).st_mode)
414
+ except FileNotFoundError:
415
+ mode = None
416
+ if mode is not None:
417
+ os.chmod(temp_filename, mode)
418
+
419
+ os.replace(temp_filename, self._filename)
420
+ except BaseException:
421
+ try:
422
+ os.unlink(temp_filename)
423
+ except OSError:
424
+ pass
425
+ raise
edgeable/edge.py ADDED
@@ -0,0 +1,112 @@
1
+ from edgeable.threadlock import GraphModifyLock
2
+
3
+
4
+ class GraphEdge:
5
+ """Class representing edges between nodes in the graph."""
6
+
7
+ def __init__(self, db, destination, source, properties):
8
+ self._db = db
9
+ self._destination_id = destination.get_id()
10
+ self._source_id = source.get_id()
11
+
12
+ self._properties = properties.copy()
13
+
14
+ def __eq__(self, other):
15
+ if isinstance(other, GraphEdge):
16
+ return (
17
+ self._source_id == other._source_id
18
+ and self._destination_id == other._destination_id
19
+ )
20
+ return False
21
+
22
+ def __hash__(self):
23
+ return hash((self._source_id, self._destination_id))
24
+
25
+ def __str__(self):
26
+ return f"{self._source_id}->{self._destination_id}"
27
+
28
+ def __repr__(self):
29
+ return f"{self._source_id}->{self._destination_id}"
30
+
31
+ def get_destination(self):
32
+ """Get the node which is the destination of this edge."""
33
+ return self._db._graph[self._destination_id]
34
+
35
+ def get_source(self):
36
+ """Get the node which is the source of this edge."""
37
+ return self._db._graph[self._source_id]
38
+
39
+ @GraphModifyLock
40
+ def set_property(self, key, value, directed=False):
41
+ """Set an edge property. If directed=False the property is mirrored
42
+ to an edge in the reverse direction."""
43
+ if type(key) is not str:
44
+ raise RuntimeError("Key must be a string")
45
+ self._properties[key] = value
46
+
47
+ if not directed:
48
+ if (
49
+ self._destination_id in self._db._graph
50
+ and self._source_id in self._db._graph[self._destination_id]._edges
51
+ ):
52
+ self._db._graph[self._destination_id]._edges[
53
+ self._source_id
54
+ ]._properties[key] = value
55
+
56
+ @GraphModifyLock
57
+ def set_properties(self, properties, directed=False):
58
+ """Set multiple properties from the provided dict. Properties not in the dict
59
+ are not removed. If directed=False the property is mirrored
60
+ to an edge in the reverse direction."""
61
+ if type(properties) is not dict:
62
+ raise RuntimeError("Properties must be a dict.")
63
+ for key in properties:
64
+ if type(key) is not str:
65
+ raise RuntimeError("Key must be a string")
66
+ self._properties = {**self._properties, **properties}
67
+ if not directed:
68
+ if (
69
+ self._destination_id in self._db._graph
70
+ and self._source_id in self._db._graph[self._destination_id]._edges
71
+ ):
72
+ destination = self._db._graph[self._destination_id]
73
+ destination._edges[self._source_id]._properties = {
74
+ **destination._edges[self._source_id]._properties,
75
+ **properties,
76
+ }
77
+
78
+ def get_property(self, key):
79
+ """Get the property value."""
80
+ if type(key) is not str:
81
+ raise RuntimeError("Key must be a string")
82
+ return self._properties[key] if self.has_property(key) else None
83
+
84
+ def get_properties(self):
85
+ """Get a dict containing all properties and values."""
86
+ return self._properties.copy()
87
+
88
+ def has_property(self, key):
89
+ """Boolean value indicating if the property is defined."""
90
+ if type(key) is not str:
91
+ raise RuntimeError("Key must be a string")
92
+ return key in self._properties
93
+
94
+ @GraphModifyLock
95
+ def delete_property(self, key):
96
+ """Delete a property if it is defined. Returns the previous value, or None."""
97
+ if type(key) is not str:
98
+ raise RuntimeError("Key must be a string.")
99
+ value = self.get_property(key)
100
+ if self.has_property(key):
101
+ del self._properties[key]
102
+ return value
103
+
104
+ @GraphModifyLock
105
+ def delete(self, directed=False):
106
+ """Delete this edge between nodes. If directed=False than any edge in
107
+ the reverse direction is also deleted. Returns a boolean indicating
108
+ if an edge was removed."""
109
+ source = self._db._graph.get(self._source_id)
110
+ if source is None:
111
+ return False
112
+ return source._detach_id(self._destination_id, directed)
edgeable/node.py ADDED
@@ -0,0 +1,430 @@
1
+ from collections import deque
2
+ import heapq
3
+ import logging
4
+ import math
5
+ import numbers
6
+
7
+ from edgeable.threadlock import GraphModifyLock, GraphReadLock
8
+ from edgeable.edge import GraphEdge
9
+
10
+ logger = logging.getLogger("edgeable")
11
+
12
+
13
+ def _validate_properties(properties):
14
+ if type(properties) is not dict:
15
+ raise RuntimeError("Properties must be a dict.")
16
+ for key in properties:
17
+ if type(key) is not str:
18
+ raise RuntimeError("Key must be a string.")
19
+
20
+
21
+ class GraphNode:
22
+ """Class representing nodes in the graph."""
23
+
24
+ def __init__(self, db, id):
25
+ self._db = db
26
+ self._id = id
27
+ self._properties = {}
28
+ self._edges = {}
29
+
30
+ def __eq__(self, other):
31
+ if isinstance(other, GraphNode):
32
+ return self.get_id() == other.get_id()
33
+ return False
34
+
35
+ def __str__(self):
36
+ return str(self._id)
37
+
38
+ def __repr__(self):
39
+ return str(self._id)
40
+
41
+ def __hash__(self):
42
+ return hash(self.get_id())
43
+
44
+ def get_id(self):
45
+ return self._id
46
+
47
+ def _is_member(self):
48
+ """Whether this exact object is the node stored in the graph."""
49
+ return self._db._graph.get(self._id) is self
50
+
51
+ @GraphModifyLock
52
+ def attach(self, destination, properties=None, directed=False):
53
+ """Attach this node to another node with an edge. Returns a boolean
54
+ indicating if a new edge was created. Optionally provided properties
55
+ will be set on the edge, whether it exists or is created new. Unless
56
+ directed=True then this is mirrored onto an edge in the reverse
57
+ direction. If a create edge callback cancels the operation nothing
58
+ is changed (in either direction) and False is returned."""
59
+
60
+ if not isinstance(destination, GraphNode):
61
+ raise RuntimeError("Destination must be an instance of GraphNode.")
62
+ if properties is None:
63
+ properties = {}
64
+ _validate_properties(properties)
65
+ if not self._is_member():
66
+ raise RuntimeError("Node does not exist in graph")
67
+ if destination is self:
68
+ return False
69
+ if (
70
+ not destination._is_member()
71
+ or destination._db._graph is not self._db._graph
72
+ ):
73
+ raise RuntimeError("Destination node does not exist in graph")
74
+
75
+ pairs = [(self, destination)]
76
+ if not directed:
77
+ pairs.append((destination, self))
78
+
79
+ # Build every edge which is missing, and let the callbacks see all
80
+ # of them before anything is changed, so that the operation is
81
+ # applied in both directions or not at all.
82
+ new_edges = {}
83
+ for source, target in pairs:
84
+ if target._id not in source._edges:
85
+ logger.debug(
86
+ "attach '%s' -> '%s' (%s)", source._id, target._id, properties
87
+ )
88
+ new_edges[source._id] = GraphEdge(
89
+ db=self._db,
90
+ source=source,
91
+ destination=target,
92
+ properties=properties,
93
+ )
94
+
95
+ # run create edge callbacks
96
+ cancel = False
97
+ for edge in new_edges.values():
98
+ for fn in list(self._db._on_create_edge.values()):
99
+ if fn(edge) is False:
100
+ cancel = True
101
+ if cancel:
102
+ return False
103
+
104
+ # a callback may have removed one of the nodes
105
+ if not self._is_member() or not destination._is_member():
106
+ return False
107
+
108
+ created = False
109
+ for source, target in pairs:
110
+ edge = source._edges.get(target._id)
111
+ if edge is None:
112
+ edge = new_edges.get(source._id)
113
+ if edge is None:
114
+ edge = GraphEdge(
115
+ db=self._db,
116
+ source=source,
117
+ destination=target,
118
+ properties=properties,
119
+ )
120
+ source._edges[target._id] = edge
121
+ created = True
122
+ else:
123
+ edge._properties.update(properties)
124
+
125
+ return created
126
+
127
+ def _detach_id(self, destination_id, directed):
128
+ """Remove the edge to the node with the provided id, and unless
129
+ directed the edge in the reverse direction. All or nothing: if a
130
+ delete edge callback cancels, neither is removed. Returns whether an
131
+ edge was removed. Callers must hold the modify lock."""
132
+ targets = []
133
+ edge = self._edges.get(destination_id)
134
+ if edge is not None:
135
+ targets.append((self, destination_id, edge))
136
+ if not directed:
137
+ other = self._db._graph.get(destination_id)
138
+ if other is not None and other is not self:
139
+ edge = other._edges.get(self._id)
140
+ if edge is not None:
141
+ targets.append((other, self._id, edge))
142
+ if not targets:
143
+ return False
144
+
145
+ # run delete edge callbacks
146
+ cancel = False
147
+ for owner, key, edge in targets:
148
+ logger.debug("detach '%s' from '%s'", owner._id, key)
149
+ for fn in list(self._db._on_delete_edge.values()):
150
+ if fn(edge) is False:
151
+ cancel = True
152
+ if cancel:
153
+ return False
154
+
155
+ removed = False
156
+ for owner, key, edge in targets:
157
+ # a callback may already have removed or replaced the edge
158
+ if owner._edges.get(key) is edge:
159
+ del owner._edges[key]
160
+ removed = True
161
+ return removed
162
+
163
+ @GraphModifyLock
164
+ def detach(self, destination=None, directed=False):
165
+ """Detach this node from another node. Returns a boolean
166
+ indicating if an edge was removed. If no destination is provided
167
+ then the node is detached fom all other nodes. Unless directed=True
168
+ then this is mirrored onto an edge in the reverse direction. If a
169
+ delete edge callback cancels, neither direction is removed."""
170
+
171
+ if destination is not None and not isinstance(destination, GraphNode):
172
+ raise RuntimeError("Destination must be an instance of GraphNode.")
173
+ if not self._is_member():
174
+ raise RuntimeError("Node does not exist in graph")
175
+
176
+ if destination is not None:
177
+ return self._detach_id(destination.get_id(), directed)
178
+
179
+ was_connected = False
180
+ for destination_id in list(self._edges):
181
+ if self._detach_id(destination_id, directed):
182
+ was_connected = True
183
+ return was_connected
184
+
185
+ @GraphModifyLock
186
+ def delete(self):
187
+ """Delete this node and all associated edges, including edges on
188
+ other nodes which point at this node. Returns a boolean indicating
189
+ if the node was deleted.
190
+
191
+ A delete node callback returning False cancels the deletion. Delete
192
+ edge callbacks are then called for every edge being removed, but
193
+ their return value is ignored: once the node is being deleted its
194
+ edges always go with it."""
195
+ graph = self._db._graph
196
+ if not self._is_member():
197
+ raise RuntimeError("Node does not exist in graph")
198
+
199
+ # run delete node callbacks
200
+ cancel = False
201
+ for fn in list(self._db._on_delete_node.values()):
202
+ if fn(self) is False:
203
+ cancel = True
204
+ if cancel or not self._is_member():
205
+ return False
206
+
207
+ # notify delete edge callbacks, for outgoing and incoming edges
208
+ doomed = list(self._edges.values())
209
+ for node in list(graph.values()):
210
+ if node is not self and self._id in node._edges:
211
+ doomed.append(node._edges[self._id])
212
+ for edge in doomed:
213
+ for fn in list(self._db._on_delete_edge.values()):
214
+ fn(edge)
215
+
216
+ # Scan again when removing, as callbacks may have added edges.
217
+ if not self._is_member():
218
+ return False
219
+ logger.debug("delete node '%s'", self._id)
220
+ for node in graph.values():
221
+ node._edges.pop(self._id, None)
222
+ self._edges.clear()
223
+ del graph[self._id]
224
+ return True
225
+
226
+ @GraphModifyLock
227
+ def set_property(self, key, value):
228
+ """Set a node property."""
229
+ if type(key) is not str:
230
+ raise RuntimeError("Key must be a string.")
231
+ self._properties[key] = value
232
+
233
+ @GraphModifyLock
234
+ def set_properties(self, properties):
235
+ """Set multiple properties from the provided dict. Properties not in the dict are not removed."""
236
+ _validate_properties(properties)
237
+ self._properties = {**self._properties, **properties}
238
+
239
+ def get_property(self, key):
240
+ """Get the property value."""
241
+ if type(key) is not str:
242
+ raise RuntimeError("Key must be a string.")
243
+ return self._properties.get(key)
244
+
245
+ def get_properties(self):
246
+ """Get a dict containing all properties and values."""
247
+ return self._properties.copy()
248
+
249
+ def has_property(self, key):
250
+ """Boolean value indicating if the property is defined."""
251
+ if type(key) is not str:
252
+ raise RuntimeError("Key must be a string.")
253
+ return key in self._properties
254
+
255
+ @GraphModifyLock
256
+ def delete_property(self, key):
257
+ """Delete a property if it is defined. Returns the previous value, or None."""
258
+ if type(key) is not str:
259
+ raise RuntimeError("Key must be a string.")
260
+ return self._properties.pop(key, None)
261
+
262
+ # Returns a list of edges
263
+ def get_edges(self, filter_fn=lambda edge: True):
264
+ """Return all edges, or edges which match the optional filter function."""
265
+ if not callable(filter_fn):
266
+ raise RuntimeError("Filter must be a function.")
267
+ if self._id not in self._db._graph:
268
+ raise RuntimeError("Node does not exist in graph")
269
+ return [edge for edge in list(self._edges.values()) if filter_fn(edge)]
270
+
271
+ # Returns an edge to the specified node
272
+ def get_edge(self, destination):
273
+ """Return the edge to the specified destination node, or None if one does not exist."""
274
+ if not isinstance(destination, GraphNode):
275
+ raise RuntimeError("Destination must be an instance of GraphNode.")
276
+ if self._id not in self._db._graph:
277
+ raise RuntimeError("Node does not exist in graph")
278
+ return self._edges.get(destination.get_id())
279
+
280
+ # Returns an edge to the specified node
281
+ def has_edge(self, destination):
282
+ """Boolean whether an edge exists to the specified destination node."""
283
+ if not isinstance(destination, GraphNode):
284
+ raise RuntimeError("Destination must be an instance of GraphNode.")
285
+ if self._id not in self._db._graph:
286
+ raise RuntimeError("Node does not exist in graph")
287
+ return destination.get_id() in self._edges
288
+
289
+ def _find_route(self, destination_id, skip_ids):
290
+ """Breadth first search for the shortest (fewest edges) route to the
291
+ node with the provided id, avoiding the provided node ids. Callers
292
+ must hold the read lock."""
293
+ graph = self._db._graph
294
+ if self._id not in graph:
295
+ raise RuntimeError("Node does not exist in graph")
296
+ if destination_id == self._id:
297
+ return [self]
298
+
299
+ previous = {self._id: None}
300
+ q = deque([self._id])
301
+ found = False
302
+ while q and not found:
303
+ node_id = q.popleft()
304
+ for next_id in list(graph[node_id]._edges):
305
+ if next_id in previous or next_id in skip_ids:
306
+ continue
307
+ if next_id not in graph:
308
+ # dangling edge, as may exist in files from older versions
309
+ continue
310
+ previous[next_id] = node_id
311
+ if next_id == destination_id:
312
+ found = True
313
+ break
314
+ q.append(next_id)
315
+ if not found:
316
+ return None
317
+
318
+ route = []
319
+ node_id = destination_id
320
+ while node_id != self._id:
321
+ route.append(graph[node_id])
322
+ node_id = previous[node_id]
323
+ route.append(self)
324
+ route.reverse()
325
+ return route
326
+
327
+ # Returns a collection of less-optimal routes. The number of
328
+ # these returned depends on the effort to find them, provided
329
+ # as a numeric parameter.
330
+ @GraphReadLock
331
+ def find_routes_to(self, destination, effort=5):
332
+ """Find multiple routes to the destination node, the shortest first,
333
+ returned as a list of routes. Alternatives are found by repeating
334
+ the search while avoiding up to `effort` of the intermediate nodes
335
+ of the routes already found, so the cost grows quickly with effort
336
+ on densely connected graphs."""
337
+ if not isinstance(destination, GraphNode):
338
+ raise RuntimeError("Destination must be an instance of GraphNode.")
339
+ destination_id = destination.get_id()
340
+ q = deque([()])
341
+ searched = {frozenset()}
342
+ routes = []
343
+ found = set()
344
+ while q:
345
+ skip = q.popleft()
346
+ if len(skip) > effort:
347
+ continue
348
+ route = self._find_route(destination_id, set(skip))
349
+ if route:
350
+ for step in route[1:-1]:
351
+ step_id = step.get_id()
352
+ if (
353
+ step_id != self._id
354
+ and step_id != destination_id
355
+ and step_id not in skip
356
+ ):
357
+ # the route found depends only on which nodes are
358
+ # skipped, not the order they were chosen in
359
+ next_skip = skip + (step_id,)
360
+ key = frozenset(next_skip)
361
+ if key not in searched:
362
+ searched.add(key)
363
+ q.append(next_skip)
364
+ key = tuple(step.get_id() for step in route)
365
+ if key not in found:
366
+ found.add(key)
367
+ routes.append(route)
368
+
369
+ return routes
370
+
371
+ @GraphReadLock
372
+ def find_route_to(self, destination, skip=None):
373
+ """Find a route across the graph from the current node to the
374
+ destination node, returned as an array of nodes. If no route
375
+ exists, returns None. Nodes in the optional skip collection
376
+ are not travelled through."""
377
+
378
+ if not isinstance(destination, GraphNode):
379
+ raise RuntimeError("Destination must be an instance of GraphNode.")
380
+ skip_ids = {node.get_id() for node in skip or () if isinstance(node, GraphNode)}
381
+ return self._find_route(destination.get_id(), skip_ids)
382
+
383
+ @GraphReadLock
384
+ def find_neighbors(self, distance=1, distance_fn=lambda edge: 1):
385
+ """Find all neighbors within the specified distance, nearest first.
386
+ The distance of an edge is 1 unless a distance function is provided,
387
+ which is called with an edge and must return a non-negative number."""
388
+
389
+ if not callable(distance_fn):
390
+ raise RuntimeError("Distance function must be a function.")
391
+ if not isinstance(distance, numbers.Real):
392
+ raise RuntimeError("Distance must be a number.")
393
+ graph = self._db._graph
394
+ if self._id not in graph:
395
+ raise RuntimeError("Node does not exist in graph")
396
+
397
+ # Dijkstra's algorithm. The counter keeps nodes at the same distance
398
+ # in the order in which they were discovered.
399
+ best = {self._id: 0}
400
+ done = set()
401
+ neighbors = []
402
+ counter = 0
403
+ heap = [(0, counter, self._id)]
404
+ while heap:
405
+ node_distance, _, node_id = heapq.heappop(heap)
406
+ if node_id in done:
407
+ continue
408
+ done.add(node_id)
409
+ if node_id != self._id:
410
+ neighbors.append(graph[node_id])
411
+ for next_id, edge in list(graph[node_id]._edges.items()):
412
+ if next_id in done or next_id not in graph:
413
+ # already settled, or a dangling edge
414
+ continue
415
+ edge_distance = distance_fn(edge)
416
+ if not isinstance(edge_distance, numbers.Real) or math.isnan(
417
+ edge_distance
418
+ ):
419
+ raise RuntimeError("Edge distance must be a number.")
420
+ if edge_distance < 0:
421
+ raise RuntimeError("Edge distance must not be negative.")
422
+ next_distance = node_distance + edge_distance
423
+ if next_distance <= distance and (
424
+ next_id not in best or next_distance < best[next_id]
425
+ ):
426
+ best[next_id] = next_distance
427
+ counter += 1
428
+ heapq.heappush(heap, (next_distance, counter, next_id))
429
+
430
+ return neighbors
edgeable/threadlock.py ADDED
@@ -0,0 +1,57 @@
1
+ """Locking for graph operations.
2
+
3
+ Every ``GraphDatabase`` owns one re-entrant lock (``db._lock``). Methods of the
4
+ database, and of the nodes and edges that belong to it, are decorated with
5
+ ``GraphReadLock`` or ``GraphModifyLock`` and hold that lock for the duration of
6
+ the call.
7
+
8
+ The lock is re-entrant, so code already running inside a locked call (an event
9
+ callback, a filter function, a distance function) may freely call any other
10
+ graph method, reading or modifying, on the same thread. Calls from different
11
+ threads are serialised: one thread at a time operates on a given database.
12
+ Unrelated databases do not block each other.
13
+
14
+ A reader/writer lock is deliberately not used. Allowing a filter function
15
+ running under a read lock to modify the graph means a read lock would have to
16
+ be upgradable to a write lock, and two readers upgrading at the same time
17
+ deadlock. A single re-entrant lock cannot.
18
+ """
19
+
20
+ import functools
21
+ import threading
22
+
23
+ # Used for decorated callables which are not bound to a database.
24
+ _global_lock = threading.RLock()
25
+
26
+
27
+ def _lock_for(args):
28
+ """Find the lock guarding a call: the lock of the database that the first
29
+ positional argument is, or belongs to, otherwise the module level lock."""
30
+ if args:
31
+ owner = args[0]
32
+ database = getattr(owner, "_db", owner)
33
+ lock = getattr(database, "_lock", None)
34
+ if hasattr(lock, "acquire") and hasattr(lock, "release"):
35
+ return lock
36
+ return _global_lock
37
+
38
+
39
+ def _locked(func):
40
+ @functools.wraps(func)
41
+ def inner(*args, **kwargs):
42
+ with _lock_for(args):
43
+ return func(*args, **kwargs)
44
+
45
+ return inner
46
+
47
+
48
+ def GraphModifyLock(func):
49
+ """Lock for modification. Operations on the same database from other
50
+ threads will block. Re-entrant on the owning thread."""
51
+ return _locked(func)
52
+
53
+
54
+ def GraphReadLock(func):
55
+ """Lock for reading. Operations on the same database from other
56
+ threads will block. Re-entrant on the owning thread."""
57
+ return _locked(func)
@@ -0,0 +1,189 @@
1
+ Metadata-Version: 2.4
2
+ Name: edgeable
3
+ Version: 0.2.0
4
+ Summary: Easy to use, in memory, persistable graph database.
5
+ Author-email: Lee Adcock <lee@katieandlee.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/LeeAdcock/edgeable
8
+ Project-URL: Issues, https://github.com/LeeAdcock/edgeable/issues
9
+ Project-URL: Changelog, https://github.com/LeeAdcock/edgeable/blob/master/CHANGELOG.md
10
+ Keywords: graph,database,in-memory
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Database
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest; extra == "dev"
23
+ Requires-Dist: coverage; extra == "dev"
24
+ Requires-Dist: black~=26.0; extra == "dev"
25
+ Requires-Dist: build; extra == "dev"
26
+ Requires-Dist: twine; extra == "dev"
27
+
28
+ <img src="https://raw.githubusercontent.com/LeeAdcock/edgeable/master/assets/logo.png" alt="Edgeable" width="300"/>
29
+
30
+ *Edgeable is an easy to use, in memory, persistable graph database. It is perfect for prototyping, exploring, and quick implementation in Python applications.* The library is written completely in Python, supporting 3.10+.
31
+
32
+ In Edgeable, graphs are made of nodes with a string or numeric identifier and can have any number of properties. Nodes are connected by directed or non-directed edges that can also have any number of properties. Additional convenience capabilities, like route detection through the graph, are built-in. Edgeable is thread safe for multi-threaded applications (operations on a database are serialized by a re-entrant, per-database lock) and easily handles databases with tens to hundreds of thousands of nodes.
33
+
34
+ ## Installation
35
+
36
+ The Edgeable database library can easily be installed with pip using `pip install edgeable`.
37
+
38
+ ## Examples
39
+
40
+ ### Create a graph instances and add nodes and edges
41
+
42
+ ```
43
+ from edgeable import GraphDatabase
44
+
45
+ graph = GraphDatabase()
46
+ A = graph.put_node('A', {'type': 'building'})
47
+ B = graph.put_node('B', {'type': 'classroom'})
48
+ A.attach(B, {'relationship': 'contains'})
49
+ ```
50
+
51
+ ### Loading from a csv file of edges
52
+
53
+ ```
54
+ from edgeable import GraphDatabase
55
+ import csv
56
+
57
+ graph = GraphDatabase()
58
+ with open('edges.csv') as csvfile:
59
+ reader = csv.reader(csvfile)
60
+ for row in reader:
61
+ node_a = graph.put_node(row[0].strip())
62
+ node_b = graph.put_node(row[1].strip())
63
+ node_a.attach(node_b)
64
+ ```
65
+
66
+ ### Write a csv file of edges
67
+
68
+ ```
69
+ with open('edges.csv', 'w') as csvfile:
70
+ writer = csv.writer(csvfile)
71
+ for node in graph.get_nodes():
72
+ for edge in node.get_edges():
73
+ writer.writerow([
74
+ edge.get_source().get_id(),
75
+ edge.get_destination().get_id()
76
+ ])
77
+ ```
78
+
79
+ ## Classes
80
+
81
+ ### Graph Class
82
+ The `GraphDatabase` class represents the entire graph. Instances of `GraphDatabase` provide the ability to retrieve and creates nodes, as well as save or load from the file system.
83
+
84
+ ##### Graph Constructor
85
+ The `GraphDatabase(filename="graph.db", properties=None)` constructor is used to create a new graph database instance. The file name used to persist the database can optionally be ovewritten. If a persisted database file already exists, it will be loaded.
86
+
87
+ An optional dict of database properties can be provided. If a persisted database file is loaded, the properties stored in it are loaded first and the provided properties are then set on top of them, so a provided value replaces a loaded value with the same key.
88
+
89
+ The `with` syntax can be used to initialize the graph and ensure it is saved once the block is exited.
90
+
91
+ ```
92
+ from edgeable import GraphDatabase
93
+
94
+ with GraphDatabase(filename="mygraph.db") as graph:
95
+ A = graph.put_node('A', {'type': 'building'})
96
+ B = graph.put_node('B', {'type': 'classroom'})
97
+ A.attach(B, {'relationship': 'contains'})
98
+ ```
99
+
100
+ ##### Graph Persistance
101
+ - `reload()` - Reload the graph from the file system. The persisted file is loaded automatically when the `GraphDatabase` instance is initialized, calling `reload()` is only neccessary to reload it, overwriting any changes to nodes, edges and database properties. Registered callbacks are kept, and apply to the reloaded nodes and edges.
102
+ - `save()` - Save the graph to the file system. When using the `with` syntax, this is called automatically. Save operations are done in a way to be thread-safe and avoid corruption if the application terminates during a write: the content is written and synced to a temporary file in the same directory, which then replaces the database file. The directory must already exist.
103
+
104
+ Nodes, edges, their properties and the database properties are persisted. Callbacks are not.
105
+
106
+ Property values (on the database, nodes and edges) must be made up of the following types to be persisted: `None`, `bool`, `int`, `float`, `complex`, `str`, `bytes`, `bytearray`, `list`, `tuple`, `dict`, `set`, `frozenset`, `range`, `slice`, `datetime.datetime`, `datetime.date`, `datetime.time`, `datetime.timedelta`, `datetime.timezone`, `decimal.Decimal`, `fractions.Fraction`, `uuid.UUID`, `collections.OrderedDict`, `collections.deque` and `collections.Counter`. Other values, such as instances of your own classes, can be held in memory but `save()` raises `pickle.PicklingError` for them and leaves the existing file untouched.
107
+
108
+ The file is a gzip compressed pickle. When loading, anything other than Edgeable's own classes and the types above is refused with `pickle.UnpicklingError` rather than imported, so loading a file does not run code embedded in it. This is a safeguard and not a guarantee: a crafted file can still contain a misleading or very large graph, so only load database files from sources you trust. Files written by earlier releases can still be loaded, and are written in the current format on the next `save()`; earlier releases cannot read files in the current format.
109
+
110
+ ##### Graph Nodes and Edges
111
+
112
+ - `put_node(id, properties={})` - Creates or retrieves the instance of `GraphNode` with the provided identifier. The optionally provided properties are set or updated on the node.
113
+ - `has_node(id)` - Taking a node identifier, returns a boolean indicating whether a node with that identifier exists in the database.
114
+ - `get_node(id)` - Taking a node identifier, return an instance of type `GraphNode` if it exists in the database. Returns `None` otherwise.
115
+ - `get_nodes(filter_fn=lambda node: True)` - Retrieve a list of `GraphNode` instances from the database. If the optional filter function is not provided, all nodes are returned, otherwise the filter function is used to return only matching nodes.
116
+ - `get_edges(edge_filter_fn=lambda edge: True, node_filter_fn=lambda node: True)` - Retrieve a list of `GraphEdge` instances from the database. If the optional filter functions are not provided, all edges are returned, otherwise only edges matching `edge_filter_fn` whose source node matches `node_filter_fn` are returned. Filters can be any callable.
117
+ - `get_node_count()` - Return the number of nodes in the database.
118
+ - `get_edge_count()` - Return the number of edges in the database.
119
+
120
+ ##### Graph Properties
121
+ Database properties are saved to and loaded from the file system together with the graph. Property keys must be strings.
122
+
123
+ - `set_property(key, value)` - Set a property on the database with the provided key and value.
124
+ - `set_properties(properties)` - Provide a dict to set multiple properites on the database.
125
+ - `get_property(key)` - Retrieve the database's property value for the provided key.
126
+ - `get_properties()` - Retrieve a `dict` containing all properties set on the database.
127
+ - `has_property(key)` - Returns a boolean indicating whether the property key is defined.
128
+ - `delete_property(key)` - Removes a property.
129
+
130
+ ##### Graph Callbacks
131
+
132
+ Event callbacks can be provided that will have the opportunity to process objects in the graph. Multiple callbacks can be defined for an event type. Each callbacks has an identifier, this can be specified when created or one will automatically be generated and returned. The id can be later used to overwrite or remove (set to `None`) the callback. Removing an id which is not registered does nothing. Callbacks can be any callable; anything else raises a `RuntimeError`.
133
+
134
+ - `on_create_node(fn, id=None)` - Sets or changes a callback that is called when a node is added to the graph.
135
+ - `on_create_edge(fn, id=None)` - Sets or changes a callback that is called when a edge is added to the graph.
136
+ - `on_delete_node(fn, id=None)` - Sets or changes a callback that is called when a node is deleted from the graph.
137
+ - `on_delete_edge(fn, id=None)` - Sets or changes a callback that is called when a edge is deleted from the graph.
138
+
139
+ Callback functions that return `False` will cancel the event; any other return value, including `None` and `0`, does not. Every callback registered for an event is called, even after one of them has cancelled it. Callbacks, like filter functions, can themselves read and modify the graph. Callback functions are not persisted with the database.
140
+
141
+ ### Node Class
142
+ The `GraphNode` class represent nodes and associated properties within the graph. Nodes can be connected through directed or non-directed edges.
143
+
144
+ - `delete()` - Delete the node from the database, removing any associated edges.
145
+
146
+ ##### Node Edges
147
+ - `attach(destination, properties={}, directed=False)` - Attach the current node to the destination node with a new edge. The optionally provided properties will be set on the edge, whether it exists or is created new. The releationship will be nondirectional unless `directed` is set to `True`. The method returns a boolean indicating if a new edge was created between the nodes.
148
+ - `detach(destination=None, directed=False)` - Detach the current node from the destination node, removing any connecting edge. If no destination is provided, all attached nodes are detached. If `directed` is set to `True`, then the edge is only removed in the current direction, any edge in the other directions is untouched. The method returns a boolean indicating if any edges were removed.
149
+ - `get_edges(filter_fn=lambda edge: True)` - Retrieve a list of `GraphEdge` instances from the database. If the optional filter function is not provided, all edges for the node are returned, otherwise the filter function is used to return only matching edges.
150
+ - `get_edge(destination)` - Retrieve the edge that leads from the current node to the provided destination node.
151
+ - `has_edge(destination)` - Returns a boolean indicating whether there is an edge from the current node to the destination node.
152
+
153
+ ##### Node Properties
154
+ - `set_property(key, value)` - Set a property on the node with the provided key and value.
155
+ - `set_properties(properties)` - Provide a dict to set multiple properites on the node.
156
+ - `get_property(key)` - Retrieve the node's property value for the provided key.
157
+ - `get_properties()` - Retrieve a `dict` containing all properties set on the node.
158
+ - `has_property(key)` - Returns a boolean indicating whether the property key is defined.
159
+ - `delete_property(key)` - Removes a property.
160
+
161
+ ##### Node Routes
162
+ - `find_route_to(end, skip=[])` - Find a shortest route (by number of edges) from the current node to the `end` node, returned as a list of `GraphNode` instances starting with the current node and ending with `end`. Returns `None` if there is no route. Nodes in the optional `skip` list are not travelled through.
163
+ - `find_routes_to(end, effort=5)` - Find alternative routes from the current node to the `end` node, returned as a list of routes with the shortest first. After the shortest route, further routes are found by searching again while avoiding nodes used by the routes found so far. `effort` bounds how many nodes may be avoided at once: higher values find more, less direct routes and take longer.
164
+
165
+ ##### Node Neighbors
166
+ - `find_neighbors(distance=1, distance_fn=lambda edge: 1)` - Find all nodes within a specified distance. By default, each edge is considered a distance of one. A custom function can be provided to provide a custom distance calculation.
167
+
168
+ ### Edge Class
169
+ The `GraphEdge` class representes the connections between `GraphNode` instances in the database. All methods assume edges are nondirected, so interactions with edges equally manipulates an edge in each direction between nodes. This behavior can be overridden for specific calls, resulting in the creation, modification, or deletion of directional edges.
170
+
171
+ - `get_destination()` - Retrieve the `GraphNode` instance that is the destination of this edge.
172
+ - `get_source()` - Retrieve the `GraphNode` instance that is the source of this edge.
173
+ - `delete(directed=False)` - Delete the edge from the database. If `directed` is `True` than only the edge in this direction is deleted.
174
+
175
+ ##### Edge Properties
176
+ - `set_property(key, value, directed=False)` - Set a property on the node with the provided key and value. If `directed` is `True` than the property is set only on the edge in this direction.
177
+ - `set_properties(properties, directed=False)` - Provide a dict to set multiple properites on the edge.
178
+ - `get_property(key)` - Retrieve the node's property value for the provided key.
179
+ - `get_properties()` - Retrieve a `dict` containing all properties set on the edge.
180
+ - `has_property(key)` - Returns a boolean indicating whether the property key is defined.
181
+ - `delete_property(key)` - Removes a property.
182
+
183
+ ## Resources
184
+
185
+ Build process: https://github.com/LeeAdcock/edgeable/actions
186
+
187
+ Changelog: [CHANGELOG.md](CHANGELOG.md)
188
+
189
+ PyPi: https://pypi.org/project/edgeable/
@@ -0,0 +1,9 @@
1
+ edgeable/__init__.py,sha256=_l_8aOLGnYIy54bxAA6VegseAACOWgQw50E5RjoqWYc,330
2
+ edgeable/database.py,sha256=80eIVyWPi3PU_Ca-8qF2xvLF_38cYDq-Xorf2rZVfTo,15114
3
+ edgeable/edge.py,sha256=pJdzUD5dY6x5rWVa4glTRUBUw9u8VQ5HNdgW3K8jpMU,4218
4
+ edgeable/node.py,sha256=pylnnKuBmx4F0_LhLqgvJtcxjwTxmprHVPgBOWQbB40,16919
5
+ edgeable/threadlock.py,sha256=FeOcREUmupYwkNRoP4lzGt393G8CsJ1NFaiJkkck51U,2004
6
+ edgeable-0.2.0.dist-info/METADATA,sha256=unIpIIcQYLETSXUWArw8yds83Ky_1WR_SaV5rohr_ns,13784
7
+ edgeable-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ edgeable-0.2.0.dist-info/top_level.txt,sha256=OxtLaKPQSJej2Dxbh5-7pUQ90tD5Cvhd9kS_Kp6XUDM,9
9
+ edgeable-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ edgeable