diff --git a/docs/conf.py b/docs/conf.py index 4f57bb3..7c097e1 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -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, diff --git a/queueing_tool/graph/graph_functions.py b/queueing_tool/graph/graph_functions.py index d1310a8..6635b6c 100644 --- a/queueing_tool/graph/graph_functions.py +++ b/queueing_tool/graph/graph_functions.py @@ -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 ------- @@ -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 diff --git a/queueing_tool/graph/graph_generation.py b/queueing_tool/graph/graph_generation.py index d0238a6..223d75d 100644 --- a/queueing_tool/graph/graph_generation.py +++ b/queueing_tool/graph/graph_generation.py @@ -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 @@ -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) @@ -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: @@ -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') diff --git a/queueing_tool/graph/graph_preparation.py b/queueing_tool/graph/graph_preparation.py index 21193cc..0caa65c 100644 --- a/queueing_tool/graph/graph_preparation.py +++ b/queueing_tool/graph/graph_preparation.py @@ -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 diff --git a/queueing_tool/network/queue_network.py b/queueing_tool/network/queue_network.py index a6771c1..e94a80d 100644 --- a/queueing_tool/network/queue_network.py +++ b/queueing_tool/network/queue_network.py @@ -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' @@ -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(): @@ -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 @@ -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() @@ -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: @@ -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] @@ -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] @@ -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 diff --git a/queueing_tool/queues/agents.py b/queueing_tool/queues/agents.py index 10d207e..24c45ba 100644 --- a/queueing_tool/queues/agents.py +++ b/queueing_tool/queues/agents.py @@ -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 diff --git a/queueing_tool/queues/queue_extentions.py b/queueing_tool/queues/queue_extentions.py index e242c96..4757be5 100644 --- a/queueing_tool/queues/queue_extentions.py +++ b/queueing_tool/queues/queue_extentions.py @@ -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 @@ -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): @@ -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): diff --git a/queueing_tool/queues/queue_servers.py b/queueing_tool/queues/queue_servers.py index 60c3a18..6102474 100644 --- a/queueing_tool/queues/queue_servers.py +++ b/queueing_tool/queues/queue_servers.py @@ -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 @@ -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): @@ -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 @@ -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): @@ -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) @@ -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 @@ -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 diff --git a/queueing_tool/union_find.py b/queueing_tool/union_find.py index 69c558d..15a3a83 100644 --- a/queueing_tool/union_find.py +++ b/queueing_tool/union_find.py @@ -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 @@ -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) @@ -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 @@ -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 @@ -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 diff --git a/tests/test_graph_generation.py b/tests/test_graph_generation.py index 70ffe36..15e186f 100644 --- a/tests/test_graph_generation.py +++ b/tests/test_graph_generation.py @@ -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)} diff --git a/tests/test_network.py b/tests/test_network.py index d3ad9ae..0a3b229 100644 --- a/tests/test_network.py +++ b/tests/test_network.py @@ -42,16 +42,16 @@ def test_QueueNetwork_accounting(self): nEvents = 2500 ans = np.zeros(nEvents, bool) na = np.zeros(self.qn.nE, int) - for q in self.qn.edge2queue : + for q in self.qn.edge2queue: na[q.edge[2]] = len(q._arrivals) + len(q._departures) + len(q.queue) - 2 for k in range(nEvents): ans[k] = (self.qn.nAgents == na).all() self.qn.simulate(n=1) - for q in self.qn.edge2queue : + for q in self.qn.edge2queue: na[q.edge[2]] = len(q._arrivals) + len(q._departures) + len(q.queue) - 2 - self.assertTrue( ans.all() ) + self.assertTrue(ans.all()) def test_QueueNetwork_add_arrival(self): @@ -62,12 +62,12 @@ def test_QueueNetwork_add_arrival(self): mat = qt.generate_transition_matrix(g) qn.set_transitions(mat) - qn.initialize(edges=(0,1)) - qn.start_collecting_data(edge=[(1,2), (1,3)]) + qn.initialize(edges=(0, 1)) + qn.start_collecting_data(edge=[(1, 2), (1, 3)]) qn.simulate(150000) - data = qn.get_queue_data(edge=[(1,2), (1,3)]) + data = qn.get_queue_data(edge=[(1, 2), (1, 3)]) e0, e1 = qn.out_edges[1] p0 = np.sum(data[:, 5] == e0, dtype=float) / data.shape[0] @@ -75,8 +75,8 @@ def test_QueueNetwork_add_arrival(self): trans = qn.transitions(False) - self.assertAlmostEqual( trans[1][2], p0, 2) - self.assertAlmostEqual( trans[1][3], p1, 2) + self.assertAlmostEqual(trans[1][2], p0, 2) + self.assertAlmostEqual(trans[1][3], p1, 2) def test_QueueNetwork_animate(self): @@ -127,12 +127,12 @@ def test_QueueNetwork_closedness(self): nEvents = 2500 ans = np.zeros(nEvents, bool) na = np.zeros(self.qn.nE, int) - for q in self.qn.edge2queue : + for q in self.qn.edge2queue: na[q.edge[2]] = len(q._arrivals) + len(q._departures) + len(q.queue) - 2 for k in range(nEvents): ans[k] = np.sum(self.qn.nAgents) >= np.sum(na) - for q in self.qn.edge2queue : + for q in self.qn.edge2queue: na[q.edge[2]] = len(q._arrivals) + len(q._departures) + len(q.queue) - 2 self.qn.simulate(n=1) @@ -143,7 +143,7 @@ def test_QueueNetwork_closedness(self): def test_QueueNetwork_copy(self): g = nx.random_geometric_graph(100, 0.2).to_directed() - g = qt.set_types_random(g, proportions={k : 0.2 for k in range(1,6)}) + g = qt.set_types_random(g, proportions={k : 0.2 for k in range(1, 6)}) q_cls = { 1: qt.LossQueue, 2: qt.QueueServer, @@ -170,7 +170,7 @@ def test_QueueNetwork_copy(self): ans = [] for k, q in enumerate(qn2.edge2queue): - if stamp[k][1] != q.time : + if stamp[k][1] != q.time: ans.append(q.time != qn.edge2queue[k].time) self.assertTrue(np.array(ans).all()) @@ -220,20 +220,20 @@ def test_QueueNetwork_get_agent_data(self): self.qn.simulate(n=20000) data = self.qn.get_agent_data() - dat0 = data[(1,0)] + dat0 = data[(1, 0)] - a = dat0[:,0] - b = dat0[dat0[:,1] > 0, 1] - c = dat0[dat0[:,2] > 0, 2] + a = dat0[:, 0] + b = dat0[dat0[:, 1] > 0, 1] + c = dat0[dat0[:, 2] > 0, 2] a.sort() b.sort() c.sort() - self.assertTrue( (a == dat0[:,0]).all() ) - self.assertTrue( (b == dat0[dat0[:,1] > 0, 1]).all() ) - self.assertTrue( (c == dat0[dat0[:,2] > 0, 2]).all() ) - self.assertTrue( (dat0[1:, 0] == dat0[dat0[:,2] > 0, 2]).all() ) + self.assertTrue((a == dat0[:, 0]).all()) + self.assertTrue((b == dat0[dat0[:, 1] > 0, 1]).all()) + self.assertTrue((c == dat0[dat0[:, 2] > 0, 2]).all()) + self.assertTrue((dat0[1:, 0] == dat0[dat0[:, 2] > 0, 2]).all()) def test_QueueNetwork_get_queue_data(self): @@ -249,21 +249,21 @@ def test_QueueNetwork_get_queue_data(self): qn.simulate(n=k) data = qn.get_queue_data() - self.assertTrue( data.shape == (k, 6) ) + self.assertTrue(data.shape == (k, 6)) qn.stop_collecting_data() qn.clear_data() ans = np.array([q.data == {} for q in qn.edge2queue]) - self.assertTrue( ans.all() ) + self.assertTrue(ans.all()) def test_QueueNetwork_greedy_routing(self): - lam = np.random.randint(1,10) + 0.0 + lam = np.random.randint(1, 10) + 0.0 rho = np.random.uniform(0.75, 1) nSe = np.random.randint(1, 10) mu = lam / (3 * rho * nSe) - arr = lambda t : t + np.random.exponential(1/lam) - ser = lambda t : t + np.random.exponential(1/mu) + arr = lambda t: t + np.random.exponential(1 / lam) + ser = lambda t: t + np.random.exponential(1 / mu) adj = { 0 : {1: {'edge_type': 1}}, @@ -305,7 +305,7 @@ def test_QueueNetwork_greedy_routing(self): ans[c] = d0 == d1 c += 1 - self.assertTrue( ans.all() ) + self.assertTrue(ans.all()) def test_QueueNetwork_initialize_Error(self): @@ -341,7 +341,7 @@ def test_QueueNetwork_initialization(self): ans = np.array([q.edge[2] for q in self.qn.edge2queue if q.active]) ans.sort() - self.assertTrue( (ans == k).all() ) + self.assertTrue((ans == k).all()) # Single edge as edge k = np.random.randint(0, self.qn.nE) @@ -368,7 +368,7 @@ def test_QueueNetwork_initialization(self): self.qn.initialize(edges=es) ans = [q.edge[2] for q in self.qn.edge2queue if q.active] - self.assertTrue( (ans == k).all() ) + self.assertTrue((ans == k).all()) # Multple edges as edges k = np.unique(np.random.randint(0, self.qn.nE, 5)) @@ -377,7 +377,7 @@ def test_QueueNetwork_initialization(self): self.qn.initialize(edges=es) ans = [q.edge[2] for q in self.qn.edge2queue if q.active] - self.assertTrue( (ans == k).all() ) + self.assertTrue((ans == k).all()) # Single edge_type k = np.random.randint(1, 4) @@ -418,7 +418,7 @@ def test_QueueNetwork_max_agents(self): ans[k] = np.sum(self.qn.nAgents) <= self.qn.max_agents self.qn.simulate(n=1) - self.assertTrue( ans.all() ) + self.assertTrue(ans.all()) def test_QueueNetwork_properties(self): @@ -470,7 +470,7 @@ def test_QueueNetwork_simulate(self): qn.max_agents = 2000 qn.simulate(t=t0) - self.assertTrue( qn.current_time > t0 ) + self.assertTrue(qn.current_time > t0) def test_QueueNetwork_simulate_error(self): @@ -552,7 +552,7 @@ def test_QueueNetwork_sorting(self): self.qn.simulate(n=1) ans[k] = (tmp == self.qn._qkey[0]) - self.assertTrue( ans.all() ) + self.assertTrue(ans.all()) def test_QueueNetwork_transitions(self): @@ -569,23 +569,23 @@ def test_QueueNetwork_transitions(self): mat = self.qn.transitions() tra = mat[v, [e[1] for e in self.qn.g.out_edges(v)]] - self.assertTrue( (tra == trans).all() ) + self.assertTrue((tra == trans).all()) tra = self.qn.transitions(return_matrix=False) tra = np.array([tra[v][e[1]] for e in self.qn.g.out_edges(v)]) - self.assertTrue( (tra == trans).all() ) + self.assertTrue((tra == trans).all()) mat = qt.generate_transition_matrix(self.g) self.qn.set_transitions(mat) tra = self.qn.transitions() - self.assertTrue( np.allclose(tra, mat) ) + self.assertTrue(np.allclose(tra, mat)) mat = qt.generate_transition_matrix(self.g) self.qn.set_transitions({v: {e[1]: mat[e] for e in self.qn.g.out_edges(v)}}) tra = self.qn.transitions() - self.assertTrue( np.allclose(tra[v], mat[v]) ) + self.assertTrue(np.allclose(tra[v], mat[v])) diff --git a/tests/test_queue_server.py b/tests/test_queue_server.py index a35df27..f67eace 100644 --- a/tests/test_queue_server.py +++ b/tests/test_queue_server.py @@ -30,9 +30,9 @@ def test_QueueServer_set_nServers(self): Se2 = q.nServers q.set_nServers(np.infty) - self.assertTrue( Se1 == nSe ) - self.assertTrue( Se2 == 2*nSe ) - self.assertTrue( q.nServers is np.inf ) + self.assertTrue(Se1 == nSe) + self.assertTrue(Se2 == 2*nSe) + self.assertTrue(q.nServers is np.inf) def test_QueueServer_set_nServers_errors(self): q = qt.QueueServer(nServers=3) @@ -45,14 +45,14 @@ def test_QueueServer_set_nServers_errors(self): def test_QueueServer_set_inactive(self): - q = qt.QueueServer() + q = qt.QueueServer() q.set_active() - a = q.active + a = q.active q.set_inactive() - self.assertTrue( a ) - self.assertTrue( not q.active ) + self.assertTrue(a) + self.assertTrue(not q.active) def test_QueueServer_copy(self): @@ -87,21 +87,21 @@ def test_QueueServer_accounting(self): arr = lambda t: t + np.random.exponential(1 / self.lam) ser = lambda t: t + np.random.exponential(1 / mu) - q = qt.QueueServer(nServers=nSe, arrival_f=arr, service_f=ser) + q = qt.QueueServer(nServers=nSe, arrival_f=arr, service_f=ser) q.set_active() nEvents = 15000 - - ans = np.zeros((nEvents,3), bool) + + ans = np.zeros((nEvents, 3), bool) for k in range(nEvents): nt = len(q._departures) + len(q.queue) + len(q._arrivals) - 2 nS = len(q._departures) + len(q.queue) - 1 - ans[k,0] = nt == q._nTotal - ans[k,1] = nS == q.nSystem - ans[k,2] = len(q._departures) - 1 <= q.nServers + ans[k, 0] = nt == q._nTotal + ans[k, 1] = nS == q.nSystem + ans[k, 2] = len(q._departures) - 1 <= q.nServers q.simulate(n=1) - self.assertTrue( ans.all() ) + self.assertTrue(ans.all()) def test_QueueServer_deactivate(self): @@ -110,7 +110,7 @@ def test_QueueServer_deactivate(self): self.assertTrue(q.active) q.simulate(t=10) self.assertFalse(q.active) - + def test_QueueServer_simulation(self): @@ -122,7 +122,7 @@ def test_QueueServer_simulation(self): q = qt.QueueServer(nServers=nSe, arrival_f=arr, service_f=ser) q.set_active() nEvents = 5000 - + ans = np.zeros(4, bool) k = np.random.randint(nEvents * 0.75, nEvents * 1.25) @@ -146,31 +146,31 @@ def test_QueueServer_simulation(self): q.simulate(t=t) ans[3] = q.current_time - t0 >= t - self.assertTrue( ans.all() ) + self.assertTrue(ans.all()) def test_LossQueue_accounting(self): nSe = np.random.randint(1, 10) mu = self.lam / (self.rho * nSe) - arr = lambda t : t + np.random.exponential(1 / self.lam) - ser = lambda t : t + np.random.exponential(1 / mu) + arr = lambda t: t + np.random.exponential(1 / self.lam) + ser = lambda t: t + np.random.exponential(1 / mu) q = qt.LossQueue(nServers=nSe, arrival_f=arr, service_f=ser) q.set_active() nEvents = 15000 - - ans = np.zeros((nEvents,3), bool) + + ans = np.zeros((nEvents, 3), bool) for k in range(nEvents): nt = len(q._departures) + len(q.queue) + len(q._arrivals) - 2 nS = len(q._departures) + len(q.queue) - 1 - ans[k,0] = nt == q._nTotal - ans[k,1] = nS == q.nSystem - ans[k,2] = len(q._departures) - 1 <= q.nServers + ans[k, 0] = nt == q._nTotal + ans[k, 1] = nS == q.nSystem + ans[k, 2] = len(q._departures) - 1 <= q.nServers q.simulate(n=1) - self.assertTrue( ans.all() ) + self.assertTrue(ans.all()) def test_LossQueue_blocking(self): @@ -180,8 +180,8 @@ def test_LossQueue_blocking(self): k = np.random.randint(5, 15) scl = 1 / (mu * k) - arr = lambda t : t + np.random.exponential(1 / self.lam) - ser = lambda t : t + np.random.gamma(k, scl) + arr = lambda t: t + np.random.exponential(1 / self.lam) + ser = lambda t: t + np.random.gamma(k, scl) q = qt.LossQueue(nServers=nSe, arrival_f=arr, service_f=ser) q.set_active() @@ -189,16 +189,16 @@ def test_LossQueue_blocking(self): c = 0 ans = np.zeros(nE, bool) - while c < nE : + while c < nE: if q.next_event_description() == 1 and q.at_capacity(): nB0 = q.nBlocked q.simulate(n=1) ans[c] = nB0 + 1 == q.nBlocked c += 1 - else : + else: q.simulate(n=1) - self.assertTrue( ans.all() ) + self.assertTrue(ans.all()) def test_NullQueue_data_collection(self): @@ -223,7 +223,7 @@ def test_NullQueue_data_collection(self): # service start times in the data self.assertFalse(data[:, (1, 2)].any()) - + def test_ResourceQueue_network(self): @@ -289,22 +289,22 @@ def test_InfoQueue_network(self): qn.simulate(n=2000) # Finish this - self.assertTrue( True ) + self.assertTrue(True) def test_Agent_compare(self): a0 = qt.Agent() a1 = qt.Agent() - self.assertTrue( a0 == a1 ) + self.assertTrue(a0 == a1) a1._time = 10 - self.assertTrue( a0 <= a1 ) - self.assertTrue( a0 < a1 ) + self.assertTrue(a0 <= a1) + self.assertTrue(a0 < a1) a0._time = 20 - self.assertTrue( a0 >= a1 ) - self.assertTrue( a0 > a1 ) + self.assertTrue(a0 >= a1) + self.assertTrue(a0 > a1) diff --git a/tests/test_statistical_properties.py b/tests/test_statistical_properties.py index cf57344..4235a5e 100644 --- a/tests/test_statistical_properties.py +++ b/tests/test_statistical_properties.py @@ -23,7 +23,7 @@ def chi2_cdf(q, k, n=1000000, ns=1): class TestQueueServers(unittest.TestCase): def setUp(self): - self.lam = np.random.randint(1,10) + 0.0 + self.lam = np.random.randint(1, 10) + 0.0 self.rho = np.random.uniform(0.5, 1) @unittest.skipIf(TRAVIS_TEST, reason) @@ -32,8 +32,8 @@ def test_Markovian_QueueServer(self): nSe = np.random.randint(1, 10) mu = self.lam / (self.rho * nSe) - arr = lambda t: t + np.random.exponential(1/self.lam) - ser = lambda t: t + np.random.exponential(1/mu) + arr = lambda t: t + np.random.exponential(1 / self.lam) + ser = lambda t: t + np.random.exponential(1 / mu) q = qt.QueueServer(nServers=nSe, arrival_f=arr, service_f=ser) n = 50000 @@ -50,10 +50,10 @@ def test_Markovian_QueueServer(self): n = len(dep) lamh = 1 / np.mean(dep) - upb = - np.log( 6.0 / n) / lamh + upb = -np.log(6.0 / n) / lamh nbin = n // 6 - 1 #np.floor( np.exp( lam * upb) - 1 ) bins = np.zeros(nbin+2) - bins[1:-1] = upb - np.log( np.arange(nbin, 0, -1)) / lamh + bins[1:-1] = upb - np.log(np.arange(nbin, 0, -1)) / lamh bins[-1] = np.infty N = np.histogram(dep, bins=bins)[0] @@ -63,9 +63,9 @@ def test_Markovian_QueueServer(self): p1 = 1 - chi2_cdf(Q, nbin-1) x, y = dep[1:], dep[:-1] - cc = np.corrcoef(x,y)[0,1] - self.assertAlmostEqual( cc, 0, 1) - self.assertTrue( p1 > 0.05 ) + cc = np.corrcoef(x,y)[0, 1] + self.assertAlmostEqual(cc, 0, 1) + self.assertTrue(p1 > 0.05) @unittest.skipIf(TRAVIS_TEST, reason) def test_QueueServer_Littleslaw(self): @@ -86,7 +86,7 @@ def test_QueueServer_Littleslaw(self): data = q.fetch_data() q.clear() - ind = data[:,2] > 0 + ind = data[:, 2] > 0 wait = data[ind, 1] - data[ind, 0] ans = np.mean(wait) * self.lam - np.mean(data[:, 3]) * self.rho @@ -100,8 +100,8 @@ def test_LossQueue_blocking(self): k = np.random.randint(5, 15) scl = 1 / (mu * k) - arr = lambda t : t + np.random.exponential(1/self.lam) - ser = lambda t : t + np.random.gamma(k, scl) + arr = lambda t: t + np.random.exponential(1 / self.lam) + ser = lambda t: t + np.random.gamma(k, scl) q2 = qt.LossQueue(nServers=nSe, arrival_f=arr, service_f=ser) q2.set_active() @@ -141,26 +141,26 @@ def test_poisson_random_measure(self): nSamp = 15000 nArr = 1000 - arrival_times = np.zeros( (nSamp, nArr) ) + arrival_times = np.zeros((nSamp, nArr)) for k in range(nSamp): t = 0 for j in range(nArr): t = arr_f(t) arrival_times[k, j] = t - if t > 12 : + if t > 12: break mu1 = 5 * np.sum(rate(np.linspace(3, 8, 200))) / 200 # or 2*(5 + (sqrt(3) + 2) * 3/pi) + 2.5 mu2 = 4 * np.sum(rate(np.linspace(8, 12, 200))) / 200 # or 2*(4 - 3*sqrt(3)/pi) + 2 mus = [mu1, mu2] - + rv1 = np.sum(np.logical_and(3 < arrival_times, arrival_times < 8), axis=1) rv2 = np.sum(np.logical_and(8 < arrival_times, arrival_times < 12), axis=1) rvs = [rv1, rv2] df = [max(rv1)+2, max(rv2)+2] - - Q = np.zeros( (max(df), len(rvs)) ) - + + Q = np.zeros((max(df), len(rvs))) + for i, sample in enumerate(rvs): for k in range(df[i]-1): pi_hat = nSamp * np.exp(-mus[i]) * mus[i]**k / math.factorial(k) @@ -169,10 +169,10 @@ def test_poisson_random_measure(self): ans = np.array([math.factorial(j) for j in range(k+1)]) pois_cdf = np.sum(np.exp(-mus[i]) * mus[i]**np.arange(k+1) / ans) Q[k+1, i] = nSamp * (1 - pois_cdf) - + Qs = np.sum(Q, axis=0) p = np.array([1 - chi2_cdf(Qs[i], df[i]-2) for i in range(len(rvs))]) - self.assertTrue( (p > 0.1).any() ) + self.assertTrue((p > 0.1).any()) if __name__ == '__main__':