netoptim 0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- netoptim/__init__.py +16 -0
- netoptim/network_oracle.py +72 -0
- netoptim/optscaling_oracle.py +90 -0
- netoptim/skeleton.py +149 -0
- netoptim-0.1.dist-info/METADATA +60 -0
- netoptim-0.1.dist-info/RECORD +9 -0
- netoptim-0.1.dist-info/WHEEL +5 -0
- netoptim-0.1.dist-info/licenses/LICENSE.txt +21 -0
- netoptim-0.1.dist-info/top_level.txt +1 -0
netoptim/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
|
|
3
|
+
if sys.version_info[:2] >= (3, 8):
|
|
4
|
+
# TODO: Import directly (no need for conditional) when `python_requires = >= 3.9`
|
|
5
|
+
from importlib.metadata import PackageNotFoundError, version # pragma: no cover
|
|
6
|
+
else:
|
|
7
|
+
from importlib_metadata import PackageNotFoundError, version # pragma: no cover
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
# Change here if project is renamed and does not equal the package name
|
|
11
|
+
dist_name = __name__
|
|
12
|
+
__version__ = version(dist_name)
|
|
13
|
+
except PackageNotFoundError: # pragma: no cover
|
|
14
|
+
__version__ = "unknown"
|
|
15
|
+
finally:
|
|
16
|
+
del version, PackageNotFoundError
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
from typing import Any, Optional, Tuple
|
|
2
|
+
|
|
3
|
+
from digraphx.neg_cycle import NegCycleFinder
|
|
4
|
+
|
|
5
|
+
Cut = Tuple[Any, float]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class NetworkOracle:
|
|
9
|
+
"""Oracle for Parametric Network Problem:
|
|
10
|
+
|
|
11
|
+
The `NetworkOracle` class represents an oracle for solving a parametric network problem, where the
|
|
12
|
+
goal is to find values for variables `x` and `u` that satisfy certain constraints.
|
|
13
|
+
|
|
14
|
+
| find x, u
|
|
15
|
+
| s.t. u[j] − u[i] ≤ h(edge, x)
|
|
16
|
+
| ∀ edge(i, j) ∈ E
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, gra, u, h):
|
|
20
|
+
"""
|
|
21
|
+
The function initializes an object with a directed graph, a list or dictionary, and a function for
|
|
22
|
+
evaluation and gradient.
|
|
23
|
+
|
|
24
|
+
:param gra: The parameter `gra` is a directed graph represented by a tuple `(Node, E)`. `Node`
|
|
25
|
+
represents the set of nodes in the graph, and `E` represents the set of edges in the graph
|
|
26
|
+
:param u: The `u` parameter is either a list or a dictionary. It represents the initial values
|
|
27
|
+
of the variables in the optimization problem. The specific meaning of these variables depends on the
|
|
28
|
+
context of the optimization problem being solved
|
|
29
|
+
:param h: The parameter `h` is a function that is used for evaluation and gradient calculations. It
|
|
30
|
+
takes in some input and returns the evaluation value and gradient of that input
|
|
31
|
+
"""
|
|
32
|
+
self._gra = gra
|
|
33
|
+
self._potential = u
|
|
34
|
+
self._h = h
|
|
35
|
+
self._ncf = NegCycleFinder(gra)
|
|
36
|
+
|
|
37
|
+
def update(self, t):
|
|
38
|
+
"""[summary]
|
|
39
|
+
|
|
40
|
+
Arguments:
|
|
41
|
+
t (float): the best-so-far optimal value
|
|
42
|
+
"""
|
|
43
|
+
self._h.update(t)
|
|
44
|
+
|
|
45
|
+
def assess_feas(self, x) -> Optional[Cut]:
|
|
46
|
+
"""Make object callable for cutting_plane_feas()
|
|
47
|
+
|
|
48
|
+
Arguments:
|
|
49
|
+
x ([type]): [description]
|
|
50
|
+
|
|
51
|
+
Returns:
|
|
52
|
+
Optional[Cut]: [description]
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def get_weight(edge):
|
|
56
|
+
"""[summary]
|
|
57
|
+
|
|
58
|
+
Arguments:
|
|
59
|
+
edge ([type]): [description]
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
Any: [description]
|
|
63
|
+
"""
|
|
64
|
+
return self._h.eval(edge, x)
|
|
65
|
+
|
|
66
|
+
for cycle in self._ncf.howard(self._potential, get_weight):
|
|
67
|
+
f = -sum(self._h.eval(edge, x) for edge in cycle)
|
|
68
|
+
g = -sum(self._h.grad(edge, x) for edge in cycle)
|
|
69
|
+
# TODO: choose the minumum cycle
|
|
70
|
+
return g, f # use the first cycle only
|
|
71
|
+
|
|
72
|
+
return None
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
from typing import Optional, Tuple
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from .network_oracle import NetworkOracle
|
|
6
|
+
|
|
7
|
+
Arr = np.ndarray
|
|
8
|
+
Cut = Tuple[Arr, float]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class OptScalingOracle:
|
|
12
|
+
"""Oracle for Optimal Matrix Scaling
|
|
13
|
+
|
|
14
|
+
This example is taken from[Orlin and Rothblum, 1985]
|
|
15
|
+
|
|
16
|
+
| min π/ψ
|
|
17
|
+
| s.t. ψ ≤ u[i] * |aij| * u[j]^{−1} ≤ π,
|
|
18
|
+
| ∀ aij != 0,
|
|
19
|
+
| π, ψ, utx, positive
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
class Ratio:
|
|
23
|
+
def __init__(self, gra, get_cost):
|
|
24
|
+
"""[summary]
|
|
25
|
+
|
|
26
|
+
Arguments:
|
|
27
|
+
gra ([type]): [description]
|
|
28
|
+
"""
|
|
29
|
+
self._gra = gra
|
|
30
|
+
self._get_cost = get_cost
|
|
31
|
+
|
|
32
|
+
def eval(self, edge, x: Arr) -> float:
|
|
33
|
+
"""[summary]
|
|
34
|
+
|
|
35
|
+
Arguments:
|
|
36
|
+
edge ([type]): [description]
|
|
37
|
+
x (Arr): (π, ψ) in log scale
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
float: function evaluation
|
|
41
|
+
"""
|
|
42
|
+
aij, aji = self._get_cost(edge)
|
|
43
|
+
return min(x[0] - aji, aij - x[1])
|
|
44
|
+
|
|
45
|
+
def grad(self, edge, x: Arr) -> Arr:
|
|
46
|
+
"""[summary]
|
|
47
|
+
|
|
48
|
+
Arguments:
|
|
49
|
+
edge ([type]): [description]
|
|
50
|
+
x (Arr): (π, ψ) in log scale
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
[type]: [description]
|
|
54
|
+
"""
|
|
55
|
+
aij, aji = self._get_cost(edge)
|
|
56
|
+
if x[0] - aji < aij - x[1]:
|
|
57
|
+
return np.array([1.0, 0.0])
|
|
58
|
+
return np.array([0.0, -1.0])
|
|
59
|
+
|
|
60
|
+
def __init__(self, gra, utx, get_cost):
|
|
61
|
+
"""Construct a new optscaling oracle object
|
|
62
|
+
|
|
63
|
+
Arguments:
|
|
64
|
+
gra ([type]): [description]
|
|
65
|
+
"""
|
|
66
|
+
self._network = NetworkOracle(gra, utx, self.Ratio(gra, get_cost))
|
|
67
|
+
|
|
68
|
+
def assess_optim(self, x: Arr, t: float) -> Tuple[Cut, Optional[float]]:
|
|
69
|
+
"""
|
|
70
|
+
Make object callable for cutting_plane_optim()
|
|
71
|
+
|
|
72
|
+
Arguments:
|
|
73
|
+
x (Arr): (π, ψ) in log scale
|
|
74
|
+
t (float): the best-so-far optimal value
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
Tuple[Cut, Optional[float]]
|
|
78
|
+
|
|
79
|
+
See also:
|
|
80
|
+
cutting_plane_optim
|
|
81
|
+
"""
|
|
82
|
+
if cut := self._network.assess_feas(x):
|
|
83
|
+
return cut, None
|
|
84
|
+
|
|
85
|
+
s = x[0] - x[1]
|
|
86
|
+
g = np.array([1.0, -1.0])
|
|
87
|
+
if (fj := s - t) > 0.0:
|
|
88
|
+
return (g, fj), None
|
|
89
|
+
|
|
90
|
+
return (g, 0.0), s
|
netoptim/skeleton.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This is a skeleton file that can serve as a starting point for a Python
|
|
3
|
+
console script. To run this script uncomment the following lines in the
|
|
4
|
+
``[options.entry_points]`` section in ``setup.cfg``::
|
|
5
|
+
|
|
6
|
+
console_scripts =
|
|
7
|
+
fibonacci = netoptim.skeleton:run
|
|
8
|
+
|
|
9
|
+
Then run ``pip install .`` (or ``pip install -e .`` for editable mode)
|
|
10
|
+
which will install the command ``fibonacci`` inside your current environment.
|
|
11
|
+
|
|
12
|
+
Besides console scripts, the header (i.e. until ``_logger``...) of this file can
|
|
13
|
+
also be used as template for Python modules.
|
|
14
|
+
|
|
15
|
+
Note:
|
|
16
|
+
This file can be renamed depending on your needs or safely removed if not needed.
|
|
17
|
+
|
|
18
|
+
References:
|
|
19
|
+
- https://setuptools.pypa.io/en/latest/userguide/entry_point.html
|
|
20
|
+
- https://pip.pypa.io/en/stable/reference/pip_install
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import argparse
|
|
24
|
+
import logging
|
|
25
|
+
import sys
|
|
26
|
+
|
|
27
|
+
from netoptim import __version__
|
|
28
|
+
|
|
29
|
+
__author__ = "Wai-Shing Luk"
|
|
30
|
+
__copyright__ = "Wai-Shing Luk"
|
|
31
|
+
__license__ = "MIT"
|
|
32
|
+
|
|
33
|
+
_logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# ---- Python API ----
|
|
37
|
+
# The functions defined in this section can be imported by users in their
|
|
38
|
+
# Python scripts/interactive interpreter, e.g. via
|
|
39
|
+
# `from netoptim.skeleton import fib`,
|
|
40
|
+
# when using this Python module as a library.
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def fib(n):
|
|
44
|
+
"""Fibonacci example function
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
n (int): integer
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
int: n-th Fibonacci number
|
|
51
|
+
"""
|
|
52
|
+
assert n > 0
|
|
53
|
+
a, b = 1, 1
|
|
54
|
+
for _i in range(n - 1):
|
|
55
|
+
a, b = b, a + b
|
|
56
|
+
return a
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# ---- CLI ----
|
|
60
|
+
# The functions defined in this section are wrappers around the main Python
|
|
61
|
+
# API allowing them to be called directly from the terminal as a CLI
|
|
62
|
+
# executable/script.
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_args(args):
|
|
66
|
+
"""Parse command line parameters
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
args (List[str]): command line parameters as list of strings
|
|
70
|
+
(for example ``["--help"]``).
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
:obj:`argparse.Namespace`: command line parameters namespace
|
|
74
|
+
"""
|
|
75
|
+
parser = argparse.ArgumentParser(description="Just a Fibonacci demonstration")
|
|
76
|
+
parser.add_argument(
|
|
77
|
+
"--version",
|
|
78
|
+
action="version",
|
|
79
|
+
version=f"netoptim {__version__}",
|
|
80
|
+
)
|
|
81
|
+
parser.add_argument(dest="n", help="n-th Fibonacci number", type=int, metavar="INT")
|
|
82
|
+
parser.add_argument(
|
|
83
|
+
"-v",
|
|
84
|
+
"--verbose",
|
|
85
|
+
dest="loglevel",
|
|
86
|
+
help="set loglevel to INFO",
|
|
87
|
+
action="store_const",
|
|
88
|
+
const=logging.INFO,
|
|
89
|
+
)
|
|
90
|
+
parser.add_argument(
|
|
91
|
+
"-vv",
|
|
92
|
+
"--very-verbose",
|
|
93
|
+
dest="loglevel",
|
|
94
|
+
help="set loglevel to DEBUG",
|
|
95
|
+
action="store_const",
|
|
96
|
+
const=logging.DEBUG,
|
|
97
|
+
)
|
|
98
|
+
return parser.parse_args(args)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def setup_logging(loglevel):
|
|
102
|
+
"""Setup basic logging
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
loglevel (int): minimum loglevel for emitting messages
|
|
106
|
+
"""
|
|
107
|
+
logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
|
|
108
|
+
logging.basicConfig(
|
|
109
|
+
level=loglevel, stream=sys.stdout, format=logformat, datefmt="%Y-%m-%d %H:%M:%S"
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def main(args):
|
|
114
|
+
"""Wrapper allowing :func:`fib` to be called with string arguments in a CLI fashion
|
|
115
|
+
|
|
116
|
+
Instead of returning the value from :func:`fib`, it prints the result to the
|
|
117
|
+
``stdout`` in a nicely formatted message.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
args (List[str]): command line parameters as list of strings
|
|
121
|
+
(for example ``["--verbose", "42"]``).
|
|
122
|
+
"""
|
|
123
|
+
args = parse_args(args)
|
|
124
|
+
setup_logging(args.loglevel)
|
|
125
|
+
_logger.debug("Starting crazy calculations...")
|
|
126
|
+
print(f"The {args.n}-th Fibonacci number is {fib(args.n)}")
|
|
127
|
+
_logger.info("Script ends here")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def run():
|
|
131
|
+
"""Calls :func:`main` passing the CLI arguments extracted from :obj:`sys.argv`
|
|
132
|
+
|
|
133
|
+
This function can be used as entry point to create console scripts with setuptools.
|
|
134
|
+
"""
|
|
135
|
+
main(sys.argv[1:])
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
if __name__ == "__main__":
|
|
139
|
+
# ^ This is a guard statement that will prevent the following code from
|
|
140
|
+
# being executed in the case someone imports this file instead of
|
|
141
|
+
# executing it as a script.
|
|
142
|
+
# https://docs.python.org/3/library/__main__.html
|
|
143
|
+
|
|
144
|
+
# After installing your project with pip, users can also run your Python
|
|
145
|
+
# modules as scripts via the ``-m`` flag, as defined in PEP 338::
|
|
146
|
+
#
|
|
147
|
+
# python -m netoptim.skeleton 42
|
|
148
|
+
#
|
|
149
|
+
run()
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: netoptim
|
|
3
|
+
Version: 0.1
|
|
4
|
+
Summary: Network Optimization Python Code
|
|
5
|
+
Home-page: https://github.com/luk036/netoptim
|
|
6
|
+
Author: Wai-Shing Luk
|
|
7
|
+
Author-email: luk036@gmail.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Project-URL: Documentation, https://pyscaffold.org/
|
|
10
|
+
Platform: any
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Programming Language :: Python
|
|
13
|
+
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
14
|
+
License-File: LICENSE.txt
|
|
15
|
+
Requires-Dist: importlib-metadata; python_version < "3.9"
|
|
16
|
+
Requires-Dist: networkx
|
|
17
|
+
Provides-Extra: testing
|
|
18
|
+
Requires-Dist: setuptools; extra == "testing"
|
|
19
|
+
Requires-Dist: pytest; extra == "testing"
|
|
20
|
+
Requires-Dist: pytest-cov; extra == "testing"
|
|
21
|
+
Requires-Dist: networkx; extra == "testing"
|
|
22
|
+
Requires-Dist: numpy; extra == "testing"
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
<!-- These are examples of badges you might want to add to your README:
|
|
26
|
+
please update the URLs accordingly
|
|
27
|
+
|
|
28
|
+
[](https://cirrus-ci.com/github/<USER>/netoptim)
|
|
29
|
+
[](https://netoptim.readthedocs.io/en/stable/)
|
|
30
|
+
[](https://coveralls.io/r/<USER>/netoptim)
|
|
31
|
+
[](https://pypi.org/project/netoptim/)
|
|
32
|
+
[](https://anaconda.org/conda-forge/netoptim)
|
|
33
|
+
[](https://pepy.tech/project/netoptim)
|
|
34
|
+
[](https://twitter.com/netoptim)
|
|
35
|
+
-->
|
|
36
|
+
|
|
37
|
+
[](https://pyscaffold.org/)
|
|
38
|
+
[](https://netoptim.readthedocs.io/en/latest/?badge=latest)
|
|
39
|
+
[](https://codecov.io/gh/luk036/netoptim)
|
|
40
|
+
|
|
41
|
+
# 🖧 netoptim
|
|
42
|
+
|
|
43
|
+
> Network Optimization Python Code
|
|
44
|
+
|
|
45
|
+
A longer description of your project goes here...
|
|
46
|
+
|
|
47
|
+
## Dependencies
|
|
48
|
+
|
|
49
|
+
- [luk036/ellalgo](https://github.com/luk036/ellalgo)
|
|
50
|
+
- [luk036/mywheel](https://github.com/luk036/mywheel)
|
|
51
|
+
- [luk036/digraphx](https://github.com/luk036/digraphx)
|
|
52
|
+
- networkx
|
|
53
|
+
- numpy
|
|
54
|
+
|
|
55
|
+
<!-- pyscaffold-notes -->
|
|
56
|
+
|
|
57
|
+
## 👉 Note
|
|
58
|
+
|
|
59
|
+
This project has been set up using PyScaffold 4.5. For details and usage
|
|
60
|
+
information on PyScaffold see https://pyscaffold.org/.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
netoptim/__init__.py,sha256=ethe4DV1CwbXvO2DSjEzt5SL_7jt2fxQnF4RPgRgTDI,577
|
|
2
|
+
netoptim/network_oracle.py,sha256=hJaiJ1Bc40OOq4RDCCCAPFno7WKrNkB11XfMqsS2510,2478
|
|
3
|
+
netoptim/optscaling_oracle.py,sha256=T6HevOn5SA0xnFUWq7eKyMbHNttygr30-RObsVxHKu8,2400
|
|
4
|
+
netoptim/skeleton.py,sha256=V1dgm3AdkUOtJOvW77z79V9ZSR0awv7HQ8LJqK-gSag,4219
|
|
5
|
+
netoptim-0.1.dist-info/licenses/LICENSE.txt,sha256=MyvlyWiWdJ3ZpAOA4wziXlNa9Hbx8XnEL1Aztt9F7W8,1080
|
|
6
|
+
netoptim-0.1.dist-info/METADATA,sha256=0hFlLDCEMY9kXRiWVe15Nozs4Pd6C5pfyXbVmVTYKiU,2609
|
|
7
|
+
netoptim-0.1.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
|
8
|
+
netoptim-0.1.dist-info/top_level.txt,sha256=z782jnxUdVszVSqfpR6FM3fVfxDmxIB5rN4LpqyI1HA,9
|
|
9
|
+
netoptim-0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023 Wai-Shing Luk
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
netoptim
|