Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,23 @@

import alabaster

class Mock(mock.MagicMock):
@classmethod
def __getattr__(cls, name):
return Mock()

MOCK_MODULES = [
'choice',
'queueing_tool.queues.choice',
'matplotlib',
'networkx',
'numpy',
'numpy.random',
'priority_queue',
'queueing_tool.network.priority_queue',
'pygraphviz'
]
sys.modules.update((mod_name, mock.Mock()) for mod_name in MOCK_MODULES)
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)


# If extensions (or modules to document with autodoc) are in another directory,
Expand Down
18 changes: 9 additions & 9 deletions queueing_tool/graph/graph_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@



def _test_graph(g) :
"""A function that makes sure ``g`` is either a
def _test_graph(graph):
"""A function that makes sure ``graph`` is either a
:any:`networkx.DiGraph` or a string or file object to one.

Parameters
----------
g : A **str** or a :any:`networkx.DiGraph`.
graph : A **str** or a :any:`networkx.DiGraph`.

Returns
-------
Expand All @@ -19,18 +19,18 @@ def _test_graph(g) :
Raises
------
TypeError
Raises a :exc:`~TypeError` if ``g`` cannot be turned into a
Raises a :exc:`~TypeError` if ``graph`` cannot be turned into a
:any:`networkx.DiGraph`.
"""
if not isinstance(g, QueueNetworkDiGraph):
if not isinstance(graph, QueueNetworkDiGraph):
try:
g = QueueNetworkDiGraph(g)
graph = QueueNetworkDiGraph(graph)
except (nx.NetworkXError, TypeError):
raise TypeError("Couldn't turn g into a graph.")
return g
raise TypeError("Couldn't turn graph into a DiGraph.")
return graph


def graph2dict(g, return_dict_of_dict=True) :
def graph2dict(g, return_dict_of_dict=True):
"""Takes a graph and returns an adjacency list.

Parameters
Expand Down
8 changes: 4 additions & 4 deletions queueing_tool/graph/graph_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def _calculate_distance(latlon1, latlon2):
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat / 2.)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon / 2.))**2
c = 2 * np.pi * R * np.arctan2( np.sqrt(a), np.sqrt(1-a) ) / 180.
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1-a)) / 180.
return c


Expand Down Expand Up @@ -206,7 +206,7 @@ def minimal_random_graph(nVertices, seed=None, **kwargs):
for k in range(nVertices-1):
for j in range(k+1, nVertices):
v = points[k] - points[j]
edges.append( (k, j, v[0]**2 + v[1]**2) )
edges.append((k, j, v[0]**2 + v[1]**2))

mytype = [('n1', int), ('n2', int), ('distance', np.float)]
edges = np.array(edges, dtype=mytype)
Expand All @@ -215,7 +215,7 @@ def minimal_random_graph(nVertices, seed=None, **kwargs):

g = nx.Graph()

for n1, n2, d in edges:
for n1, n2, dummy in edges:
unionF.union(n1, n2)
g.add_edge(n1, n2)
if unionF.nClusters == 1:
Expand Down Expand Up @@ -389,7 +389,7 @@ def set_types_rank(g, rank, pType2=0.1, pType3=0.1, seed=None, **kwargs):
ind_g_dist[min_g_dist == tmp] = v

ind_g_dist = np.unique(ind_g_dist)
fcqs = set(ind_g_dist[:min( (nFCQ, len(ind_g_dist)) )])
fcqs = set(ind_g_dist[:min(nFCQ, len(ind_g_dist))])
dests = set(dests)
g.new_vertex_property('loop_type')

Expand Down
2 changes: 1 addition & 1 deletion queueing_tool/graph/graph_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def _calculate_distance(latlon1, latlon2):
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * (np.sin(dlon/2))**2
c = 2 * np.pi * R * np.arctan2( np.sqrt(a), np.sqrt(1-a) ) / 180
c = 2 * np.pi * R * np.arctan2(np.sqrt(a), np.sqrt(1-a)) / 180
return c


Expand Down
16 changes: 8 additions & 8 deletions queueing_tool/network/queue_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -895,7 +895,7 @@ def get_queue_data(self, queues=None, edge=None, edge_type=None, return_header=F
dat = self.edge2queue[q].fetch_data()

if len(dat) > 0:
data = np.vstack( (data, dat) )
data = np.vstack((data, dat))

if return_header:
return data, 'arrival,service,departure,num_queued,num_total,q_id'
Expand Down Expand Up @@ -1119,7 +1119,7 @@ def set_transitions(self, mat):
msg = ("Matrix is the wrong shape, should "
"be {0} x {1}.").format(self.nV, self.nV)
raise ValueError(msg)
elif not np.allclose(np.sum(mat[non_terminal,:], axis=1), 1):
elif not np.allclose(np.sum(mat[non_terminal, :], axis=1), 1):
msg = "Sum of transition probabilities at a vertex was not 1."
raise ValueError(msg)
elif (mat < 0).any():
Expand Down Expand Up @@ -1292,7 +1292,7 @@ def simulate(self, n=1, t=None):
"Call '.initialize()' first.")
raise QueueingToolError(msg)
if t is None:
for k in range(n):
for dummy in range(n):
self._simulate_next_event(slow=False)
else:
now = self._t
Expand All @@ -1315,7 +1315,7 @@ def _simulate_next_event(self, slow=True):
self._qkey = q1k
self.nEvents += 1

if event == 2 : # This is a departure
if event == 2: # This is a departure
e2 = q1._departures[0].desired_destination(self, q1.edge)
q2 = self.edge2queue[e2]
q2k = q2._key()
Expand Down Expand Up @@ -1371,7 +1371,7 @@ def _simulate_next_event(self, slow=True):

if slow:
self._update_graph_colors(qedge=q1.edge)
self._prev_edge = q1.edge
self._prev_edge = q1.edge

new_q1k = q1._key()
if new_q1k[0] < np.infty:
Expand Down Expand Up @@ -1520,7 +1520,7 @@ def transitions(self, return_matrix=True):
probability ``0.326``, etc.
"""
if return_matrix:
mat = np.zeros( (self.nV, self.nV) )
mat = np.zeros((self.nV, self.nV))
for v in self.g.nodes():
ind = [e[1] for e in self.g.out_edges(v)]
mat[v, ind] = self._route_probs[v]
Expand All @@ -1534,7 +1534,7 @@ def transitions(self, return_matrix=True):


def _update_all_colors(self):
do = [True for v in range(self.nV)]
do = [True for v in range(self.nV)]
for q in self.edge2queue:
e = q.edge[:2]
v = q.edge[1]
Expand All @@ -1555,7 +1555,7 @@ def _update_all_colors(self):


def _update_vertex_color(self, v):
ee = (v, v)
ee = (v, v)
ee_is_edge = self.g.is_edge(ee)
eei = self.g.edge_index[ee] if ee_is_edge else 0

Expand Down
2 changes: 1 addition & 1 deletion queueing_tool/queues/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class Agent(object):
Specifies how many times an agent has been blocked by a finite
capacity queue.
"""
def __init__(self, agent_id=(0,0), **kwargs):
def __init__(self, agent_id=(0, 0), **kwargs):
self.agent_id = agent_id
self.blocked = 0
self._time = 0 # agents arrival or departure time
Expand Down
8 changes: 4 additions & 4 deletions queueing_tool/queues/queue_extentions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ResourceAgent(Agent):
a resource to that queue by increasing the number of
servers there by one; the ``ResourceAgent`` is then deleted.
"""
def __init__(self, agent_id=(0,0)):
def __init__(self, agent_id=(0, 0)):
super(ResourceAgent, self).__init__(agent_id)
self._has_resource = False
self._had_resource = False
Expand Down Expand Up @@ -252,10 +252,10 @@ class InfoAgent(Agent):
**kwargs :
Any arguments to pass to :class:`.Agent`.
"""
def __init__(self, agent_id=(0,0), net_size=1, **kwargs):
def __init__(self, agent_id=(0, 0), net_size=1, **kwargs):
super(InfoAgent, self).__init__(agent_id, **kwargs)

self.stats = np.zeros((net_size, 3), np.int32 )
self.stats = np.zeros((net_size, 3), np.int32)
self.net_data = np.ones((net_size, 3)) * -1

def __repr__(self):
Expand Down Expand Up @@ -376,7 +376,7 @@ def next_event(self):

def clear(self):
super(InfoQueue, self).clear()
self.networking( len(self.net_data) )
self.networking(len(self.net_data))


def __deepcopy__(self, memo):
Expand Down
24 changes: 12 additions & 12 deletions queueing_tool/queues/queue_servers.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,9 @@ def poisson_random_measure(rate, rate_max, t):
:doi:`10.1007/978-0-387-87859-1`
"""
scale = 1.0 / rate_max
t = t + exponential(scale)
t = t + exponential(scale)
while rate_max * uniform() > rate(t):
t = t + exponential(scale)
t = t + exponential(scale)
return t


Expand Down Expand Up @@ -275,7 +275,7 @@ class QueueServer(object):
}

def __init__(self, nServers=1, arrival_f=lambda t: t + exponential(1),
service_f=lambda t: t + exponential(0.9), edge=(0,0,0,1),
service_f=lambda t: t + exponential(0.9), edge=(0, 0, 0, 1),
AgentFactory=Agent, collect_data=False, active_cap=infty,
deactive_t=infty, colors=None, seed=None,
coloring_sensitivity=2, **kwargs):
Expand All @@ -296,7 +296,7 @@ def __init__(self, nServers=1, arrival_f=lambda t: t + exponential(1),

self.arrival_f = arrival_f
self.service_f = service_f
self.AgentFactory = AgentFactory
self.AgentFactory = AgentFactory
self.collect_data = collect_data
self.active_cap = active_cap
self.deactive_t = deactive_t
Expand All @@ -306,11 +306,11 @@ def __init__(self, nServers=1, arrival_f=lambda t: t + exponential(1),
self._departures = [inftyAgent] # A list of departing agents.
self._nArrivals = 0
self._oArrivals = 0
self._nTotal = 0 # The number of agents scheduled to arrive + nSystem
self._nTotal = 0 # The number of agents scheduled to arrive + nSystem
self._active = False
self._current_t = 0 # The time of the last event.
self._time = infty # The time of the next event.
self._next_ct = 0 # The next time an arrival from outside the network can arrive.
self._current_t = 0 # The time of the last event.
self._time = infty # The time of the next event.
self._next_ct = 0 # The next time an arrival from outside the network can arrive.
self.coloring_sensitivity = coloring_sensitivity

if isinstance(seed, numbers.Integral):
Expand Down Expand Up @@ -617,9 +617,9 @@ def next_event(self):
if self.collect_data:
b = 0 if self.nSystem <= self.nServers else 1
if arrival.agent_id not in self.data:
self.data[arrival.agent_id] = [[arrival._time, 0, 0, len(self.queue)+b, self.nSystem]]
self.data[arrival.agent_id] = [[arrival._time, 0, 0, len(self.queue) + b, self.nSystem]]
else:
self.data[arrival.agent_id].append([arrival._time, 0, 0, len(self.queue)+b, self.nSystem])
self.data[arrival.agent_id].append([arrival._time, 0, 0, len(self.queue) + b, self.nSystem])

arrival.queue_action(self, 0)

Expand Down Expand Up @@ -695,7 +695,7 @@ def set_nServers(self, n):
raise TypeError(the_str.format(str(self)))
elif n <= 0:
the_str = "n must be a positive integer or infinity.\n{0}"
raise ValueError( the_str.format(str(self)) )
raise ValueError(the_str.format(str(self)))
else:
self.nServers = n

Expand Down Expand Up @@ -762,7 +762,7 @@ def simulate(self, n=1, t=None, nA=None, nD=None):

"""
if t is None and nD is None and nA is None:
for k in range(n):
for dummy in range(n):
self.next_event()
elif t is not None:
then = self._current_t + t
Expand Down
30 changes: 15 additions & 15 deletions queueing_tool/union_find.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class UnionFind(object) :
class UnionFind(object):
"""The union-find data structure with union by rank and path compression.

The UnionFind data structure is a collection of objects that supports
Expand All @@ -18,14 +18,14 @@ class UnionFind(object) :
nClusters : int
The number of clusters contained in the data-structure.
"""
def __init__(self, S) :
def __init__(self, S):
self._leader = dict((s, s) for s in S)
self._size = dict((s, 1) for s in S)
self._rank = dict((s, 0) for s in S)
self.nClusters = len(self._leader)


def __repr__(self) :
def __repr__(self):
return "UnionFind: contains {0} clusters.".format(self.nClusters)


Expand All @@ -46,7 +46,7 @@ def size(self, s):
return self._size[leader]


def find(self, s) :
def find(self, s):
"""Locates the leader of the set to which the element ``s`` belongs.

Parameters
Expand All @@ -62,18 +62,18 @@ def find(self, s) :
pSet = [s]
parent = self._leader[s]

while parent != self._leader[parent] :
while parent != self._leader[parent]:
pSet.append(parent)
parent = self._leader[parent]

if len(pSet) > 1 :
for a in pSet :
if len(pSet) > 1:
for a in pSet:
self._leader[a] = parent

return parent


def union(self, a, b) :
def union(self, a, b):
"""Merges the set that contains ``a`` with the set that contains ``b``.

Parameters
Expand All @@ -82,14 +82,14 @@ def union(self, a, b) :
Two objects whose sets are to be merged.
"""
s1, s2 = self.find(a), self.find(b)
if s1 != s2 :
if s1 != s2:
r1, r2 = self._rank[s1], self._rank[s2]
if r2 > r1 :
if r2 > r1:
r1, r2 = r2, r1
s1, s2 = s2, s1
if r1 == r2 :
self._rank[s1] += 1
if r1 == r2:
self._rank[s1] += 1

self._leader[s2] = s1
self._size[s1] += self._size[s2]
self.nClusters -= 1
self._leader[s2] = s1
self._size[s1] += self._size[s2]
self.nClusters -= 1
2 changes: 1 addition & 1 deletion tests/test_graph_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def test_set_types_random(self):
props = (np.array(mat).sum(1) + 0.0) / len(non_loops)
ps = np.array([pType[k] for k in eType])

self.assertTrue(np.allclose(props , ps, atol=0.01))
self.assertTrue(np.allclose(props, ps, atol=0.01))

prob[-1] = 2
pType = {eType[k] : prob[k] for k in range(nT)}
Expand Down
Loading