stochastic-matching 0.2.2__tar.gz → 0.3.0__tar.gz

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.
Files changed (59) hide show
  1. stochastic_matching-0.3.0/PKG-INFO +102 -0
  2. stochastic_matching-0.3.0/pyproject.toml +67 -0
  3. stochastic_matching-0.3.0/stochastic_matching/__init__.py +24 -0
  4. {stochastic_matching-0.2.2 → stochastic_matching-0.3.0}/stochastic_matching/common.py +5 -168
  5. {stochastic_matching-0.2.2 → stochastic_matching-0.3.0}/stochastic_matching/model.py +24 -16
  6. stochastic_matching-0.3.0/stochastic_matching/simulator/arrivals.py +103 -0
  7. stochastic_matching-0.3.0/stochastic_matching/simulator/e_filtering.py +196 -0
  8. stochastic_matching-0.3.0/stochastic_matching/simulator/fcfm.py +142 -0
  9. stochastic_matching-0.3.0/stochastic_matching/simulator/graph.py +72 -0
  10. stochastic_matching-0.3.0/stochastic_matching/simulator/logs.py +28 -0
  11. stochastic_matching-0.3.0/stochastic_matching/simulator/longest.py +307 -0
  12. stochastic_matching-0.3.0/stochastic_matching/simulator/multiqueue.py +271 -0
  13. stochastic_matching-0.3.0/stochastic_matching/simulator/priority.py +111 -0
  14. stochastic_matching-0.3.0/stochastic_matching/simulator/random_edge.py +136 -0
  15. stochastic_matching-0.3.0/stochastic_matching/simulator/random_item.py +95 -0
  16. stochastic_matching-0.2.2/stochastic_matching/simulator/generic.py → stochastic_matching-0.3.0/stochastic_matching/simulator/simulator.py +97 -88
  17. stochastic_matching-0.3.0/stochastic_matching/simulator/virtual_queue.py +346 -0
  18. stochastic_matching-0.2.2/CONTRIBUTING.rst +0 -128
  19. stochastic_matching-0.2.2/HISTORY.rst +0 -132
  20. stochastic_matching-0.2.2/MANIFEST.in +0 -11
  21. stochastic_matching-0.2.2/PKG-INFO +0 -237
  22. stochastic_matching-0.2.2/docs/Makefile +0 -20
  23. stochastic_matching-0.2.2/docs/authors.rst +0 -1
  24. stochastic_matching-0.2.2/docs/conf.py +0 -182
  25. stochastic_matching-0.2.2/docs/contributing.rst +0 -1
  26. stochastic_matching-0.2.2/docs/history.rst +0 -1
  27. stochastic_matching-0.2.2/docs/index.rst +0 -20
  28. stochastic_matching-0.2.2/docs/installation.rst +0 -51
  29. stochastic_matching-0.2.2/docs/make.bat +0 -36
  30. stochastic_matching-0.2.2/docs/readme.rst +0 -1
  31. stochastic_matching-0.2.2/docs/reference/common.rst +0 -7
  32. stochastic_matching-0.2.2/docs/reference/display.rst +0 -7
  33. stochastic_matching-0.2.2/docs/reference/graphs.rst +0 -7
  34. stochastic_matching-0.2.2/docs/reference/index.rst +0 -11
  35. stochastic_matching-0.2.2/docs/reference/model.rst +0 -7
  36. stochastic_matching-0.2.2/docs/reference/simulator.rst +0 -27
  37. stochastic_matching-0.2.2/docs/sm_logo.png +0 -0
  38. stochastic_matching-0.2.2/docs/sm_logo_short.png +0 -0
  39. stochastic_matching-0.2.2/docs/tutorials/index.rst +0 -12
  40. stochastic_matching-0.2.2/setup.cfg +0 -29
  41. stochastic_matching-0.2.2/setup.py +0 -48
  42. stochastic_matching-0.2.2/stochastic_matching/__init__.py +0 -14
  43. stochastic_matching-0.2.2/stochastic_matching/simulator/age_based.py +0 -380
  44. stochastic_matching-0.2.2/stochastic_matching/simulator/size_based.py +0 -791
  45. stochastic_matching-0.2.2/stochastic_matching/simulator/virtual_queue.py +0 -208
  46. stochastic_matching-0.2.2/stochastic_matching.egg-info/PKG-INFO +0 -237
  47. stochastic_matching-0.2.2/stochastic_matching.egg-info/SOURCES.txt +0 -44
  48. stochastic_matching-0.2.2/stochastic_matching.egg-info/dependency_links.txt +0 -1
  49. stochastic_matching-0.2.2/stochastic_matching.egg-info/not-zip-safe +0 -1
  50. stochastic_matching-0.2.2/stochastic_matching.egg-info/requires.txt +0 -6
  51. stochastic_matching-0.2.2/stochastic_matching.egg-info/top_level.txt +0 -2
  52. stochastic_matching-0.2.2/tests/__init__.py +0 -1
  53. stochastic_matching-0.2.2/tests/test_stochastic_matching.py +0 -21
  54. {stochastic_matching-0.2.2 → stochastic_matching-0.3.0}/AUTHORS.rst +0 -0
  55. {stochastic_matching-0.2.2 → stochastic_matching-0.3.0}/LICENSE +0 -0
  56. {stochastic_matching-0.2.2 → stochastic_matching-0.3.0}/README.rst +0 -0
  57. {stochastic_matching-0.2.2 → stochastic_matching-0.3.0}/stochastic_matching/display.py +0 -0
  58. {stochastic_matching-0.2.2 → stochastic_matching-0.3.0}/stochastic_matching/graphs.py +0 -0
  59. {stochastic_matching-0.2.2 → stochastic_matching-0.3.0}/stochastic_matching/simulator/__init__.py +0 -0
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.1
2
+ Name: stochastic-matching
3
+ Version: 0.3.0
4
+ Summary: Stochastic Matching provides tools to analyze the behavior of stochastic matching problems.
5
+ License: GPLv3
6
+ Author: Fabien Mathieu
7
+ Author-email: fabien.mathieu@normalesup.org
8
+ Requires-Python: >=3.10,<4.0
9
+ Classifier: License :: Other/Proprietary License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Dist: cached-property (>=1.5.2,<2.0.0)
15
+ Requires-Dist: ipython (>=8.24.0,<9.0.0)
16
+ Requires-Dist: matplotlib (>=3.9.0,<4.0.0)
17
+ Requires-Dist: numba (>=0.59.1,<0.60.0)
18
+ Requires-Dist: scipy (>=1.13.0,<2.0.0)
19
+ Description-Content-Type: text/x-rst
20
+
21
+ .. image:: https://github.com/balouf/stochastic_matching/raw/master/docs/sm_logo.png
22
+ :alt: SMUP logo
23
+ :target: https://balouf.github.io/stochastic_matching/
24
+
25
+
26
+ ===================
27
+ Stochastic Matching
28
+ ===================
29
+
30
+
31
+ .. image:: https://img.shields.io/pypi/v/stochastic_matching.svg
32
+ :target: https://pypi.python.org/pypi/stochastic_matching
33
+ :alt: PyPI Status
34
+
35
+ .. image:: https://github.com/balouf/stochastic_matching/workflows/build/badge.svg?branch=master
36
+ :target: https://github.com/balouf/stochastic_matching/actions?query=workflow%3Abuild
37
+ :alt: Build Status
38
+
39
+ .. image:: https://github.com/balouf/stochastic_matching/workflows/docs/badge.svg?branch=master
40
+ :target: https://github.com/balouf/stochastic_matching/actions?query=workflow%3Adocs
41
+ :alt: Documentation Status
42
+
43
+
44
+ .. image:: https://codecov.io/gh/balouf/stochastic_matching/branch/master/graphs/badge.svg
45
+ :target: https://codecov.io/gh/balouf/stochastic_matching/tree/master/stochastic_matching
46
+ :alt: Code Coverage
47
+
48
+
49
+ Stochastic Matching provides tools to analyze the behavior of stochastic matching problems.
50
+
51
+
52
+ * Free software: GNU General Public License v3
53
+ * Documentation: https://balouf.github.io/stochastic_matching/.
54
+
55
+
56
+ --------
57
+ Features
58
+ --------
59
+
60
+ * Compatibility graph creation (from scratch, from one of the provided generator, or by some combination).
61
+ * Theoretical analysis:
62
+ * Injectivity/surjectivity of the graph, kernel description.
63
+ * Polytope description of positive solutions.
64
+ * Fast simulator.
65
+ * Provided with a large set of greedy / non-greedy policies.
66
+ * Adding new policies is feasible out-of-the-box.
67
+ * Lot of display features, including `Vis JS Network`_.
68
+
69
+
70
+ ---------------------
71
+ Installation
72
+ ---------------------
73
+
74
+ To install Stochastic Matching, run this command in your terminal:
75
+
76
+ .. code-block:: console
77
+
78
+ $ pip install stochastic_matching
79
+
80
+ This is the preferred method to install Stochastic Matching, as it will always install the most recent stable release.
81
+
82
+
83
+ ---------------------------
84
+ Acknowledging package
85
+ ---------------------------
86
+
87
+ If you publish results based on `Stochastic Matching`_, **please acknowledge** the usage of the package by quoting the following paper.
88
+
89
+ * Céline Comte, Fabien Mathieu, Ana Bušić. `Stochastic dynamic matching: A mixed graph-theory and linear-algebra approach <https://hal.archives-ouvertes.fr/hal-03502084>`_. 2022.
90
+
91
+ -------
92
+ Credits
93
+ -------
94
+
95
+ This package was created with Cookiecutter_ and the `francois-durand/package_helper_2`_ project template.
96
+
97
+ .. _Cookiecutter: https://github.com/audreyr/cookiecutter
98
+ .. _`francois-durand/package_helper_2`: https://github.com/francois-durand/package_helper_2
99
+ .. _`Vis JS Network`: https://visjs.github.io/vis-network/docs/network/
100
+ .. _`Stochastic Matching`: https://balouf.github.io/stochastic_matching/
101
+
102
+
@@ -0,0 +1,67 @@
1
+ [tool.poetry]
2
+ name = "stochastic-matching"
3
+ version = "v0.3.0"
4
+ description = "Stochastic Matching provides tools to analyze the behavior of stochastic matching problems."
5
+ authors = ["Fabien Mathieu <fabien.mathieu@normalesup.org>"]
6
+ license = "GPLv3"
7
+ readme = "README.rst"
8
+
9
+ [tool.poetry.dependencies]
10
+ python = "^3.10"
11
+ numba = "^0.59.1"
12
+ scipy = "^1.13.0"
13
+ cached-property = "^1.5.2"
14
+ ipython = "^8.24.0"
15
+ matplotlib = "^3.9.0"
16
+
17
+ [tool.poetry.group.dev.dependencies]
18
+ pytest-cov = "^5.0.0"
19
+ tox = "^4.15.0"
20
+
21
+
22
+ [tool.poetry.group.docs.dependencies]
23
+ pydata-sphinx-theme = "^0.15.2"
24
+ sphinx-mdinclude = "^0.6.0"
25
+ nbsphinx = "^0.9.4"
26
+
27
+ [build-system]
28
+ requires = ["poetry-core"]
29
+ build-backend = "poetry.core.masonry.api"
30
+
31
+ [tool.coverage.report]
32
+ skip_empty = true
33
+
34
+ [tool.coverage.run]
35
+ branch = true
36
+ source = ["stochastic_matching"]
37
+
38
+ [tool.coverage.html]
39
+ directory = "cov"
40
+
41
+ [tool.pytest.ini_options]
42
+ addopts = "--doctest-modules --ignore=hooks --cov --cov-config=pyproject.toml --cov-report xml --cov-report html --showlocals --capture=no --exitfirst --failed-first"
43
+
44
+ [tool.tox]
45
+ legacy_tox_ini = """
46
+ [tox]
47
+ skipsdist = true
48
+
49
+ [gh-actions]
50
+ python =
51
+ 3.10: py310
52
+ 3.11: py311
53
+ 3.12: py312
54
+
55
+ [testenv]
56
+ passenv = PYTHON_VERSION
57
+ setenv =
58
+ NUMBA_DISABLE_JIT=1
59
+ allowlist_externals = poetry
60
+ commands =
61
+ poetry install -v
62
+ pytest
63
+ """
64
+
65
+ [tool.poetry_bumpversion.file."stochastic_matching/__init__.py"]
66
+
67
+
@@ -0,0 +1,24 @@
1
+ """Top-level package for Stochastic Matching."""
2
+
3
+ __author__ = """Fabien Mathieu"""
4
+ __email__ = 'fabien.mathieu@normalesup.org'
5
+ __version__ = '0.3.0'
6
+
7
+ from stochastic_matching.model import Model
8
+ from stochastic_matching.graphs import Path, Star, Cycle, Codomino, CycleChain, Complete, Pyramid, HyperPaddle, \
9
+ KayakPaddle, Lollipop, Tadpole, Barbell, Fan, concatenate
10
+ from stochastic_matching.simulator.simulator import Simulator
11
+ from stochastic_matching.simulator.fcfm import FCFM
12
+ from stochastic_matching.simulator.longest import Longest
13
+ from stochastic_matching.simulator.priority import Priority
14
+ from stochastic_matching.simulator.random_edge import RandomEdge
15
+ from stochastic_matching.simulator.random_item import RandomItem
16
+ from stochastic_matching.simulator.virtual_queue import VirtualQueue
17
+ from stochastic_matching.simulator.e_filtering import EFiltering
18
+
19
+
20
+ # from stochastic_matching.old_simulator.age_based import FCFM
21
+ # from stochastic_matching.old_simulator.virtual_queue import VQSimulator
22
+ # from stochastic_matching.old_simulator.size_based import LongestSimulator, PrioritySimulator, QueueSizeSimulator, \
23
+ # RandomItemSimulator, \
24
+ # RandomNodeSimulator, FilteringGreedy
@@ -147,16 +147,16 @@ def class_converter(subclass, motherclass):
147
147
  --------
148
148
 
149
149
  >>> import stochastic_matching as sm
150
- >>> from stochastic_matching.simulator.generic import Simulator
151
- >>> class_converter('random_node', Simulator)
152
- <class 'stochastic_matching.simulator.size_based.RandomNodeSimulator'>
150
+ >>> from stochastic_matching.simulator.simulator import Simulator
151
+ >>> class_converter('random_edge', Simulator)
152
+ <class 'stochastic_matching.simulator.random_edge.RandomEdge'>
153
153
  >>> class_converter(sm.FCFM, Simulator)
154
- <class 'stochastic_matching.simulator.age_based.FCFM'>
154
+ <class 'stochastic_matching.simulator.fcfm.FCFM'>
155
155
  >>> class_converter('anything', Simulator) # doctest: +NORMALIZE_WHITESPACE
156
156
  Traceback (most recent call last):
157
157
  ...
158
158
  ValueError: anything is not a known name for a subclass of Simulator.
159
- Known names: virtual_queue, generic_queue_size, fcfm, random_node, longest_queue, random_item, filtering, priority.
159
+ Known names: fcfm, longest, priority, random_edge, random_item, virtual_queue, e_filtering.
160
160
 
161
161
  >>> class_converter(2, Simulator)
162
162
  Traceback (most recent call last):
@@ -251,166 +251,3 @@ def set_seed(value):
251
251
  0.3745401188473625
252
252
  """
253
253
  np.random.seed(value)
254
-
255
-
256
- def create_prob_alias(mu):
257
- """
258
- Prepare vector to draw a distribution with the alias method.
259
-
260
- Based on https://www.keithschwarz.com/darts-dice-coins/.
261
-
262
- Parameters
263
- ----------
264
- mu: :class:`list` or :class:`~numpy.ndarray`
265
- Arrival intensities.
266
-
267
- Returns
268
- -------
269
- prob: :class:`~numpy.ndarray`
270
- Probabilities to stay in the drawn bucket
271
- alias: :class:`~numpy.ndarray`
272
- Redirection array
273
-
274
- Examples
275
- --------
276
-
277
- >>> probas, aliases = create_prob_alias([2 ,2, 3, 1])
278
- >>> probas
279
- array([1. , 1. , 1. , 0.5])
280
- >>> aliases
281
- array([0, 0, 0, 2])
282
- """
283
- cmu = np.array(mu)
284
- n = len(cmu)
285
- alias = np.zeros(n, dtype=int)
286
- prob = np.zeros(n)
287
- # noinspection PyUnresolvedReferences
288
- normalized_intensities = cmu * n / np.sum(cmu)
289
- small = [i for i in range(n) if normalized_intensities[i] < 1]
290
- large = [i for i in range(n) if normalized_intensities[i] >= 1]
291
- while small and large:
292
- l, g = small.pop(), large.pop()
293
- prob[l], alias[l] = normalized_intensities[l], g
294
- normalized_intensities[g] += normalized_intensities[l] - 1
295
- if normalized_intensities[g] < 1:
296
- small.append(g)
297
- else:
298
- large.append(g)
299
- for i in large + small:
300
- prob[i] = 1
301
- return prob, alias
302
-
303
-
304
- def graph_neighbors_list(model, forbidden_edges=None):
305
- """
306
- Extract Numba-compatible neighboring structures from a :class:`~stochastic_matching.model.Model`.
307
-
308
- Parameters
309
- ----------
310
- model: :class:`~stochastic_matching.model.Model`
311
- Model with the graph to transform.
312
-
313
-
314
- Returns
315
- -------
316
- :class:`~numba.typed.List`
317
- List of neighbors for each node. For one given node yields a list of tuples where the first element is the edge
318
- and the second element the neighbor (for `SimpleGraph`) / array of neighbors (for `HyperGraph`).
319
-
320
- Examples
321
- --------
322
-
323
- Consider a diamond graph.
324
-
325
- >>> import stochastic_matching as sm
326
- >>> diamond = sm.CycleChain()
327
- >>> diamond.incidence
328
- array([[1, 1, 0, 0, 0],
329
- [1, 0, 1, 1, 0],
330
- [0, 1, 1, 0, 1],
331
- [0, 0, 0, 1, 1]])
332
-
333
- Node 0 is connected with edge 0 to node 1 and with edge 1 to node 2.
334
-
335
- Node 1 is connected with edge 0 to node 0, with edge 2 to node 2, and with edge 3 to node 3.
336
-
337
- Node 2 is connected with edge 1 to node 0, with edge 2 to node 1, and with edge 4 to node 3.
338
-
339
- Node 3 is connected with edge 3 to node 1 and with edge 4 to node 2.
340
-
341
- This is exactly what `graph_neighbors_list` outputs, in a numba-compatible way.
342
-
343
- >>> graph_neighbors_list(diamond) # doctest: +NORMALIZE_WHITESPACE
344
- [[(0, 1), (1, 2)],
345
- [(0, 0), (2, 2), (3, 3)],
346
- [(1, 0), (2, 1), (4, 3)],
347
- [(3, 1), (4, 2)]]
348
-
349
- To remove some egdes, use the optional parameter forbidden_edges.
350
-
351
- >>> graph_neighbors_list(diamond, forbidden_edges={0, 4}) # doctest: +NORMALIZE_WHITESPACE
352
- [[(1, 2)],
353
- [(2, 2), (3, 3)],
354
- [(1, 0), (2, 1)],
355
- [(3, 1)]]
356
-
357
- With hypergraph notation, the second term of the tuples is an array instead of an integer.
358
-
359
- >>> diamond.adjacency = None
360
- >>> g = graph_neighbors_list(diamond)
361
- >>> [ [(e, a.astype(int)) for e, a in n] for n in g ] # doctest: +NORMALIZE_WHITESPACE
362
- [[(0, array([1])), (1, array([2]))],
363
- [(0, array([0])), (2, array([2])), (3, array([3]))],
364
- [(1, array([0])), (2, array([1])), (4, array([3]))],
365
- [(3, array([1])), (4, array([2]))]]
366
-
367
-
368
- Having arrays is only useful for true hypergraphs. For instance, in the candy hypergraph, edge 6 links
369
- nodes 2, 3, and 4 together.
370
-
371
- >>> candy = sm.HyperPaddle()
372
- >>> candy.incidence
373
- array([[1, 1, 0, 0, 0, 0, 0],
374
- [1, 0, 1, 0, 0, 0, 0],
375
- [0, 1, 1, 0, 0, 0, 1],
376
- [0, 0, 0, 0, 0, 0, 1],
377
- [0, 0, 0, 1, 1, 0, 1],
378
- [0, 0, 0, 1, 0, 1, 0],
379
- [0, 0, 0, 0, 1, 1, 0]])
380
-
381
- This shows in the output of the function.
382
-
383
- >>> g = graph_neighbors_list(candy)
384
- >>> [ [(e, a.astype(int)) for e, a in n] for n in g ] # doctest: +NORMALIZE_WHITESPACE
385
- [[(0, array([1])), (1, array([2]))],
386
- [(0, array([0])), (2, array([2]))],
387
- [(1, array([0])), (2, array([1])), (6, array([3, 4]))],
388
- [(6, array([2, 4]))],
389
- [(3, array([5])), (4, array([6])), (6, array([2, 3]))],
390
- [(3, array([4])), (5, array([6]))],
391
- [(4, array([4])), (5, array([5]))]]
392
-
393
- >>> g = graph_neighbors_list(candy, forbidden_edges={1, 3})
394
- >>> [ [(e, a.astype(int)) for e, a in n] for n in g ] # doctest: +NORMALIZE_WHITESPACE
395
- [[(0, array([1]))],
396
- [(0, array([0])), (2, array([2]))],
397
- [(2, array([1])), (6, array([3, 4]))],
398
- [(6, array([2, 4]))],
399
- [(4, array([6])), (6, array([2, 3]))],
400
- [(5, array([6]))],
401
- [(4, array([4])), (5, array([5]))]]
402
-
403
- """
404
- if forbidden_edges is None:
405
- forbidden_edges = set()
406
- edges = [model.incidence_csr.indices[model.incidence_csr.indptr[i]:model.incidence_csr.indptr[i + 1]]
407
- for i in range(model.n)]
408
- edges = [ [e for e in edges[i] if e not in forbidden_edges] for i in range(model.n) ]
409
- if model.adjacency is not None:
410
- neighbors = [[[k for k in model.incidence_csc.indices[model.incidence_csc.indptr[e]:model.incidence_csc.indptr[e + 1]] if k != i][0]
411
- for e in edges[i]] for i in range(model.n)]
412
- else:
413
- neighbors = [
414
- [np.array([k for k in model.incidence_csc.indices[model.incidence_csc.indptr[e]:model.incidence_csc.indptr[e + 1]] if k != i], dtype=np.int32)
415
- for e in edges[i] if e not in forbidden_edges] for i in range(model.n)]
416
- return List([List([(e, v) for e, v in zip(edges[i], neighbors[i])]) for i in range(model.n)])
@@ -6,7 +6,7 @@ from cached_property import cached_property
6
6
 
7
7
  from stochastic_matching.common import pseudo_inverse_scalar, clean_zeros, CharMaker, neighbors, class_converter
8
8
  from stochastic_matching.display import show
9
- from stochastic_matching.simulator.generic import Simulator
9
+ from stochastic_matching.simulator.simulator import Simulator
10
10
 
11
11
  status_names = {(False, False): "Nonjective",
12
12
  (True, False): "Injective-only",
@@ -63,7 +63,7 @@ def adjacency_to_incidence(adjacency):
63
63
  def incidence_to_adjacency(incidence):
64
64
  """
65
65
  Converts incidence matrix to adjacency matrix.
66
- If the incidence matrix does not corresponds to a simple graph, an error is thrown.
66
+ If the incidence matrix does not correspond to a simple graph, an error is thrown.
67
67
 
68
68
  Parameters
69
69
  ----------
@@ -692,7 +692,7 @@ def traversal(model):
692
692
  'spanner': {19, 20, 21}, 'pivot': False, 'seeds': set(),
693
693
  'type': 'Tree'}]
694
694
 
695
- These informations make the analysis worthy even in the cases where the graph is connected.
695
+ This information makes the analysis worthy even in the cases where the graph is connected.
696
696
 
697
697
  >>> traversal(sm.Pyramid()) # doctest: +NORMALIZE_WHITESPACE
698
698
  [{'nodes': {0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
@@ -764,14 +764,14 @@ class Model:
764
764
 
765
765
  Parameters
766
766
  ----------
767
- incidence: :class:`~numpy.ndarray`, optional
767
+ incidence: :class:`~numpy.ndarray` or :class:`list`, optional
768
768
  Incidence matrix. If used, the graph will be considered as a hypergraph.
769
- adjacency: :class:`~numpy.ndarray`, optional
769
+ adjacency: :class:`~numpy.ndarray` or :class:`list`, optional
770
770
  Adjacency matrix. If used, the graph will be considered as a simple graph.
771
771
  rates: :class:`~numpy.ndarray` or :class:`list` or :class:`str`, optional
772
772
  Arrival rates. You can use a specific rate vector or list.
773
773
  You can use `uniform` or `proportional` for uniform or degree-proportional allocation.
774
- Default to `proportional`, which makes the problem stabilizable if the graph is bijective.
774
+ Default to `proportional`, which makes the problem stabilizable if the graph is surjective.
775
775
  names: :class:`list` of :class:`str` or 'alpha', optional
776
776
  List of node names (e.g. for display)
777
777
  tol: :class:`float`, optional
@@ -1568,14 +1568,22 @@ class Model:
1568
1568
  default = {'flow': flow, 'disp_zero': False, 'check_flow': True}
1569
1569
  show(self, **{**default, **kwargs})
1570
1570
 
1571
- def run(self, simulator, **kwargs):
1571
+ def run(self, simulator, n_steps=1000000, seed=None, max_queue=1000, **kwargs):
1572
1572
  """
1573
1573
  All-in-one instantiate and run simulation.
1574
1574
 
1575
1575
  Parameters
1576
1576
  ----------
1577
- simulator: :class:`str` or :class:`~stochastic_matching.simulator.generic.Simulator`
1577
+ simulator: :class:`str` or :class:`~stochastic_matching.simulator.simulator.Simulator`
1578
1578
  Type of simulator to instantiate.
1579
+ n_steps: :class:`int`, optional
1580
+ Number of arrivals to simulate.
1581
+ seed: :class:`int`, optional
1582
+ Seed of the random generator
1583
+ max_queue: :class:`int`
1584
+ Max queue size. Necessary for speed and detection of unstability.
1585
+ For stable systems very close to the unstability
1586
+ border, the max_queue may be reached.
1579
1587
  **kwargs
1580
1588
  Arguments to pass to the simulator.
1581
1589
 
@@ -1593,10 +1601,10 @@ class Model:
1593
1601
  >>> triangle = sm.Cycle(rates=[3, 4, 5])
1594
1602
  >>> triangle.base_flow
1595
1603
  array([1., 2., 3.])
1596
- >>> triangle.run('random_node', seed=42, number_events=20000)
1604
+ >>> triangle.run('random_edge', seed=42, n_steps=20000)
1597
1605
  True
1598
1606
  >>> triangle.simulation
1599
- array([1.044 , 2.0352, 2.9202])
1607
+ array([1.0716, 1.9524, 2.976 ])
1600
1608
 
1601
1609
  A ill diamond graph (simulation ends before completion due to drift).
1602
1610
 
@@ -1606,7 +1614,7 @@ class Model:
1606
1614
  >>> diamond.base_flow
1607
1615
  array([0.5, 0.5, 0. , 0.5, 0.5])
1608
1616
 
1609
- >>> diamond.run('longest_queue', seed=42, number_events=20000)
1617
+ >>> diamond.run('longest', seed=42, n_steps=20000)
1610
1618
  True
1611
1619
  >>> diamond.simulation
1612
1620
  array([0.501 , 0.4914, 0.0018, 0.478 , 0.5014])
@@ -1620,9 +1628,9 @@ class Model:
1620
1628
 
1621
1629
  The above states that the target flow for the hyperedge of the candy (last entry) is 1.
1622
1630
 
1623
- >>> candy.run('longest_queue', seed=42, number_events=20000)
1631
+ >>> candy.run('longest', seed=42, n_steps=20000)
1624
1632
  False
1625
- >>> candy.simulator.logs['steps_done']
1633
+ >>> candy.simulator.logs.steps_done
1626
1634
  10459
1627
1635
  >>> candy.simulation # doctest: +NORMALIZE_WHITESPACE
1628
1636
  array([0.64227938, 0.37586767, 0.38757051, 0.40753418, 0.40891099,
@@ -1630,7 +1638,7 @@ class Model:
1630
1638
 
1631
1639
  A greedy simulator performs poorly on the hyperedge.
1632
1640
 
1633
- >>> candy.run('virtual_queue', seed=42, number_events=20000)
1641
+ >>> candy.run('virtual_queue', seed=42, n_steps=20000)
1634
1642
  True
1635
1643
  >>> candy.simulation # doctest: +NORMALIZE_WHITESPACE
1636
1644
  array([0.96048, 0.04104, 0.04428, 0.06084, 0.06084, 0.94464, 0.9846 ])
@@ -1638,8 +1646,8 @@ class Model:
1638
1646
  The virtual queue simulator manages to cope with the target flow on the hyperedge.
1639
1647
  """
1640
1648
  simulator = class_converter(simulator, Simulator)
1641
- self.simulator = simulator(self, **kwargs)
1649
+ self.simulator = simulator(self, n_steps=n_steps, seed=seed, max_queue=max_queue, **kwargs)
1642
1650
  self.simulator.run()
1643
1651
  self.simulation = self.simulator.compute_flow()
1644
1652
  self.base_flow = self.simulation
1645
- return self.simulator.generator['number_events'] == self.simulator.logs['steps_done']
1653
+ return self.simulator.internal['n_steps'] == self.simulator.logs.steps_done
@@ -0,0 +1,103 @@
1
+ import numpy as np
2
+ from numba import njit, typeof
3
+ from numba.experimental import jitclass
4
+
5
+
6
+ @njit
7
+ def create_prob_alias(mu):
8
+ """
9
+ Prepare vector to draw a distribution with the alias method.
10
+
11
+ Based on https://www.keithschwarz.com/darts-dice-coins/.
12
+
13
+ Parameters
14
+ ----------
15
+ mu: :class:`list` or :class:`~numpy.ndarray`
16
+ Arrival intensities.
17
+
18
+ Returns
19
+ -------
20
+ prob: :class:`~numpy.ndarray`
21
+ Probabilities to stay in the drawn bucket
22
+ alias: :class:`~numpy.ndarray`
23
+ Redirection array
24
+
25
+ Examples
26
+ --------
27
+
28
+ >>> probas, aliases = create_prob_alias([2 ,2, 3, 1])
29
+ >>> probas
30
+ array([1. , 1. , 1. , 0.5])
31
+ >>> aliases
32
+ array([0, 0, 0, 2])
33
+ """
34
+ if isinstance(mu, list):
35
+ cmu = np.array(mu)
36
+ else:
37
+ cmu = mu
38
+ n = len(cmu)
39
+ alias = np.zeros(n, dtype=np.int_)
40
+ prob = np.zeros(n)
41
+ # noinspection PyUnresolvedReferences
42
+ normalized_intensities = cmu * n / np.sum(cmu)
43
+ small = [i for i in range(n) if normalized_intensities[i] < 1]
44
+ large = [i for i in range(n) if normalized_intensities[i] >= 1]
45
+ while small and large:
46
+ l, g = small.pop(), large.pop()
47
+ prob[l], alias[l] = normalized_intensities[l], g
48
+ normalized_intensities[g] += normalized_intensities[l] - 1
49
+ if normalized_intensities[g] < 1:
50
+ small.append(g)
51
+ else:
52
+ large.append(g)
53
+ for i in large + small:
54
+ prob[i] = 1
55
+ return prob, alias
56
+
57
+
58
+ alias_type = typeof(np.zeros(1, dtype=int))
59
+ prob_type = typeof(np.zeros(1))
60
+
61
+
62
+ @jitclass
63
+ class Arrivals:
64
+ """
65
+ Parameters
66
+ ----------
67
+ mu: :class:`list` or :class:`~numpy.ndarray`
68
+ Arrival intensities.
69
+ seed: :class:`int`
70
+ Seed for random generator.
71
+
72
+ Examples
73
+ --------
74
+
75
+ >>> arrivals = Arrivals([2 ,2, 3, 1], seed=42)
76
+ >>> arrivals.prob
77
+ array([1. , 1. , 1. , 0.5])
78
+ >>> arrivals.alias.astype(int)
79
+ array([0, 0, 0, 2])
80
+ >>> from collections import Counter
81
+ >>> Counter([arrivals.draw() for _ in range(800)])
82
+ Counter({2: 291, 1: 210, 0: 208, 3: 91})
83
+ """
84
+ prob: prob_type
85
+ alias: alias_type
86
+ n: int
87
+
88
+ def __init__(self, mu, seed=None):
89
+ self.prob, self.alias = create_prob_alias(mu)
90
+ self.n = len(mu)
91
+ if seed is not None:
92
+ self.set_seed(seed)
93
+
94
+ @staticmethod
95
+ def set_seed(seed):
96
+ np.random.seed(seed)
97
+
98
+ def draw(self):
99
+ node = np.random.randint(self.n)
100
+ if np.random.rand() > self.prob[node]:
101
+ node = self.alias[node]
102
+ return node
103
+