signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def update_window(turn_from, tick_from, turn_to, tick_to, updfun, branchd):
if turn_from in branchd:<EOL><INDENT>for past_state in branchd[turn_from][tick_from+<NUM_LIT:1>:]:<EOL><INDENT>updfun(*past_state)<EOL><DEDENT><DEDENT>for midturn in range(turn_from+<NUM_LIT:1>, turn_to):<EOL><INDENT>if midturn in branchd:<EOL><INDENT>for past_state in branchd[midturn][:]:<EOL><INDENT>updfun(*past_state)<EOL><DEDENT><DEDENT><DEDENT>if turn_to in branchd:<EOL><INDENT>for past_state in branchd[turn_to][:tick_to+<NUM_LIT:1>]:<EOL><INDENT>updfun(*past_state)<EOL><DEDENT><DEDENT>
Iterate over a window of time in ``branchd`` and call ``updfun`` on the values
f9011:m0
def update_backward_window(turn_from, tick_from, turn_to, tick_to, updfun, branchd):
if turn_from in branchd:<EOL><INDENT>for future_state in reversed(branchd[turn_from][:tick_from]):<EOL><INDENT>updfun(*future_state)<EOL><DEDENT><DEDENT>for midturn in range(turn_from-<NUM_LIT:1>, turn_to, -<NUM_LIT:1>):<EOL><INDENT>if midturn in branchd:<EOL><INDENT>for future_state in reversed(branchd[midturn][:]):<EOL><INDENT>updfun(*future_state)<EOL><DEDENT><DEDENT><DEDENT>if turn_to in branchd:<EOL><INDENT>for future_state in reversed(branchd[turn_to][tick_to+<NUM_LIT:1>:]):<EOL><INDENT>updfun(*future_state)<EOL><DEDENT><DEDENT>
Iterate backward over a window of time in ``branchd`` and call ``updfun`` on the values
f9011:m1
def within_history(rev, windowdict):
if not windowdict:<EOL><INDENT>return False<EOL><DEDENT>begin = windowdict._past[<NUM_LIT:0>][<NUM_LIT:0>] if windowdict._past elsewindowdict._future[-<NUM_LIT:1>][<NUM_LIT:0>]<EOL>end = windowdict._future[<NUM_LIT:0>][<NUM_LIT:0>] if windowdict._future elsewindowdict._past[-<NUM_LIT:1>][<NUM_LIT:0>]<EOL>return begin <= rev <= end<EOL>
Return whether the windowdict has history at the revision.
f9011:m2
def future(self, rev=None):
if rev is not None:<EOL><INDENT>self.seek(rev)<EOL><DEDENT>return WindowDictFutureView(self._future)<EOL>
Return a Mapping of items after the given revision. Default revision is the last one looked up.
f9011:c14:m0
def past(self, rev=None):
if rev is not None:<EOL><INDENT>self.seek(rev)<EOL><DEDENT>return WindowDictPastView(self._past)<EOL>
Return a Mapping of items at or before the given revision. Default revision is the last one looked up.
f9011:c14:m1
@cython.locals(rev=cython.int, past_end=cython.int, future_start=cython.int)<EOL><INDENT>def seek(self, rev):<DEDENT>
<EOL>if not self:<EOL><INDENT>return<EOL><DEDENT>if type(rev) is not int:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>past = self._past<EOL>future = self._future<EOL>if future:<EOL><INDENT>appender = past.append<EOL>popper = future.pop<EOL>future_start = future[-<NUM_LIT:1>][<NUM_LIT:0>]<EOL>while future_start <= rev:<EOL><INDENT>appender(popper())<EOL>if future:<EOL><INDENT>future_start = future[-<NUM_LIT:1>][<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>if past:<EOL><INDENT>popper = past.pop<EOL>appender = future.append<EOL>past_end = past[-<NUM_LIT:1>][<NUM_LIT:0>]<EOL>while past_end > rev:<EOL><INDENT>appender(popper())<EOL>if past:<EOL><INDENT>past_end = past[-<NUM_LIT:1>][<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>
Arrange the caches to help look up the given revision.
f9011:c14:m2
def rev_before(self, rev: int) -> int:
self.seek(rev)<EOL>if self._past:<EOL><INDENT>return self._past[-<NUM_LIT:1>][<NUM_LIT:0>]<EOL><DEDENT>
Return the latest past rev on which the value changed.
f9011:c14:m4
def rev_after(self, rev: int) -> int:
self.seek(rev)<EOL>if self._future:<EOL><INDENT>return self._future[-<NUM_LIT:1>][<NUM_LIT:0>]<EOL><DEDENT>
Return the earliest future rev on which the value will change.
f9011:c14:m5
def truncate(self, rev: int) -> None:
self.seek(rev)<EOL>self._keys.difference_update(map(get0, self._future))<EOL>self._future = []<EOL>if not self._past:<EOL><INDENT>self._beginning = None<EOL><DEDENT>
Delete everything after the given revision.
f9011:c14:m6
def __init__(<EOL>self, dbstring, connect_args, alchemy,<EOL>pack=None, unpack=None<EOL>):
dbstring = dbstring or '<STR_LIT>'<EOL>def alchem_init(dbstring, connect_args):<EOL><INDENT>from sqlalchemy import create_engine<EOL>from sqlalchemy.engine.base import Engine<EOL>from allegedb.alchemy import Alchemist<EOL>if isinstance(dbstring, Engine):<EOL><INDENT>self.engine = dbstring<EOL><DEDENT>else:<EOL><INDENT>self.engine = create_engine(<EOL>dbstring,<EOL>connect_args=connect_args<EOL>)<EOL><DEDENT>self.alchemist = Alchemist(self.engine)<EOL>self.transaction = self.alchemist.conn.begin()<EOL><DEDENT>def lite_init(dbstring, connect_args):<EOL><INDENT>from sqlite3 import connect, Connection<EOL>from json import load<EOL>self.strings = load(<EOL>open(os.path.join(self.path, '<STR_LIT>'))<EOL>)<EOL>if isinstance(dbstring, Connection):<EOL><INDENT>self.connection = dbstring<EOL><DEDENT>else:<EOL><INDENT>if dbstring.startswith('<STR_LIT>'):<EOL><INDENT>slashidx = dbstring.rindex('<STR_LIT:/>')<EOL>dbstring = dbstring[slashidx+<NUM_LIT:1>:]<EOL><DEDENT>self.connection = connect(dbstring)<EOL><DEDENT><DEDENT>if alchemy:<EOL><INDENT>try:<EOL><INDENT>alchem_init(dbstring, connect_args)<EOL><DEDENT>except ImportError:<EOL><INDENT>lite_init(dbstring, connect_args)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>lite_init(dbstring, connect_args)<EOL><DEDENT>self.globl = GlobalKeyValueStore(self)<EOL>self._branches = {}<EOL>self._nodevals2set = []<EOL>self._edgevals2set = []<EOL>self._graphvals2set = []<EOL>self._nodes2set = []<EOL>self._edges2set = []<EOL>self._btts = set()<EOL>if unpack is None:<EOL><INDENT>from ast import literal_eval as unpack<EOL><DEDENT>self.pack = pack or repr<EOL>self.unpack = unpack<EOL>
If ``alchemy`` is True and ``dbstring`` is a legit database URI, instantiate an Alchemist and start a transaction with it. Otherwise use sqlite3. You may pass an already created sqlalchemy :class:`Engine` object in place of ``dbstring`` if you wish. I'll still create my own transaction though.
f9012:c2:m0
def sql(self, stringname, *args, **kwargs):
if hasattr(self, '<STR_LIT>'):<EOL><INDENT>return getattr(self.alchemist, stringname)(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>s = self.strings[stringname]<EOL>return self.connection.cursor().execute(<EOL>s.format(**kwargs) if kwargs else s, args<EOL>)<EOL><DEDENT>
Wrapper for the various prewritten or compiled SQL calls. First argument is the name of the query, either a key in ``sqlite.json`` or a method name in ``allegedb.alchemy.Alchemist``. The rest of the arguments are parameters to the query.
f9012:c2:m1
def sqlmany(self, stringname, *args):
if hasattr(self, '<STR_LIT>'):<EOL><INDENT>return getattr(self.alchemist.many, stringname)(*args)<EOL><DEDENT>s = self.strings[stringname]<EOL>return self.connection.cursor().executemany(s, args)<EOL>
Wrapper for executing many SQL calls on my connection. First arg is the name of a query, either a key in the precompiled JSON or a method name in ``allegedb.alchemy.Alchemist``. Remaining arguments should be tuples of argument sequences to be passed to the query.
f9012:c2:m2
def have_graph(self, graph):
graph = self.pack(graph)<EOL>return bool(self.sql('<STR_LIT>', graph).fetchone()[<NUM_LIT:0>])<EOL>
Return whether I have a graph by this name.
f9012:c2:m3
def new_graph(self, graph, typ):
graph = self.pack(graph)<EOL>return self.sql('<STR_LIT>', graph, typ)<EOL>
Declare a new graph by this name of this type.
f9012:c2:m4
def del_graph(self, graph):
g = self.pack(graph)<EOL>self.sql('<STR_LIT>', g)<EOL>self.sql('<STR_LIT>', g)<EOL>self.sql('<STR_LIT>', g)<EOL>self.sql('<STR_LIT>', g)<EOL>self.sql('<STR_LIT>', g)<EOL>self.sql('<STR_LIT>', g)<EOL>
Delete all records to do with the graph
f9012:c2:m5
def graph_type(self, graph):
graph = self.pack(graph)<EOL>return self.sql('<STR_LIT>', graph).fetchone()[<NUM_LIT:0>]<EOL>
What type of graph is this?
f9012:c2:m6
def have_branch(self, branch):
return bool(self.sql('<STR_LIT>', branch).fetchone()[<NUM_LIT:0>])<EOL>
Return whether the branch thus named exists in the database.
f9012:c2:m7
def all_branches(self):
return self.sql('<STR_LIT>').fetchall()<EOL>
Return all the branch data in tuples of (branch, parent, parent_turn).
f9012:c2:m8
def global_get(self, key):
key = self.pack(key)<EOL>r = self.sql('<STR_LIT>', key).fetchone()<EOL>if r is None:<EOL><INDENT>raise KeyError("<STR_LIT>")<EOL><DEDENT>return self.unpack(r[<NUM_LIT:0>])<EOL>
Return the value for the given key in the ``globals`` table.
f9012:c2:m9
def global_items(self):
for (k, v) in self.sql('<STR_LIT>'):<EOL><INDENT>yield (self.unpack(k), self.unpack(v))<EOL><DEDENT>
Iterate over (key, value) pairs in the ``globals`` table.
f9012:c2:m10
def global_set(self, key, value):
(key, value) = map(self.pack, (key, value))<EOL>try:<EOL><INDENT>return self.sql('<STR_LIT>', key, value)<EOL><DEDENT>except IntegrityError:<EOL><INDENT>return self.sql('<STR_LIT>', value, key)<EOL><DEDENT>
Set ``key`` to ``value`` globally (not at any particular branch or revision)
f9012:c2:m11
def global_del(self, key):
key = self.pack(key)<EOL>return self.sql('<STR_LIT>', key)<EOL>
Delete the global record for the key.
f9012:c2:m12
def new_branch(self, branch, parent, parent_turn, parent_tick):
return self.sql('<STR_LIT>', branch, parent, parent_turn, parent_tick, parent_turn, parent_tick)<EOL>
Declare that the ``branch`` is descended from ``parent`` at ``parent_turn``, ``parent_tick``
f9012:c2:m13
def graph_val_dump(self):
self._flush_graph_val()<EOL>for (graph, key, branch, turn, tick, value) in self.sql('<STR_LIT>'):<EOL><INDENT>yield (<EOL>self.unpack(graph),<EOL>self.unpack(key),<EOL>branch,<EOL>turn,<EOL>tick,<EOL>self.unpack(value)<EOL>)<EOL><DEDENT>
Yield the entire contents of the graph_val table.
f9012:c2:m20
def _flush_graph_val(self):
if not self._graphvals2set:<EOL><INDENT>return<EOL><DEDENT>delafter = {}<EOL>for graph, key, branch, turn, tick, value in self._graphvals2set:<EOL><INDENT>if (graph, key, branch) in delafter:<EOL><INDENT>delafter[graph, key, branch] = min((<EOL>(turn, tick),<EOL>delafter[graph, key, branch]<EOL>))<EOL><DEDENT>else:<EOL><INDENT>delafter[graph, key, branch] = (turn, tick)<EOL><DEDENT><DEDENT>self.sqlmany(<EOL>'<STR_LIT>',<EOL>*((graph, key, branch, turn, turn, tick)<EOL>for ((graph, key, branch), (turn, tick)) in delafter.items())<EOL>)<EOL>self.sqlmany('<STR_LIT>', *self._graphvals2set)<EOL>self._graphvals2set = []<EOL>
Send all new and changed graph values to the database.
f9012:c2:m21
def exist_node(self, graph, node, branch, turn, tick, extant):
if (branch, turn, tick) in self._btts:<EOL><INDENT>raise TimeError<EOL><DEDENT>self._btts.add((branch, turn, tick))<EOL>self._nodes2set.append((self.pack(graph), self.pack(node), branch, turn, tick, extant))<EOL>
Declare that the node exists or doesn't. Inserts a new record or updates an old one, as needed.
f9012:c2:m26
def nodes_dump(self):
self._flush_nodes()<EOL>for (graph, node, branch, turn,tick, extant) in self.sql('<STR_LIT>'):<EOL><INDENT>yield (<EOL>self.unpack(graph),<EOL>self.unpack(node),<EOL>branch,<EOL>turn,<EOL>tick,<EOL>bool(extant)<EOL>)<EOL><DEDENT>
Dump the entire contents of the nodes table.
f9012:c2:m28
def node_val_dump(self):
self._flush_node_val()<EOL>for (<EOL>graph, node, key, branch, turn, tick, value<EOL>) in self.sql('<STR_LIT>'):<EOL><INDENT>yield (<EOL>self.unpack(graph),<EOL>self.unpack(node),<EOL>self.unpack(key),<EOL>branch,<EOL>turn,<EOL>tick,<EOL>self.unpack(value)<EOL>)<EOL><DEDENT>
Yield the entire contents of the node_val table.
f9012:c2:m29
def node_val_set(self, graph, node, key, branch, turn, tick, value):
if (branch, turn, tick) in self._btts:<EOL><INDENT>raise TimeError<EOL><DEDENT>self._btts.add((branch, turn, tick))<EOL>graph, node, key, value = map(self.pack, (graph, node, key, value))<EOL>self._nodevals2set.append((graph, node, key, branch, turn, tick, value))<EOL>
Set a key-value pair on a node at a specific branch and revision
f9012:c2:m31
def edges_dump(self):
self._flush_edges()<EOL>for (<EOL>graph, orig, dest, idx, branch, turn, tick, extant<EOL>) in self.sql('<STR_LIT>'):<EOL><INDENT>yield (<EOL>self.unpack(graph),<EOL>self.unpack(orig),<EOL>self.unpack(dest),<EOL>idx,<EOL>branch,<EOL>turn,<EOL>tick,<EOL>bool(extant)<EOL>)<EOL><DEDENT>
Dump the entire contents of the edges table.
f9012:c2:m33
def exist_edge(self, graph, orig, dest, idx, branch, turn, tick, extant):
if (branch, turn, tick) in self._btts:<EOL><INDENT>raise TimeError<EOL><DEDENT>self._btts.add((branch, turn, tick))<EOL>graph, orig, dest = map(self.pack, (graph, orig, dest))<EOL>self._edges2set.append((graph, orig, dest, idx, branch, turn, tick, extant))<EOL>
Declare whether or not this edge exists.
f9012:c2:m35
def edge_val_dump(self):
self._flush_edge_val()<EOL>for (<EOL>graph, orig, dest, idx, key, branch, turn, tick, value<EOL>) in self.sql('<STR_LIT>'):<EOL><INDENT>yield (<EOL>self.unpack(graph),<EOL>self.unpack(orig),<EOL>self.unpack(dest),<EOL>idx,<EOL>self.unpack(key),<EOL>branch,<EOL>turn,<EOL>tick,<EOL>self.unpack(value)<EOL>)<EOL><DEDENT>
Yield the entire contents of the edge_val table.
f9012:c2:m37
def edge_val_set(self, graph, orig, dest, idx, key, branch, turn, tick, value):
if (branch, turn, tick) in self._btts:<EOL><INDENT>raise TimeError<EOL><DEDENT>self._btts.add((branch, turn, tick))<EOL>graph, orig, dest, key, value = map(self.pack, (graph, orig, dest, key, value))<EOL>self._edgevals2set.append(<EOL>(graph, orig, dest, idx, key, branch, turn, tick, value)<EOL>)<EOL>
Set this key of this edge to this value.
f9012:c2:m39
def initdb(self):
if hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.alchemist.meta.create_all(self.engine)<EOL>if '<STR_LIT>' not in self.globl:<EOL><INDENT>self.globl['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' not in self.globl:<EOL><INDENT>self.globl['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>return<EOL><DEDENT>from sqlite3 import OperationalError<EOL>cursor = self.connection.cursor()<EOL>try:<EOL><INDENT>cursor.execute('<STR_LIT>')<EOL><DEDENT>except OperationalError:<EOL><INDENT>cursor.execute(self.strings['<STR_LIT>'])<EOL><DEDENT>if '<STR_LIT>' not in self.globl:<EOL><INDENT>self.globl['<STR_LIT>'] = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT>' not in self.globl:<EOL><INDENT>self.globl['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>if '<STR_LIT>' not in self.globl:<EOL><INDENT>self.globl['<STR_LIT>'] = <NUM_LIT:0><EOL><DEDENT>for table in (<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'<EOL>):<EOL><INDENT>try:<EOL><INDENT>cursor.execute('<STR_LIT>' + table + '<STR_LIT:;>')<EOL><DEDENT>except OperationalError:<EOL><INDENT>cursor.execute(self.strings['<STR_LIT>' + table])<EOL><DEDENT><DEDENT>
Create tables and indices as needed.
f9012:c2:m47
def flush(self):
self._flush_nodes()<EOL>self._flush_edges()<EOL>self._flush_graph_val()<EOL>self._flush_node_val()<EOL>self._flush_edge_val()<EOL>
Put all pending changes into the SQL transaction.
f9012:c2:m48
def commit(self):
self.flush()<EOL>if hasattr(self, '<STR_LIT>') and self.transaction.is_active:<EOL><INDENT>self.transaction.commit()<EOL><DEDENT>elif hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.connection.commit()<EOL><DEDENT>
Commit the transaction
f9012:c2:m49
def close(self):
self.commit()<EOL>if hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.connection.close()<EOL><DEDENT>
Commit the transaction, then close the connection
f9012:c2:m50
def setgraphval(delta, graph, key, val):
delta.setdefault(graph, {})[key] = val<EOL>
Change a delta to say that a graph stat was set to a certain value
f9013:m0
def setnode(delta, graph, node, exists):
delta.setdefault(graph, {}).setdefault('<STR_LIT>', {})[node] = bool(exists)<EOL>
Change a delta to say that a node was created or deleted
f9013:m1
def setnodeval(delta, graph, node, key, value):
if (<EOL>graph in delta and '<STR_LIT>' in delta[graph] and<EOL>node in delta[graph]['<STR_LIT>'] and not delta[graph]['<STR_LIT>'][node]<EOL>):<EOL><INDENT>return<EOL><DEDENT>delta.setdefault(graph, {}).setdefault('<STR_LIT>', {}).setdefault(node, {})[key] = value<EOL>
Change a delta to say that a node stat was set to a certain value
f9013:m2
def setedge(delta, is_multigraph, graph, orig, dest, idx, exists):
if is_multigraph(graph):<EOL><INDENT>delta.setdefault(graph, {}).setdefault('<STR_LIT>', {}).setdefault(orig, {}).setdefault(dest, {})[idx] = bool(exists)<EOL><DEDENT>else:<EOL><INDENT>delta.setdefault(graph, {}).setdefault('<STR_LIT>', {}).setdefault(orig, {})[dest] = bool(exists)<EOL><DEDENT>
Change a delta to say that an edge was created or deleted
f9013:m3
def setedgeval(delta, is_multigraph, graph, orig, dest, idx, key, value):
if is_multigraph(graph):<EOL><INDENT>if (<EOL>graph in delta and '<STR_LIT>' in delta[graph] and<EOL>orig in delta[graph]['<STR_LIT>'] and dest in delta[graph]['<STR_LIT>'][orig]<EOL>and idx in delta[graph]['<STR_LIT>'][orig][dest]<EOL>and not delta[graph]['<STR_LIT>'][orig][dest][idx]<EOL>):<EOL><INDENT>return<EOL><DEDENT>delta.setdefault(graph, {}).setdefault('<STR_LIT>', {}).setdefault(orig, {}).setdefault(dest, {}).setdefault(idx, {})[key] = value<EOL><DEDENT>else:<EOL><INDENT>if (<EOL>graph in delta and '<STR_LIT>' in delta[graph] and<EOL>orig in delta[graph]['<STR_LIT>'] and dest in delta[graph]['<STR_LIT>'][orig]<EOL>and not delta[graph]['<STR_LIT>'][orig][dest]<EOL>):<EOL><INDENT>return<EOL><DEDENT>delta.setdefault(graph, {}).setdefault('<STR_LIT>', {}).setdefault(orig, {}).setdefault(dest, {})[key] = value<EOL><DEDENT>
Change a delta to say that an edge stat was set to a certain value
f9013:m4
@contextmanager<EOL><INDENT>def advancing(self):<DEDENT>
if self._forward:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._forward = True<EOL>yield<EOL>self._forward = False<EOL>
A context manager for when time is moving forward one turn at a time. When used in LiSE, this means that the game is being simulated. It changes how the caching works, making it more efficient.
f9013:c4:m5
@contextmanager<EOL><INDENT>def batch(self):<DEDENT>
if self._no_kc:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._no_kc = True<EOL>yield<EOL>self._no_kc = False<EOL>
A context manager for when you're creating lots of state. Reads will be much slower in a batch, but writes will be faster. You *can* combine this with ``advancing`` but it isn't any faster.
f9013:c4:m6
def get_delta(self, branch, turn_from, tick_from, turn_to, tick_to):
from functools import partial<EOL>if turn_from == turn_to:<EOL><INDENT>return self.get_turn_delta(branch, turn_from, tick_from, tick_to)<EOL><DEDENT>delta = {}<EOL>graph_objs = self._graph_objs<EOL>if turn_to < turn_from:<EOL><INDENT>updater = partial(update_backward_window, turn_from, tick_from, turn_to, tick_to)<EOL>gvbranches = self._graph_val_cache.presettings<EOL>nbranches = self._nodes_cache.presettings<EOL>nvbranches = self._node_val_cache.presettings<EOL>ebranches = self._edges_cache.presettings<EOL>evbranches = self._edge_val_cache.presettings<EOL><DEDENT>else:<EOL><INDENT>updater = partial(update_window, turn_from, tick_from, turn_to, tick_to)<EOL>gvbranches = self._graph_val_cache.settings<EOL>nbranches = self._nodes_cache.settings<EOL>nvbranches = self._node_val_cache.settings<EOL>ebranches = self._edges_cache.settings<EOL>evbranches = self._edge_val_cache.settings<EOL><DEDENT>if branch in gvbranches:<EOL><INDENT>updater(partial(setgraphval, delta), gvbranches[branch])<EOL><DEDENT>if branch in nbranches:<EOL><INDENT>updater(partial(setnode, delta), nbranches[branch])<EOL><DEDENT>if branch in nvbranches:<EOL><INDENT>updater(partial(setnodeval, delta), nvbranches[branch])<EOL><DEDENT>if branch in ebranches:<EOL><INDENT>updater(partial(setedge, delta, lambda g: graph_objs[g].is_multigraph()), ebranches[branch])<EOL><DEDENT>if branch in evbranches:<EOL><INDENT>updater(partial(setedgeval, delta, lambda g: graph_objs[g].is_multigraph()), evbranches[branch])<EOL><DEDENT>return delta<EOL>
Get a dictionary describing changes to all graphs. The keys are graph names. Their values are dictionaries of the graphs' attributes' new values, with ``None`` for deleted keys. Also in those graph dictionaries are special keys 'node_val' and 'edge_val' describing changes to node and edge attributes, and 'nodes' and 'edges' full of booleans indicating whether a node or edge exists.
f9013:c4:m7
def get_turn_delta(self, branch=None, turn=None, tick_from=<NUM_LIT:0>, tick_to=None):
branch = branch or self.branch<EOL>turn = turn or self.turn<EOL>tick_to = tick_to or self.tick<EOL>delta = {}<EOL>if tick_from < tick_to:<EOL><INDENT>gvbranches = self._graph_val_cache.settings<EOL>nbranches = self._nodes_cache.settings<EOL>nvbranches = self._node_val_cache.settings<EOL>ebranches = self._edges_cache.settings<EOL>evbranches = self._edge_val_cache.settings<EOL><DEDENT>else:<EOL><INDENT>gvbranches = self._graph_val_cache.presettings<EOL>nbranches = self._nodes_cache.presettings<EOL>nvbranches = self._node_val_cache.presettings<EOL>ebranches = self._edges_cache.presettings<EOL>evbranches = self._edge_val_cache.presettings<EOL><DEDENT>if branch in gvbranches and turn in gvbranches[branch]:<EOL><INDENT>for graph, key, value in gvbranches[branch][turn][tick_from:tick_to]:<EOL><INDENT>if graph in delta:<EOL><INDENT>delta[graph][key] = value<EOL><DEDENT>else:<EOL><INDENT>delta[graph] = {key: value}<EOL><DEDENT><DEDENT><DEDENT>if branch in nbranches and turn in nbranches[branch]:<EOL><INDENT>for graph, node, exists in nbranches[branch][turn][tick_from:tick_to]:<EOL><INDENT>delta.setdefault(graph, {}).setdefault('<STR_LIT>', {})[node] = bool(exists)<EOL><DEDENT><DEDENT>if branch in nvbranches and turn in nvbranches[branch]:<EOL><INDENT>for graph, node, key, value in nvbranches[branch][turn][tick_from:tick_to]:<EOL><INDENT>if (<EOL>graph in delta and '<STR_LIT>' in delta[graph] and<EOL>node in delta[graph]['<STR_LIT>'] and not delta[graph]['<STR_LIT>'][node]<EOL>):<EOL><INDENT>continue<EOL><DEDENT>nodevd = delta.setdefault(graph, {}).setdefault('<STR_LIT>', {})<EOL>if node in nodevd:<EOL><INDENT>nodevd[node][key] = value<EOL><DEDENT>else:<EOL><INDENT>nodevd[node] = {key: value}<EOL><DEDENT><DEDENT><DEDENT>graph_objs = self._graph_objs<EOL>if branch in ebranches and turn in ebranches[branch]:<EOL><INDENT>for graph, orig, dest, idx, exists in ebranches[branch][turn][tick_from:tick_to]:<EOL><INDENT>if graph_objs[graph].is_multigraph():<EOL><INDENT>if (<EOL>graph in delta and '<STR_LIT>' in delta[graph] and<EOL>orig in delta[graph]['<STR_LIT>'] and dest in delta[graph]['<STR_LIT>'][orig]<EOL>and idx in delta[graph]['<STR_LIT>'][orig][dest]<EOL>and not delta[graph]['<STR_LIT>'][orig][dest][idx]<EOL>):<EOL><INDENT>continue<EOL><DEDENT>delta.setdefault(graph, {}).setdefault('<STR_LIT>', {}).setdefault(orig, {}).setdefault(dest, {})[idx] = bool(exists)<EOL><DEDENT>else:<EOL><INDENT>if (<EOL>graph in delta and '<STR_LIT>' in delta[graph] and<EOL>orig in delta[graph]['<STR_LIT>'] and dest in delta[graph]['<STR_LIT>'][orig]<EOL>and not delta[graph]['<STR_LIT>'][orig][dest]<EOL>):<EOL><INDENT>continue<EOL><DEDENT>delta.setdefault(graph, {}).setdefault('<STR_LIT>', {}).setdefault(orig, {})[dest] = bool(exists)<EOL><DEDENT><DEDENT><DEDENT>if branch in evbranches and turn in evbranches[branch]:<EOL><INDENT>for graph, orig, dest, idx, key, value in evbranches[branch][turn][tick_from:tick_to]:<EOL><INDENT>edgevd = delta.setdefault(graph, {}).setdefault('<STR_LIT>', {}).setdefault(orig, {}).setdefault(dest, {})<EOL>if graph_objs[graph].is_multigraph():<EOL><INDENT>if idx in edgevd:<EOL><INDENT>edgevd[idx][key] = value<EOL><DEDENT>else:<EOL><INDENT>edgevd[idx] = {key: value}<EOL><DEDENT><DEDENT>else:<EOL><INDENT>edgevd[key] = value<EOL><DEDENT><DEDENT><DEDENT>return delta<EOL>
Get a dictionary describing changes made on a given turn. If ``tick_to`` is not supplied, report all changes after ``tick_from`` (default 0). The keys are graph names. Their values are dictionaries of the graphs' attributes' new values, with ``None`` for deleted keys. Also in those graph dictionaries are special keys 'node_val' and 'edge_val' describing changes to node and edge attributes, and 'nodes' and 'edges' full of booleans indicating whether a node or edge exists. :arg branch: A branch of history; defaults to the current branch :arg turn: The turn in the branch; defaults to the current turn :arg tick_from: Starting tick; defaults to 0
f9013:c4:m8
def __init__(<EOL>self,<EOL>dbstring,<EOL>alchemy=True,<EOL>connect_args={},<EOL>validate=False<EOL>):
self._planning = False<EOL>self._forward = False<EOL>self._no_kc = False<EOL>if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.query = self.query_engine_cls(<EOL>dbstring, connect_args, alchemy,<EOL>getattr(self, '<STR_LIT>', None), getattr(self, '<STR_LIT>', None)<EOL>)<EOL><DEDENT>self.query.initdb()<EOL>self._obranch = '<STR_LIT>'<EOL>self._otick = self._oturn = <NUM_LIT:0><EOL>self._init_caches()<EOL>for (branch, parent, parent_turn, parent_tick, end_turn, end_tick) in self.query.all_branches():<EOL><INDENT>self._branches[branch] = (parent, parent_turn, parent_tick, end_turn, end_tick)<EOL>self._upd_branch_parentage(parent, branch)<EOL><DEDENT>for (branch, turn, end_tick, plan_end_tick) in self.query.turns_dump():<EOL><INDENT>self._turn_end[branch, turn] = end_tick<EOL>self._turn_end_plan[branch, turn] = plan_end_tick<EOL><DEDENT>if '<STR_LIT>' not in self._branches:<EOL><INDENT>self._branches['<STR_LIT>'] = None, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0><EOL><DEDENT>self._load_graphs()<EOL>self._init_load(validate=validate)<EOL>
Make a SQLAlchemy engine if possible, else a sqlite3 connection. In either case, begin a transaction. :arg dbstring: rfc1738 URL for a database connection. Unless it begins with "sqlite:///", SQLAlchemy will be required. :arg alchemy: Set to ``False`` to use the precompiled SQLite queries even if SQLAlchemy is available. :arg connect_args: Dictionary of keyword arguments to be used for the database connection. :arg validate: Whether to perform an integrity test on the data.
f9013:c4:m11
def __enter__(self):
return self<EOL>
Enable the use of the ``with`` keyword
f9013:c4:m14
def __exit__(self, *args):
self.close()<EOL>
Alias for ``close``
f9013:c4:m15
def is_parent_of(self, parent, child):
if parent == '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>if child == '<STR_LIT>':<EOL><INDENT>return False<EOL><DEDENT>if child not in self._branches:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>".format(<EOL>child<EOL>)<EOL>)<EOL><DEDENT>if self._branches[child][<NUM_LIT:0>] == parent:<EOL><INDENT>return True<EOL><DEDENT>return self.is_parent_of(parent, self._branches[child][<NUM_LIT:0>])<EOL>
Return whether ``child`` is a branch descended from ``parent`` at any remove.
f9013:c4:m16
def _copy_plans(self, branch_from, turn_from, tick_from):
plan_ticks = self._plan_ticks<EOL>plan_ticks_uncommitted = self._plan_ticks_uncommitted<EOL>time_plan = self._time_plan<EOL>plans = self._plans<EOL>branch = self.branch<EOL>where_cached = self._where_cached<EOL>last_plan = self._last_plan<EOL>turn_end_plan = self._turn_end_plan<EOL>for plan_id in self._branches_plans[branch_from]:<EOL><INDENT>_, start_turn, start_tick = plans[plan_id]<EOL>if start_turn > turn_from or (start_turn == turn_from and start_tick > tick_from):<EOL><INDENT>continue<EOL><DEDENT>incremented = False<EOL>for turn, ticks in list(plan_ticks[plan_id].items()):<EOL><INDENT>if turn < turn_from:<EOL><INDENT>continue<EOL><DEDENT>for tick in ticks:<EOL><INDENT>if turn == turn_from and tick < tick_from:<EOL><INDENT>continue<EOL><DEDENT>if not incremented:<EOL><INDENT>self._last_plan = last_plan = last_plan + <NUM_LIT:1><EOL>incremented = True<EOL>plans[last_plan] = branch, turn, tick<EOL><DEDENT>for cache in where_cached[branch_from, turn, tick]:<EOL><INDENT>data = cache.settings[branch_from][turn][tick]<EOL>value = data[-<NUM_LIT:1>]<EOL>key = data[:-<NUM_LIT:1>]<EOL>args = key + (branch, turn, tick, value)<EOL>if hasattr(cache, '<STR_LIT>'):<EOL><INDENT>cache.setdb(*args)<EOL><DEDENT>cache.store(*args, planning=True)<EOL>plan_ticks[last_plan][turn].append(tick)<EOL>plan_ticks_uncommitted.append((last_plan, turn, tick))<EOL>time_plan[branch, turn, tick] = last_plan<EOL>turn_end_plan[branch, turn] = tick<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
Collect all plans that are active at the given time and copy them to the current branch
f9013:c4:m19
def delete_plan(self, plan):
branch, turn, tick = self._btt()<EOL>to_delete = []<EOL>plan_ticks = self._plan_ticks[plan]<EOL>for trn, tcks in plan_ticks.items(): <EOL><INDENT>if turn == trn:<EOL><INDENT>for tck in tcks:<EOL><INDENT>if tck >= tick:<EOL><INDENT>to_delete.append((trn, tck))<EOL><DEDENT><DEDENT><DEDENT>elif trn > turn:<EOL><INDENT>to_delete.extend((trn, tck) for tck in tcks)<EOL><DEDENT><DEDENT>where_cached = self._where_cached<EOL>time_plan = self._time_plan<EOL>for trn, tck in to_delete:<EOL><INDENT>for cache in where_cached[branch, trn, tck]:<EOL><INDENT>cache.remove(branch, trn, tck)<EOL>if hasattr(cache, '<STR_LIT>'):<EOL><INDENT>cache.deldb(branch, trn, tck)<EOL><DEDENT><DEDENT>del where_cached[branch, trn, tck]<EOL>plan_ticks[trn].remove(tck)<EOL>if not plan_ticks[trn]:<EOL><INDENT>del plan_ticks[trn]<EOL><DEDENT>del time_plan[branch, trn, tck]<EOL><DEDENT>
Delete the portion of a plan that has yet to occur. :arg plan: integer ID of a plan, as given by ``with self.plan() as plan:``
f9013:c4:m20
def _btt(self):
return self._obranch, self._oturn, self._otick<EOL>
Return the branch, turn, and tick.
f9013:c4:m31
def _nbtt(self):
from .cache import HistoryError<EOL>branch, turn, tick = self._btt()<EOL>tick += <NUM_LIT:1><EOL>if (branch, turn) in self._turn_end_plan:<EOL><INDENT>if tick > self._turn_end_plan[branch, turn]:<EOL><INDENT>self._turn_end_plan[branch, turn] = tick<EOL><DEDENT>else:<EOL><INDENT>tick = self._turn_end_plan[branch, turn] + <NUM_LIT:1><EOL><DEDENT><DEDENT>self._turn_end_plan[branch, turn] = tick<EOL>if self._turn_end[branch, turn] > tick:<EOL><INDENT>raise HistoryError(<EOL>"<STR_LIT>".format(<EOL>turn, self._turn_end[branch, turn]<EOL>)<EOL>)<EOL><DEDENT>parent, turn_start, tick_start, turn_end, tick_end = self._branches[branch]<EOL>if turn < turn_end or (<EOL>turn == turn_end and tick < tick_end<EOL>):<EOL><INDENT>raise HistoryError(<EOL>"<STR_LIT>".format(turn_end, tick_end)<EOL>)<EOL><DEDENT>if self._planning:<EOL><INDENT>if (turn, tick) in self._plan_ticks[self._last_plan]:<EOL><INDENT>raise HistoryError(<EOL>"<STR_LIT>".format((branch, turn, tick))<EOL>)<EOL><DEDENT>self._plan_ticks[self._last_plan][turn].append(tick)<EOL>self._plan_ticks_uncommitted.append((self._last_plan, turn, tick))<EOL>self._time_plan[branch, turn, tick] = self._last_plan<EOL><DEDENT>self._otick = tick<EOL>return branch, turn, tick<EOL>
Increment the tick and return branch, turn, tick Unless we're viewing the past, in which case raise HistoryError. Idea is you use this when you want to advance time, which you can only do once per branch, turn, tick.
f9013:c4:m32
def commit(self):
self.query.globl['<STR_LIT>'] = self._obranch<EOL>self.query.globl['<STR_LIT>'] = self._oturn<EOL>self.query.globl['<STR_LIT>'] = self._otick<EOL>set_branch = self.query.set_branch<EOL>for branch, (parent, turn_start, tick_start, turn_end, tick_end) in self._branches.items():<EOL><INDENT>set_branch(branch, parent, turn_start, tick_start, turn_end, tick_end)<EOL><DEDENT>turn_end = self._turn_end<EOL>set_turn = self.query.set_turn<EOL>for (branch, turn), plan_end_tick in self._turn_end_plan.items():<EOL><INDENT>set_turn(branch, turn, turn_end[branch], plan_end_tick)<EOL><DEDENT>if self._plans_uncommitted:<EOL><INDENT>self.query.plans_insert_many(self._plans_uncommitted)<EOL><DEDENT>if self._plan_ticks_uncommitted:<EOL><INDENT>self.query.plan_ticks_insert_many(self._plan_ticks_uncommitted)<EOL><DEDENT>self.query.commit()<EOL>self._plans_uncommitted = []<EOL>self._plan_ticks_uncommitted = []<EOL>
Write the state of all graphs to the database and commit the transaction. Also saves the current branch, turn, and tick.
f9013:c4:m33
def close(self):
self.commit()<EOL>self.query.close()<EOL>
Write changes to database and close the connection
f9013:c4:m34
def new_graph(self, name, data=None, **attr):
self._init_graph(name, '<STR_LIT>')<EOL>g = Graph(self, name, data, **attr)<EOL>self._graph_objs[name] = g<EOL>return g<EOL>
Return a new instance of type Graph, initialized with the given data if provided. :arg name: a name for the graph :arg data: dictionary or NetworkX graph object providing initial state
f9013:c4:m36
def new_digraph(self, name, data=None, **attr):
self._init_graph(name, '<STR_LIT>')<EOL>dg = DiGraph(self, name, data, **attr)<EOL>self._graph_objs[name] = dg<EOL>return dg<EOL>
Return a new instance of type DiGraph, initialized with the given data if provided. :arg name: a name for the graph :arg data: dictionary or NetworkX graph object providing initial state
f9013:c4:m37
def new_multigraph(self, name, data=None, **attr):
self._init_graph(name, '<STR_LIT>')<EOL>mg = MultiGraph(self, name, data, **attr)<EOL>self._graph_objs[name] = mg<EOL>return mg<EOL>
Return a new instance of type MultiGraph, initialized with the given data if provided. :arg name: a name for the graph :arg data: dictionary or NetworkX graph object providing initial state
f9013:c4:m38
def new_multidigraph(self, name, data=None, **attr):
self._init_graph(name, '<STR_LIT>')<EOL>mdg = MultiDiGraph(self, name, data, **attr)<EOL>self._graph_objs[name] = mdg<EOL>return mdg<EOL>
Return a new instance of type MultiDiGraph, initialized with the given data if provided. :arg name: a name for the graph :arg data: dictionary or NetworkX graph object providing initial state
f9013:c4:m39
def get_graph(self, name):
if name in self._graph_objs:<EOL><INDENT>return self._graph_objs[name]<EOL><DEDENT>graphtypes = {<EOL>'<STR_LIT>': Graph,<EOL>'<STR_LIT>': DiGraph,<EOL>'<STR_LIT>': MultiGraph,<EOL>'<STR_LIT>': MultiDiGraph<EOL>}<EOL>type_s = self.query.graph_type(name)<EOL>if type_s not in graphtypes:<EOL><INDENT>raise GraphNameError(<EOL>"<STR_LIT>".format(name)<EOL>)<EOL><DEDENT>g = graphtypes[type_s](self, name)<EOL>self._graph_objs[name] = g<EOL>return g<EOL>
Return a graph previously created with ``new_graph``, ``new_digraph``, ``new_multigraph``, or ``new_multidigraph`` :arg name: name of an existing graph
f9013:c4:m40
def del_graph(self, name):
<EOL>self.get_graph(name)<EOL>self.query.del_graph(name)<EOL>if name in self._graph_objs:<EOL><INDENT>del self._graph_objs[name]<EOL><DEDENT>
Remove all traces of a graph's existence from the database :arg name: name of an existing graph
f9013:c4:m41
def _iter_parent_btt(self, branch=None, turn=None, tick=None, *, stoptime=None):
branch = branch or self.branch<EOL>trn = self.turn if turn is None else turn<EOL>tck = self.tick if tick is None else tick<EOL>yield branch, trn, tck<EOL>stopbranches = set()<EOL>if stoptime:<EOL><INDENT>if type(stoptime) is tuple:<EOL><INDENT>stopbranch = stoptime[<NUM_LIT:0>]<EOL>stopbranches.add(stopbranch)<EOL>stopbranches.update(self._branch_parents[stopbranch])<EOL><DEDENT>else:<EOL><INDENT>stopbranch = stoptime<EOL>stopbranches = self._branch_parents[stopbranch]<EOL><DEDENT><DEDENT>_branches = self._branches<EOL>while branch in _branches:<EOL><INDENT>(branch, trn, tck, _, _) = _branches[branch]<EOL>if branch in stopbranches and (<EOL>trn < stoptime[<NUM_LIT:1>] or (<EOL>trn == stoptime[<NUM_LIT:1>] and (<EOL>stoptime[<NUM_LIT:2>] is None or tck <= stoptime[<NUM_LIT:2>]<EOL>)<EOL>)<EOL>):<EOL><INDENT>return<EOL><DEDENT>yield branch, trn, tck<EOL><DEDENT>
Private use. Iterate over (branch, turn, tick), where the branch is a descendant of the previous (starting with whatever branch is presently active and ending at 'trunk'), and the turn is the latest revision in the branch that matters. :arg stoptime: This may be a branch, in which case iteration will stop instead of proceeding into that branch's parent; or it may be a triple, ``(branch, turn, tick)``, in which case iteration will stop instead of yielding any time before that. The tick may be ``None``, in which case iteration will stop instead of yielding the turn.
f9013:c4:m42
def _branch_descendants(self, branch=None):
branch = branch or self.branch<EOL>for (parent, (child, _, _, _, _)) in self._branches.items():<EOL><INDENT>if parent == branch:<EOL><INDENT>yield child<EOL><DEDENT><DEDENT>
Iterate over all branches immediately descended from the current one (or the given one, if available).
f9013:c4:m43
def unwrap(self):
return {<EOL>k: v.unwrap() if hasattr(v, '<STR_LIT>') and not hasattr(v, '<STR_LIT>') else v<EOL>for (k, v) in self.items()<EOL>}<EOL>
Return a deep copy of myself as a dict, and unwrap any wrapper objects in me.
f9014:c2:m1
def unwrap(self):
return [<EOL>v.unwrap() if hasattr(v, '<STR_LIT>') else v<EOL>for v in self<EOL>]<EOL>
Return a deep copy of myself as a list, and unwrap any wrapper objects in me.
f9014:c5:m1
def unwrap(self):
return {v.unwrap() if hasattr(v, '<STR_LIT>') and not hasattr(v, '<STR_LIT>') else v for v in self}<EOL>
Return a deep copy of myself as a set, and unwrap any wrapper objects in me.
f9014:c7:m5
def unwrap(self):
return [v.unwrap() if hasattr(v, '<STR_LIT>') and not hasattr(v, '<STR_LIT>') else v for v in self]<EOL>
Return a deep copy of myself as a list, and unwrap any wrapper objects in me.
f9014:c10:m6
def getatt(attribute_name):
from operator import attrgetter<EOL>return property(attrgetter(attribute_name))<EOL>
An easy way to make an alias
f9015:m0
def convert_to_networkx_graph(data, create_using=None, multigraph_input=False):
if isinstance(data, AllegedGraph):<EOL><INDENT>result = networkx.convert.from_dict_of_dicts(<EOL>data.adj,<EOL>create_using=create_using,<EOL>multigraph_input=data.is_multigraph()<EOL>)<EOL>result.graph = dict(data.graph)<EOL>result.node = {k: dict(v) for k, v in data.node.items()}<EOL>return result<EOL><DEDENT>return networkx.convert.to_networkx_graph(<EOL>data, create_using, multigraph_input<EOL>)<EOL>
Convert an AllegedGraph to the corresponding NetworkX graph type.
f9015:m1
def connect(self, func):
l = _alleged_receivers[id(self)]<EOL>if func not in l:<EOL><INDENT>l.append(func)<EOL><DEDENT>
Arrange to call this function whenever something changes here. The arguments will be this object, the key changed, and the value set.
f9015:c1:m0
def disconnect(self, func):
if id(self) not in _alleged_receivers:<EOL><INDENT>return<EOL><DEDENT>l = _alleged_receivers[id(self)]<EOL>try:<EOL><INDENT>l.remove(func)<EOL><DEDENT>except ValueError:<EOL><INDENT>return<EOL><DEDENT>if not l:<EOL><INDENT>del _alleged_receivers[id(self)]<EOL><DEDENT>
No longer call the function when something changes here.
f9015:c1:m1
def send(self, sender, **kwargs):
if id(self) not in _alleged_receivers:<EOL><INDENT>return<EOL><DEDENT>for func in _alleged_receivers[id(self)]:<EOL><INDENT>func(sender, **kwargs)<EOL><DEDENT>
Internal. Call connected functions.
f9015:c1:m2
def clear(self):
for k in list(self.keys()):<EOL><INDENT>del self[k]<EOL><DEDENT>
Delete everything
f9015:c1:m3
def update(self, other, **kwargs):
from itertools import chain<EOL>if hasattr(other, '<STR_LIT>'):<EOL><INDENT>other = other.items()<EOL><DEDENT>for (k, v) in chain(other, kwargs.items()):<EOL><INDENT>if (<EOL>k not in self or<EOL>self[k] != v<EOL>):<EOL><INDENT>self[k] = v<EOL><DEDENT><DEDENT>
Version of ``update`` that doesn't clobber the database so much
f9015:c1:m4
def _set_db(self, key, branch, turn, tick, value):
raise NotImplementedError<EOL>
Set a value for a key in the database (not the cache).
f9015:c2:m3
def _del_db(self, key, branch, turn, tick):
self._set_db(key, branch, turn, tick, None)<EOL>
Delete a key from the database (not the cache).
f9015:c2:m6
def __getitem__(self, key):
def wrapval(v):<EOL><INDENT>from functools import partial<EOL>from .wrap import DictWrapper, ListWrapper, SetWrapper<EOL>if isinstance(v, list):<EOL><INDENT>return ListWrapper(partial(self._get_cache_now, key), partial(self._set_cache_now, key), self, key)<EOL><DEDENT>elif isinstance(v, dict):<EOL><INDENT>return DictWrapper(partial(self._get_cache_now, key), partial(self._set_cache_now, key), self, key)<EOL><DEDENT>elif isinstance(v, set):<EOL><INDENT>return SetWrapper(partial(self._get_cache_now, key), partial(self._set_cache_now, key), self, key)<EOL><DEDENT>else:<EOL><INDENT>return v<EOL><DEDENT><DEDENT>return wrapval(self._get_cache_now(key))<EOL>
If key is 'graph', return myself as a dict, else get the present value of the key and return that
f9015:c2:m8
def __setitem__(self, key, value):
if value is None:<EOL><INDENT>raise ValueError(<EOL>"<STR_LIT>"<EOL>)<EOL><DEDENT>branch, turn, tick = self.db._nbtt()<EOL>try:<EOL><INDENT>if self._get_cache(key, branch, turn, tick) != value:<EOL><INDENT>self._set_cache(key, branch, turn, tick, value)<EOL><DEDENT><DEDENT>except KeyError:<EOL><INDENT>self._set_cache(key, branch, turn, tick, value)<EOL><DEDENT>self._set_db(key, branch, turn, tick, value)<EOL>self.send(self, key=key, value=value)<EOL>
Set key=value at the present branch and revision
f9015:c2:m10
def __init__(self, graph, node):
super().__init__()<EOL>self.graph = graph<EOL>self.node = node<EOL>self.db = db = graph.db<EOL>node_val_cache = db._node_val_cache<EOL>graphn = graph.name<EOL>btt = db._btt<EOL>self._iter_stuff = (node_val_cache.iter_entity_keys, graphn, node, btt)<EOL>self._cache_contains_stuff = (node_val_cache.contains_key, graphn, node)<EOL>self._len_stuff = (node_val_cache.count_entity_keys, graphn, node, btt)<EOL>self._get_cache_stuff = (node_val_cache.retrieve, graphn, node)<EOL>self._set_db_stuff = (db.query.node_val_set, graphn, node)<EOL>self._set_cache_stuff = (db._node_val_cache.store, graphn, node)<EOL>
Store name and graph
f9015:c4:m1
def __init__(self, graph, orig, dest, idx=<NUM_LIT:0>):
super().__init__()<EOL>self.graph = graph<EOL>self.db = db = graph.db<EOL>self.orig = orig<EOL>self.dest = dest<EOL>self.idx = idx<EOL>edge_val_cache = db._edge_val_cache<EOL>graphn = graph.name<EOL>btt = db._btt<EOL>self._iter_stuff = (edge_val_cache.iter_entity_keys, graphn, orig, dest, idx, btt)<EOL>self._cache_contains_stuff = (edge_val_cache.contains_key, graphn, orig, dest, idx)<EOL>self._len_stuff = (edge_val_cache.count_entity_keys, graphn, orig, dest, idx, btt)<EOL>self._get_cache_stuff = (edge_val_cache.retrieve, graphn, orig, dest, idx)<EOL>self._set_db_stuff = (db.query.edge_val_set, graphn, orig, dest, idx)<EOL>self._set_cache_stuff = (edge_val_cache.store, graphn, orig, dest, idx)<EOL>
Store the graph, the names of the nodes, and the index. For non-multigraphs the index is always 0.
f9015:c5:m1
def __iter__(self):
return self.db._nodes_cache.iter_entities(<EOL>self.graph.name, *self.db._btt()<EOL>)<EOL>
Iterate over the names of the nodes
f9015:c6:m1
def __contains__(self, node):
return self.db._nodes_cache.contains_entity(<EOL>self.graph.name, node, *self.db._btt()<EOL>)<EOL>
Return whether the node exists presently
f9015:c6:m3
def __len__(self):
return self.db._nodes_cache.count_entities(<EOL>self.graph.name, *self.db._btt()<EOL>)<EOL>
How many nodes exist right now?
f9015:c6:m4
def __getitem__(self, node):
if node not in self:<EOL><INDENT>raise KeyError<EOL><DEDENT>return self.db._get_node(self.graph, node)<EOL>
If the node exists at present, return it, else throw KeyError
f9015:c6:m5
def __setitem__(self, node, dikt):
created = False<EOL>db = self.db<EOL>graph = self.graph<EOL>gname = graph.name<EOL>if not db._node_exists(gname, node):<EOL><INDENT>created = True<EOL>db._exist_node(gname, node, True)<EOL><DEDENT>n = db._get_node(graph, node)<EOL>n.clear()<EOL>n.update(dikt)<EOL>if created:<EOL><INDENT>self.send(self, node_name=node, exists=True)<EOL><DEDENT>
Only accept dict-like values for assignment. These are taken to be dicts of node attributes, and so, a new GraphNodeMapping.Node is made with them, perhaps clearing out the one already there.
f9015:c6:m6
def __delitem__(self, node):
if node not in self:<EOL><INDENT>raise KeyError("<STR_LIT>")<EOL><DEDENT>branch, turn, tick = self.db._nbtt()<EOL>self.db.query.exist_node(<EOL>self.graph.name,<EOL>node,<EOL>branch, turn, tick,<EOL>False<EOL>)<EOL>self.db._nodes_cache.store(<EOL>self.graph.name,<EOL>node,<EOL>branch, turn, tick,<EOL>False<EOL>)<EOL>key = (self.graph.name, node)<EOL>if node in self.db._node_objs:<EOL><INDENT>del self.db._node_objs[key]<EOL><DEDENT>self.send(self, node_name=node, exists=False)<EOL>
Indicate that the given node no longer exists
f9015:c6:m7
def __eq__(self, other):
if not hasattr(other, '<STR_LIT>'):<EOL><INDENT>return False<EOL><DEDENT>if self.keys() != other.keys():<EOL><INDENT>return False<EOL><DEDENT>for k in self.keys():<EOL><INDENT>if dict(self[k]) != dict(other[k]):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
Compare values cast into dicts. As I serve the custom Node class, rather than dicts like networkx normally would, the normal comparison operation would not let you compare my nodes with regular networkx nodes-that-are-dicts. So I cast my nodes into dicts for this purpose, and cast the other argument's nodes the same way, in case it is a db graph.
f9015:c6:m8
def __eq__(self, other):
if not hasattr(other, '<STR_LIT>'):<EOL><INDENT>return False<EOL><DEDENT>if self.keys() != other.keys():<EOL><INDENT>return False<EOL><DEDENT>for k in self.keys():<EOL><INDENT>if dict(self[k]) != dict(other[k]):<EOL><INDENT>return False<EOL><DEDENT><DEDENT>return True<EOL>
Compare dictified versions of the edge mappings within me. As I serve custom Predecessor or Successor classes, which themselves serve the custom Edge class, I wouldn't normally be comparable to a networkx adjacency dictionary. Converting myself and the other argument to dicts allows the comparison to work anyway.
f9015:c7:m2
def __init__(self, container, orig):
super().__init__(container.graph)<EOL>self.container = container<EOL>self.orig = orig<EOL>
Store container and node
f9015:c8:m2
def __iter__(self):
return self.db._edges_cache.iter_successors(<EOL>self.graph.name,<EOL>self.orig,<EOL>*self.db._btt()<EOL>)<EOL>
Iterate over node IDs that have an edge with my orig
f9015:c8:m3
def __contains__(self, dest):
orig, dest = self._order_nodes(dest)<EOL>return self.db._edges_cache.has_successor(<EOL>self.graph.name,<EOL>orig,<EOL>dest,<EOL>*self.db._btt()<EOL>)<EOL>
Is there an edge leading to ``dest`` at the moment?
f9015:c8:m4
def __len__(self):
return self.db._edges_cache.count_successors(<EOL>self.graph.name,<EOL>self.orig,<EOL>*self.db._btt()<EOL>)<EOL>
How many nodes touch an edge shared with my orig?
f9015:c8:m5
def __getitem__(self, dest):
if dest not in self:<EOL><INDENT>raise KeyError("<STR_LIT>".format(self.orig, dest))<EOL><DEDENT>orig, dest = self._order_nodes(dest)<EOL>return self.db._get_edge(self.graph, orig, dest, <NUM_LIT:0>)<EOL>
Get the edge between my orig and the given node
f9015:c8:m7
def __setitem__(self, dest, value):
real_dest = dest<EOL>orig, dest = self._order_nodes(dest)<EOL>created = dest not in self<EOL>if orig not in self.graph.node:<EOL><INDENT>self.graph.add_node(orig)<EOL><DEDENT>if dest not in self.graph.node:<EOL><INDENT>self.graph.add_node(dest)<EOL><DEDENT>branch, turn, tick = self.db._nbtt()<EOL>self.db.query.exist_edge(<EOL>self.graph.name,<EOL>orig,<EOL>dest,<EOL><NUM_LIT:0>,<EOL>branch, turn, tick,<EOL>True<EOL>)<EOL>self.db._edges_cache.store(<EOL>self.graph.name,<EOL>orig,<EOL>dest,<EOL><NUM_LIT:0>,<EOL>branch, turn, tick,<EOL>True<EOL>)<EOL>e = self[real_dest]<EOL>e.clear()<EOL>e.update(value)<EOL>if created:<EOL><INDENT>self.send(self, orig=orig, dest=dest, idx=<NUM_LIT:0>, exists=True)<EOL><DEDENT>
Set the edge between my orig and the given dest to the given value, a mapping.
f9015:c8:m8
def __delitem__(self, dest):
branch, turn, tick = self.db._nbtt()<EOL>orig, dest = self._order_nodes(dest)<EOL>self.db.query.exist_edge(<EOL>self.graph.name,<EOL>orig,<EOL>dest,<EOL><NUM_LIT:0>,<EOL>branch, turn, tick,<EOL>False<EOL>)<EOL>self.db._edges_cache.store(<EOL>self.graph.name,<EOL>orig,<EOL>dest,<EOL><NUM_LIT:0>,<EOL>branch, turn, tick,<EOL>None<EOL>)<EOL>self.send(self, orig=orig, dest=dest, idx=<NUM_LIT:0>, exists=False)<EOL>
Remove the edge between my orig and the given dest
f9015:c8:m9
def clear(self):
for dest in list(self):<EOL><INDENT>del self[dest]<EOL><DEDENT>
Delete every edge with origin at my orig
f9015:c8:m11
def __setitem__(self, key, val):
if key in self:<EOL><INDENT>sucs = self[key]<EOL>created = False<EOL><DEDENT>else:<EOL><INDENT>sucs = self._cache[key] = self.Successors(self, key)<EOL>created = True<EOL><DEDENT>sucs.clear()<EOL>sucs.update(val)<EOL>if created:<EOL><INDENT>self.send(self, key=key, val=val)<EOL><DEDENT>
Wipe out any edges presently emanating from orig and replace them with those described by val
f9015:c9:m1
def __delitem__(self, key):
self[key].clear()<EOL>del self._cache[key]<EOL>self.send(self, key=key, val=None)<EOL>
Wipe out edges emanating from orig
f9015:c9:m2
def __getitem__(self, dest):
if dest not in self:<EOL><INDENT>raise KeyError("<STR_LIT>")<EOL><DEDENT>if dest not in self._cache:<EOL><INDENT>self._cache[dest] = self.Predecessors(self, dest)<EOL><DEDENT>return self._cache[dest]<EOL>
Return a Predecessors instance for edges ending at the given node
f9015:c11:m1