├── tests ├── .gitkeep ├── testgraph.png ├── test_ESPP.py ├── test_ESPPRC.py ├── tools.py └── test_random.py ├── pylgrim ├── __init__.py ├── path.py ├── tools.py ├── ESPP.py └── ESPPRC.py ├── pyproject.toml ├── .gitignore ├── README.md ├── docs └── algorithms_explained.md └── LICENSE /tests/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/testgraph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ToonWeyens/pylgrim/HEAD/tests/testgraph.png -------------------------------------------------------------------------------- /pylgrim/__init__.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.0.6' 2 | __name__ = 'pylgrim' 3 | from . import ESPP as ESPP 4 | from . import ESPPRC as ESPPRC 5 | from . import tools as tools 6 | from . import path as path -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["hatchling"] 3 | build-backend = "hatchling.build" 4 | 5 | [project] 6 | name = "pylgrim" 7 | dynamic = ["version"] # <--- This tells uv "Go look for the version in the code" 8 | description = "Elementary shortest path problems, with or without resource constraints" 9 | readme = "README.md" 10 | requires-python = ">=3.11" 11 | authors = [ 12 | { name = "Toon Weyens", email = "toon.weyens@gmail.com" }, 13 | { name = "Daan Van Vugt", email = "dvanvugt@ignitioncomputing.com" }, 14 | ] 15 | keywords = ["espp", "espprc", "shortest-path", "graph", "python"] 16 | classifiers = [ 17 | "Programming Language :: Python :: 3", 18 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 19 | "Operating System :: OS Independent", 20 | ] 21 | dependencies = [ 22 | "networkx>=3.6", 23 | "numpy>=2.3.5", 24 | ] 25 | 26 | [project.urls] 27 | Homepage = "https://github.com/ToonWeyens/pylgrim" 28 | 29 | # This configures Hatch to find the version in your __init__.py file 30 | # just like your old setup.py did. 31 | [tool.hatch.version] 32 | path = "pylgrim/__init__.py" 33 | 34 | [tool.hatch.build.targets.wheel] 35 | packages = ["pylgrim"] 36 | 37 | [dependency-groups] 38 | dev = [ 39 | "deptry>=0.24.0", 40 | "matplotlib>=3.10.7", 41 | "pytest>=9.0.1", 42 | "ruff>=0.14.7", 43 | ] 44 | -------------------------------------------------------------------------------- /tests/test_ESPP.py: -------------------------------------------------------------------------------- 1 | # test using ESPP on a simple test graph. 2 | # Note: The results can be different compared to test_ESPPRC because here resources are not taken into account. 3 | import pylgrim 4 | import logging 5 | import tools as testtools 6 | 7 | # possible values are: WARNING, INFO, DEBUG, ... 8 | # (see https://docs.python.org/3/library/logging.html#logging-levels) 9 | logging.basicConfig(level=logging.WARNING) 10 | logger = logging.getLogger(__name__) 11 | 12 | def test_ESPP_run(): 13 | # create test graph 14 | # G = testtools.create_test_graph(add_nodes_to_0=True) 15 | G = testtools.create_test_graph(add_nodes_to_0=False) 16 | source = 0 17 | print('Testing with {} nodes'.format(len(G))) 18 | print('') 19 | 20 | # move source in-edges to a new node 21 | source_in = 'source_in' 22 | pylgrim.tools.decouple_source(G, source, source_in=source_in) 23 | 24 | # solve for min_K number of paths 25 | min_K = 1 26 | paths, costs = pylgrim.ESPP.DLA(G, source, min_K, log_summary=True) 27 | 28 | print('solution paths:') 29 | for node in paths: 30 | print(' ending in node {}:'.format(node)) 31 | for path in paths[node]: 32 | print(' '+str(path)+' with cost '+str(costs[node][paths[node].index(path)])) 33 | 34 | # visualize 35 | # testtools.visualize_path(G, path) 36 | 37 | # move source in-edges back from new node 38 | pylgrim.tools.undecouple_source(G, source, source_in=source_in) 39 | 40 | 41 | if __name__ == "__main__": 42 | test_ESPP_run() -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # profiling 104 | *.prof 105 | -------------------------------------------------------------------------------- /tests/test_ESPPRC.py: -------------------------------------------------------------------------------- 1 | # test using ESPPRC on the simple test graph. 2 | # Note: The results can be different compared to test_ESPP because here resources are taken into account. 3 | import pylgrim 4 | import logging 5 | import tools as testtools 6 | 7 | # possible values are: WARNING, INFO, DEBUG, ... 8 | # (see https://docs.python.org/3/library/logging.html#logging-levels) 9 | logging.basicConfig(level=logging.WARNING) 10 | logger = logging.getLogger(__name__) 11 | 12 | # optional keywords that should also work without using them 13 | res_name = 'res_cost' 14 | 15 | def test_ESPPRC_run(): 16 | # create test graph 17 | G = testtools.create_test_graph(add_nodes_to_0=True) 18 | source = 0 19 | print('Testing with {} nodes'.format(len(G))) 20 | print('') 21 | 22 | # move source in-edges to a new node 23 | source_in = 'source_in' 24 | pylgrim.tools.decouple_source(G, source, source_in=source_in) 25 | 26 | # profiling: use `python -m cProfile -o test_ESPPRC.prof test_ESPPRC.py`, 27 | # followed, for example, by opening up a python notebook and running 28 | # import pstats 29 | # p = pstats.Stats('test_ESPPRC.prof') 30 | # p.sort_stats('cumtime') 31 | # p.print_stats(100) 32 | profiling = False 33 | 34 | if profiling: 35 | n_runs = 100 36 | else: 37 | n_runs = 1 38 | 39 | for _ in range(n_runs): 40 | # solve using ESPPRC 41 | #target = 4 42 | target = source_in 43 | max_res = list([1.0,1.0]) 44 | G_pre, res_min = pylgrim.ESPPRC.preprocess(G, source, target, max_res, res_name=res_name) 45 | shortest_path, shortest_path_label = pylgrim.ESPPRC.GSSA(G_pre, source, target, max_res, res_min, res_name=res_name) 46 | 47 | if profiling: 48 | continue 49 | 50 | print('shortest path found: {} with label {}'.format(shortest_path, shortest_path_label)) 51 | print('') 52 | 53 | while True: 54 | try: 55 | e = shortest_path.__next__() 56 | print('{} ⇨ {} : {}'.format(*e)) 57 | print('') 58 | except StopIteration: 59 | # last element reached 60 | break 61 | 62 | # visualize 63 | #testtools.visualize_path(G, shortest_path) 64 | 65 | # move source in-edges back from new node 66 | pylgrim.tools.undecouple_source(G, source, source_in=source_in) 67 | 68 | 69 | if __name__ == "__main__": 70 | test_ESPPRC_run() -------------------------------------------------------------------------------- /pylgrim/path.py: -------------------------------------------------------------------------------- 1 | # Path for pylgrim result: 2 | # * Is an elementary simple digraph that inherits from nx.DiGraph. 3 | # * As it can be cyclic, it contains the information of source node. 4 | # * Iterator for next edge in path can be returned. 5 | # 6 | # Author: 7 | # Toon Weyens 8 | 9 | import networkx as nx 10 | 11 | class Path(nx.DiGraph): 12 | """Result path with source copied from graph G""" 13 | def __new__(cls, *args, **kwargs): 14 | # We catch 'G' and 'nodes' in *args, but we don't pass them up. 15 | # We just ask the parent (DiGraph) to make a blank object. 16 | # In __init__ we will fill it. 17 | return super().__new__(cls) 18 | 19 | def __init__(self, G, nodes): 20 | super(Path, self).__init__(n_res=G.graph['n_res']) 21 | self.source = nodes[0] 22 | self.curr_node = nodes[0] 23 | for e_id in range(0,len(nodes)-1): 24 | n1, n2 = nodes[e_id:e_id+2] 25 | self.add_edge(n1, n2) 26 | for attr in G[n1][n2]: 27 | self[n1][n2][attr] = G[n1][n2][attr] 28 | 29 | def __str__(self): 30 | path_str = str(self.source) 31 | node = self.source 32 | while True: 33 | try: 34 | node = list(self.succ[node])[0] 35 | path_str += ' ⇨ ' + str(node) 36 | except IndexError: 37 | # last element reached 38 | break 39 | except KeyError: 40 | # first element had no successors 41 | break 42 | return path_str 43 | 44 | def __repr__(self): 45 | """identical to __str__ without the arrow.""" 46 | path_str = str(self.source) 47 | node = self.source 48 | while True: 49 | try: 50 | node = list(self.succ[node])[0] 51 | path_str += ' ' + str(node) 52 | except IndexError: 53 | # last element reached 54 | break 55 | except KeyError: 56 | # first element had no successors 57 | break 58 | return path_str 59 | 60 | def __eq__(x,y): 61 | """Path considers only differences of the nodes variable.""" 62 | return repr(x) == repr(y) 63 | 64 | def __hash__(self): 65 | """Path considers only differences of the nodes variable.""" 66 | return hash(repr(self)) 67 | 68 | def __iter__(self): 69 | # reset the counter to source when iterator is created 70 | self.curr_node = self.source 71 | return self 72 | 73 | def __next__(self): 74 | """Get next edge of path. 75 | Returns tuple with previous node, next node and edge attributes""" 76 | while True: 77 | prev_node = self.curr_node 78 | try: 79 | self.curr_node = list(self.succ[prev_node])[0] 80 | return (prev_node, self.curr_node, self[prev_node][self.curr_node]) 81 | except IndexError: 82 | # last element reached 83 | raise StopIteration 84 | except KeyError: 85 | # first element had no successors 86 | raise StopIteration 87 | -------------------------------------------------------------------------------- /tests/tools.py: -------------------------------------------------------------------------------- 1 | # Tools for pylgrim tests: 2 | # * create_test_graph to create a test graph. 3 | # 4 | # Author: 5 | # Toon Weyens 6 | 7 | import numpy as np 8 | import networkx as nx 9 | import matplotlib.pyplot as plt 10 | 11 | def create_test_graph(add_nodes_to_0=False): 12 | """create test based on graph from [1] 13 | (see 'testgraph.png') 14 | With the flag {add_nodes_to_0} the graph can be extended with two nodes to 0""" 15 | G = nx.DiGraph(n_res=2) 16 | G.add_edge(0, 1, weight=2, res_cost=np.array([0.1,0.2])) 17 | G.add_edge(0, 2, weight=-4, res_cost=np.array([0.1,0.2])) 18 | G.add_edge(1, 2, weight=-7, res_cost=np.array([0.1,0.2])) 19 | G.add_edge(1, 4, weight=5, res_cost=np.array([0.1,0.3])) 20 | G.add_edge(2, 3, weight=2, res_cost=np.array([0.1,0.2])) 21 | G.add_edge(3, 1, weight=1, res_cost=np.array([0.1,0.2])) 22 | G.add_edge(2, 5, weight=-2, res_cost=np.array([0.1,0.2])) 23 | G.add_edge(5, 6, weight=2, res_cost=np.array([0.1,0.2])) 24 | G.add_edge(5, 4, weight=-2, res_cost=np.array([0.1,0.2])) 25 | G.add_edge(4, 2, weight=3, res_cost=np.array([0.1,0.2])) 26 | G.add_edge(4, 6, weight=3, res_cost=np.array([0.1,0.3])) 27 | if add_nodes_to_0: 28 | # add nodes to 0 for test 29 | G.add_edge(6, 0, weight=-1, res_cost=np.array([0.1,0.2])) 30 | G.add_edge(1, 0, weight=-2, res_cost=np.array([0.1,0.2])) 31 | 32 | return G 33 | 34 | def _lighter(color, percent): 35 | """Makes a color lighter. Adapted from https://stackoverflow.com/a/28033054. 36 | Assumes color is rgb between (0, 0, 0) and (255, 255, 255)""" 37 | color = np.array(_hex2RGB(color)) 38 | white = np.array([255, 255, 255]) 39 | vector = white-color 40 | if percent < 0.0 or percent > 100.0: 41 | raise ValueError('percent must be between 0 and 100') 42 | 43 | return RGB2hex(color + vector * percent/100.0) 44 | 45 | def _hex2RGB(h): 46 | """Returns an RGB tuple for a hex string. 47 | Adapted from https://stackoverflow.com/a/29643643.""" 48 | if h[0] != '#' or len(h) !=7 : 49 | raise ValueError('not a hex string') 50 | 51 | return tuple(int(h.lstrip('#')[i:i+2], 16) for i in (0, 2 ,4)) 52 | 53 | def _RGB2hex(rgb): 54 | """Returns an hex string for an RGB tuple. 55 | Adapted from from https://stackoverflow.com/a/214657.""" 56 | if len(rgb) != 3 or np.amax(rgb) > 255 or np.amin(rgb) < 0: 57 | raise ValueError('not a rgb tuple') 58 | 59 | return '#%02x%02x%02x' % (int(rgb[0]), int(rgb[1]), int(rgb[2])) 60 | 61 | def visualize_path(G, path): 62 | """Visualize a path""" 63 | pos = nx.circular_layout(G) 64 | colors = list() 65 | weights = list() 66 | max_weight = np.amax([abs(sublist[-1]) for sublist in G.edges.data('weight', default=0.0)]) 67 | 68 | # colors for positive (0) and negative (1) edges 69 | #max_colors = tuple(['#B1D877', '#ADD9FE']) 70 | max_colors = tuple(['#FF0000', '#0000FF']) 71 | 72 | # set up widths and colors 73 | for u, v in G.edges(): 74 | if path.has_edge(u,v): 75 | colors.append('black') 76 | weights.append(3) 77 | else: 78 | if G[u][v]['weight'] > 0: 79 | colors.append(_lighter(max_colors[0], 100*((max_weight-abs(G[u][v]['weight']))/max_weight))) 80 | else: 81 | colors.append(_lighter(max_colors[1], 100*((max_weight-abs(G[u][v]['weight']))/max_weight))) 82 | weights.append(2) 83 | 84 | nx.draw(G, pos, edgelist=G.edges(), edge_color=colors, node_color = '#8CDCDA', width=weights) 85 | nx.draw_networkx_labels(G, pos, labels=None, font_size=12, font_color='k', font_family='sans-serif', font_weight='normal', alpha=1.0) 86 | plt.show() 87 | 88 | return 89 | -------------------------------------------------------------------------------- /tests/test_random.py: -------------------------------------------------------------------------------- 1 | # test using EPSPRC on a random graph. 2 | # Note: The results can be different compared to test_ESPP because here resources are taken into account. 3 | import networkx as nx 4 | import matplotlib.pyplot as plt 5 | import logging 6 | import pylgrim 7 | import random 8 | import time 9 | 10 | def print_path(G, path): 11 | CHECK = 0.0 12 | while True: 13 | try: 14 | e = path.__next__() 15 | print('{} ⇨ {} : {}'.format(*e)) 16 | CHECK += G[e[0]][e[1]]['weight'] 17 | except StopIteration: 18 | # last element reached 19 | break 20 | 21 | return CHECK 22 | 23 | def test_random_run(): 24 | # possible values are: WARNING, INFO, DEBUG, ... 25 | # (see https://docs.python.org/3/library/logging.html#logging-levels) 26 | logging.basicConfig(level=logging.WARNING) 27 | logger = logging.getLogger(__name__) 28 | 29 | # parameters 30 | graph_size = 15 31 | max_path_len = 16 32 | max_res = list([1.0]) 33 | source = 0 34 | weight_lims = (-1.0, 1.0) 35 | 36 | # set seed and target 37 | seed = random.randint(-2**31-1, 2**31) 38 | 39 | # If you want to debug a failed run 40 | # seed = -948430401 # for 5 nodes and max_path _len 6 41 | # seed = 1777749916 # for 6 nodes and max_path len 7 42 | # seed = -1370462526 # for 10 nodes and path length 11 43 | seed = -1213136599 # for 15 nodes and path length 16 44 | 45 | # set random seed to make sure edges are also the same 46 | random.seed(seed) 47 | 48 | # create test graph: inverted gnc_graph or gnp random graph 49 | G = nx.gnp_random_graph(graph_size, p=0.2, directed=True, seed=seed) 50 | target = G.number_of_nodes() 51 | G.add_node(target) 52 | 53 | print('source = {}, target = {}'.format(source, target)) 54 | print('maximum length of path: {}'.format(max_path_len)) 55 | print('') 56 | 57 | # add one resource to limit path length and one for weight 58 | G.graph['n_res']=1 59 | for u, v in G.edges(): 60 | G[u][v]['res_cost'] = [float(r)/(max_path_len-0.9) for r in max_res] 61 | G[u][v]['weight'] = random.uniform(weight_lims[0], weight_lims[1]) 62 | 63 | # decouple (actually not necessary) 64 | pylgrim.tools.decouple_source(G, source, source_in=target) 65 | 66 | # pre-process and calculate res_min 67 | check_costs = [] 68 | G_pre, res_min = pylgrim.ESPPRC.preprocess(G, source, target, max_res) 69 | 70 | # ESPPRC 71 | t0 = time.perf_counter() 72 | shortest_path, shortest_path_label = pylgrim.ESPPRC.GSSA(G_pre, source, target, max_res, res_min) 73 | time_ESPPRC = time.perf_counter() - t0 74 | 75 | # ESPP 76 | t0 = time.perf_counter() 77 | paths, costs = pylgrim.ESPP.DLA(G, source, min_K=1, log_summary=True) 78 | time_ESPP = time.perf_counter() - t0 79 | node = target 80 | path = paths[node][0] 81 | 82 | print('ESPPRC:') 83 | print('------') 84 | print('elapsed time: {}s'.format(time_ESPPRC)) 85 | print('shortest path found: {} with label {}'.format(shortest_path, shortest_path_label)) 86 | print('') 87 | check_costs.append(print_path(G, shortest_path)) 88 | print('') 89 | 90 | print('ESPP:') 91 | print('----') 92 | print('elapsed time: {}s'.format(time_ESPP)) 93 | print('best solution path to target:') 94 | print('shortest path found: {} with cost {}'.format(path, costs[node][paths[node].index(path)])) 95 | print('') 96 | check_costs.append(print_path(G, path)) 97 | print('') 98 | 99 | # check 100 | if check_costs[0] != check_costs[1]: 101 | print('WARNING: costs are not equal: {} vs {}'.format(*check_costs)) 102 | print('(seed was equal to {})'.format(seed)) 103 | print('The most probably explanation is that max_path_len is too small for ESPPRC to find the optimal path.') 104 | 105 | pos = nx.circular_layout(G) 106 | nx.draw(G, pos) 107 | edge_labels = nx.get_edge_attributes(G,'weight') 108 | for key in edge_labels: 109 | edge_labels[key] = round(edge_labels[key], 2) 110 | nx.draw_networkx_edge_labels(G, pos, edge_labels) 111 | nx.draw_networkx_labels(G, pos, labels=None, font_size=12, font_color='k', font_family='sans-serif', font_weight='normal', alpha=1.0) 112 | plt.show() 113 | 114 | if __name__ == "__main__": 115 | test_random_run() 116 | -------------------------------------------------------------------------------- /pylgrim/tools.py: -------------------------------------------------------------------------------- 1 | # Tools for pylgrim: 2 | # * decouple_source and undecouple_source to move all in-edges from a source node to a duplicate and vice versa. 3 | # * print_path to pretty print a path. 4 | # * count_elems to count the number of elements in a path and return a dictionary keyed with a label. 5 | # * print_dynamic_k to dynamically print K values as bars in the terminal. 6 | # 7 | # Author: 8 | # Toon Weyens 9 | 10 | import logging 11 | import sys 12 | import shutil 13 | 14 | #logging.basicConfig(level=logging.DEBUG) 15 | logger = logging.getLogger(__name__) 16 | 17 | def decouple_source(G, source, source_in="source_in"): 18 | """Decouple the source {source} of a graph {G}, by duplicating the node, called {source_in} and moving all the in-edges to it. 19 | Returns the number of edges displaced.""" 20 | 21 | in_edges_source = tuple(G.in_edges(source)) 22 | n_in_edges_source = len(in_edges_source) 23 | if n_in_edges_source > 0: 24 | logger.debug('displace {} in-edges ⇨ {}'.format(n_in_edges_source,source)) 25 | 26 | for e in in_edges_source: 27 | logger.debug(' move edge {}'.format(e)) 28 | G.add_edge(e[0],source_in) 29 | for attr in G[e[0]][e[1]]: 30 | G[e[0]][source_in][attr] = G[e[0]][e[1]][attr] 31 | G.remove_edge(*e) 32 | 33 | return n_in_edges_source 34 | 35 | 36 | def undecouple_source(G, source, source_in="source_in"): 37 | """Invert the decoupling of the source {source} of a graph {G} done in decouple_source by moving all the edges to {source_in} back to {source}. 38 | Returns the number of edges displaced.""" 39 | 40 | in_edges_source = tuple(G.in_edges(source_in)) 41 | n_in_edges_source = len(in_edges_source) 42 | if n_in_edges_source > 0: 43 | logger.debug('place back {} in-edges {} - {}'.format(n_in_edges_source,source, in_edges_source)) 44 | 45 | for e in in_edges_source: 46 | G.add_edge(e[0],source) 47 | for attr in G[e[0]][e[1]]: 48 | G[e[0]][source][attr] = G[e[0]][e[1]][attr] 49 | G.remove_edge(e[0],source_in) 50 | G.remove_node(source_in) 51 | 52 | return n_in_edges_source 53 | 54 | 55 | def print_path(path, max_path_len_for_print = None): 56 | """Pretty-print a path given as an iterable of strings. 57 | Optionally trim if longer than max_path_len_for_print 58 | """ 59 | path_short = str(path[0]) 60 | if max_path_len_for_print is None: 61 | max_path_len_for_print = len(path) 62 | if len(path) > max_path_len_for_print + 1: 63 | for p in range(1,max_path_len_for_print-1): 64 | path_short += ' ⇨ ' + str(path[p]) 65 | path_short += ' ⇨ … ⇨ ' + str(path[len(path)-1]) 66 | else: 67 | for p in range(1,len(path)): 68 | path_short += ' ⇨ ' + str(path[p]) 69 | return path_short 70 | 71 | 72 | def count_elems(path): 73 | """Count elements in a path and return a dictionary keyed with label""" 74 | res = dict() 75 | for n in path: 76 | res[n] = res.get(n,0)+1 77 | return res 78 | 79 | 80 | # Unicode blocks representing 1/8th increments for high-resolution bars 81 | _BLOCKS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"] 82 | 83 | 84 | def print_dynamic_k(K, previous_lines_printed=0, label="K Values", div_factor=1): 85 | """ 86 | Visualizes K by padding lines with physical spaces to overwrite old text. 87 | No weird ANSI reset codes. 88 | """ 89 | 90 | # 1. Clear previous output 91 | if previous_lines_printed > 0: 92 | # Move cursor up 93 | sys.stdout.write(f"\033[{previous_lines_printed}F") 94 | 95 | sorted_nodes = sorted(K.keys()) 96 | 97 | # Get current terminal width 98 | term_width = shutil.get_terminal_size((80, 20)).columns 99 | 100 | # Reserve space for text like "Node XX: " and " (123)" 101 | # We subtract a bit extra to be safe from auto-wrapping 102 | max_bar_width = term_width - 25 103 | 104 | max_val = max(K.values()) if K else 1 105 | if max_val == 0: max_val = 1 106 | 107 | lines_to_print = [] 108 | 109 | # Header: Pad with spaces to fill the width 110 | header = f"--- {label} Monitor ---" 111 | padding = " " * (term_width - len(header) - 1) 112 | lines_to_print.append(header + padding) 113 | 114 | for n in sorted_nodes: 115 | val = K[n] 116 | 117 | # --- SCALING LOGIC --- 118 | val_scaled = val / div_factor 119 | 120 | # If scaled value fits, use it. If not, scale down relative to max. 121 | if (max_val / div_factor) > max_bar_width: 122 | display_val = (val_scaled / (max_val / div_factor)) * max_bar_width 123 | else: 124 | display_val = val_scaled 125 | 126 | # Build the bar 127 | full_blocks = int(display_val) 128 | remainder = int((display_val - full_blocks) * 8) 129 | bar = ("█" * full_blocks) + _BLOCKS[remainder] 130 | 131 | # --- THE FIX: MANUAL PADDING --- 132 | # 1. Build the content 133 | content = f"Node {n:>3}: {bar} ({val})" 134 | 135 | # 2. Calculate how many spaces we need to reach the edge of the terminal 136 | # We use -1 to ensure we don't accidentally trigger a newline wrap 137 | spaces_needed = term_width - len(content) - 1 138 | 139 | if spaces_needed > 0: 140 | padding = " " * spaces_needed 141 | else: 142 | padding = "" 143 | 144 | # 3. Append content + physical spaces 145 | lines_to_print.append(content + padding) 146 | 147 | # Print block 148 | sys.stdout.write("\n".join(lines_to_print) + "\n") 149 | sys.stdout.flush() 150 | 151 | return len(lines_to_print) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Elementary Shortest Path Problem with or without Resource Constraint 2 | This module solves the shortest elementary path problem, by which it is meant that each node in a path can only be visited once. 3 | The edge weights do not need to be nonnegative. 4 | 5 | Two main algorithms are provided: 6 | 1. **ESPP (`DLA`)**: Solves the Elementary Shortest Path Problem from a single source to all other nodes. This algorithm is based on solving the *k-paths* problem repeatedly [1]. 7 | 2. **ESPPRC (`GSSA`)**: Solves the Elementary Shortest Path Problem with Resource Constraints from a single source to a single target. This uses a two-phase approach: preprocessing and state-space augmentation [2]. This is the recommended algorithm for most use cases. 8 | 9 | ## Installation 10 | * **PyPI**: `pip install pylgrim` 11 | * **From source** (recommended with `uv`): 12 | * Clone this repository 13 | * `uv sync --group dev` (installs runtime + dev/test deps) 14 | * `uv run python -m pylgrim` or `uv run python your_script.py` 15 | 16 | **Requirements:** 17 | * Python >= 3.11 18 | * NetworkX 19 | * NumPy 20 | 21 | ## Usage 22 | 23 | ### Getting Started: Graph Preparation 24 | Before running any algorithm, your `networkx.DiGraph` must be prepared. 25 | 26 | 1. **Set Number of Resources**: The graph must have a `n_res` attribute specifying the number of resources. 27 | ```python 28 | import networkx as nx 29 | 30 | G = nx.DiGraph(n_res=1) 31 | # or if the graph already exists: 32 | # G.graph['n_res'] = 1 33 | ``` 34 | 35 | 2. **Define Edge Attributes**: 36 | * `weight`: All edges must have a `weight` attribute, representing the cost to be minimized. 37 | * `res_cost` (for ESPPRC): For the resource-constrained algorithm, each edge must also have a `res_cost` attribute. This must be a **list or NumPy array** of length `n_res`. 38 | 39 | 3. **Decouple the Source Node**: The algorithms require that the source node has no incoming edges. The `tools.decouple_source` function handles this by creating a temporary duplicate of the source node and redirecting all in-edges to it. This operation is done in-place. 40 | ```python 41 | from pylgrim import tools 42 | 43 | source_node = 'A' 44 | temp_source_in = 'source_in' # Temporary node name 45 | tools.decouple_source(G, source_node, source_in=temp_source_in) 46 | ``` 47 | After finding a path, you can revert the graph to its original state: 48 | ```python 49 | tools.undecouple_source(G, source_node, source_in=temp_source_in) 50 | ``` 51 | 52 | ### Recommended: Elementary Shortest Path with Resource Constraints (ESPPRC) 53 | This algorithm finds the shortest path between a **single source and single target** while respecting resource limits. It is a two-step process. 54 | 55 | First, import the necessary modules: 56 | ```python 57 | from pylgrim import ESPPRC, tools 58 | import networkx as nx 59 | import numpy as np 60 | ``` 61 | 62 | **Step 1: Preprocessing** 63 | The `ESPPRC.preprocess` function prunes the graph, discarding nodes that cannot be part of a valid path (e.g., due to resource limits) and pre-calculates minimal resource paths. This is a mandatory first step. 64 | 65 | **Step 2: GSSA Algorithm** 66 | The `ESPPRC.GSSA` (General State Space Augmenting) algorithm then searches the preprocessed graph for the optimal path. 67 | 68 | #### Complete Example: 69 | ```python 70 | from pylgrim import ESPPRC, tools 71 | import networkx as nx 72 | import numpy as np 73 | 74 | # 1. Create a directed graph with resource information 75 | G = nx.DiGraph(n_res=1) 76 | edges = [ 77 | ('A', 'B', {'weight': 1, 'res_cost': [1]}), 78 | ('B', 'C', {'weight': 1, 'res_cost': [1]}), 79 | ('A', 'D', {'weight': 0, 'res_cost': [3]}), 80 | ('D', 'C', {'weight': 3, 'res_cost': [1]}), 81 | ] 82 | G.add_edges_from(edges) 83 | 84 | source, target = 'A', 'C' 85 | max_res = np.array([3]) # Maximum resource consumption allowed 86 | 87 | # 2. Decouple the source node 88 | temp_source_in = 'source_in' 89 | tools.decouple_source(G, source, source_in=temp_source_in) 90 | 91 | # 3. Preprocess the graph 92 | # This returns a reduced graph and minimum resource costs. 93 | G_reduced, res_min = ESPPRC.preprocess( 94 | G, source, target, max_res, res_name='res_cost' 95 | ) 96 | 97 | # 4. Run the GSSA algorithm 98 | best_path, best_path_label = ESPPRC.GSSA( 99 | G_reduced, source, target, max_res, res_min, res_name='res_cost' 100 | ) 101 | 102 | # 5. Process the result 103 | if best_path: 104 | print(f"Shortest path found: {best_path}") 105 | print(f"Cost: {best_path_label[0]}") 106 | print(f"Resources consumed: {best_path_label[1]}") 107 | 108 | # The 'best_path' object is a pylgrim.Path, which can be iterated over 109 | print("Edges in path:") 110 | for u, v, data in best_path.edges(data=True): 111 | print(f" - ({u} -> {v}), Weight: {data['weight']}") 112 | else: 113 | print("No path found.") 114 | 115 | # Expected output: 116 | # Shortest path found: A -> B -> C 117 | # Cost: 2 118 | # Resources consumed: [2] 119 | # Edges in path: 120 | # - (A -> B), Weight: 1 121 | # - (B -> C), Weight: 1 122 | ``` 123 | 124 | ### Advanced Usage: Finding a Tour/Cycle 125 | You can use the ESPPRC algorithm to find a shortest path that **returns to the origin** (a tour or cycle). To do this, set the `target` of the `GSSA` function to the temporary `source_in` node created by `decouple_source`. 126 | 127 | ```python 128 | # To find a path from 'A' back to 'A' 129 | # The target is the temporary node created during decoupling 130 | tour_target = temp_source_in 131 | 132 | # Preprocess and run GSSA as before, but with the new target 133 | G_reduced_tour, res_min_tour = ESPPRC.preprocess(G, source, tour_target, max_res) 134 | tour_path, tour_label = ESPPRC.GSSA(G_reduced_tour, source, tour_target, max_res, res_min_tour) 135 | 136 | if tour_path: 137 | print(f"Shortest tour found: {tour_path}") 138 | ``` 139 | 140 | 141 | ### Legacy: Elementary Shortest Path (ESPP) 142 | This algorithm finds the shortest elementary paths from a **single source to all other nodes**. Due to its performance issues and the flaw described above, its use is discouraged for all but very small graphs. 143 | 144 | ```python 145 | from pylgrim import ESPP 146 | 147 | # Ensure graph is decoupled as shown above 148 | paths, costs = ESPP.DLA(G, source) 149 | 150 | # 'paths' is a dictionary mapping target nodes to a list of Path objects 151 | for destination, path_list in paths.items(): 152 | print(f"Paths to {destination}:") 153 | for p in path_list: 154 | print(f" - Path: {p}, Cost: {p.get_cost()}") 155 | ``` 156 | 157 | ## The `Path` Object 158 | Both algorithms return results using the `pylgrim.Path` class, which inherits from `networkx.DiGraph`. It provides useful methods for inspecting the path, such as: 159 | * `path.edges(data=True)`: Iterate over edges and their data. 160 | * `path.get_cost()`: Get the total cost (sum of `weight` attributes). 161 | * Pretty-printing via `str(path)`. 162 | 163 | 164 | ## Testing 165 | * With uv (recommended): `uv run pytest` 166 | * With pip: install dev deps yourself (`matplotlib`, `pytest`) and run `pytest`. 167 | * Plots may be generated during tests. To debug, change `logging.WARNING` to `INFO` or `DEBUG` at the top of the relevant Python files. 168 | 169 | ## Algorithms explained 170 | See the full explanation of the DLA with TLAdynK algorithm and other details in [Algorithms Explained](./docs/algorithms_explained.md). 171 | 172 | ## References 173 | [1] Di Puglia Pugliese, L. (2015). *On the shortest path problem with negative cost cycles*. DOI: 10.1007/s10589-015-9773-1 174 | 175 | [2] Boland, N., et al. (2006). *Accelerated label setting algorithms for the elementary resource constrained shortest path problem*. DOI: 10.1016/j.orl.2004.11.011 176 | 177 | ## Copyright 178 | Copyright 2018-2025 Toon Weyens, Daan van Vugt 179 | -------------------------------------------------------------------------------- /docs/algorithms_explained.md: -------------------------------------------------------------------------------- 1 | ## Algorithms explained 2 | 3 | ### DLA with TLAdynK 4 | 5 | This stands for **Dynamic Labeling Approach** [1, algorithm 4] with **Truncated labelling algorithm for dynamic kSPP** [1, algorithm 3]. 6 | 7 | #### Core idea 8 | - The strategy of the Dynamic Labeling Approach (DLA) can be thought of as an extension of the Bellman-Ford (BF) algorithm 9 | - To deal with the fact that BF cannot handle negative sum cycles (NCC), DLA uses memory to store multiple paths per node, ranked by cost 10 | - When the algorithm is considering extending a path to a neighboring node, therefore, it can discard the NCCs and try another one of the paths in its memory 11 | - If the memory is large enough this ensures that we can always bypass NCCs and still find the optimal elementary path 12 | - However storing many paths per node comes at a steep cost: 13 | - increased compute: Need to iterate over more potential paths. In worst case this leads to $\mathcal{O} (n^2K^4)$ scaling [1, Lemma 2] 14 | - increased memory: Need to store more paths. This is not typically a problem 15 | - It is therefore crucial to limit the memory of each each node 16 | - The DLA handles this judiciously, starting with only allowing minimal memory for each node and lazily increases memory per node when NCCs are detected that cannot be bypassed with the current memory 17 | 18 | #### Concepts 19 | - **Path**: We consider paths from the source $s$ to a node $i$, denoted $\pi_{si}$ as the succession of individual arcs $(a,b)$ that connect $s$ to $i$ 20 | - **Truncation**: We store up to $K_i$ paths per node $i$ with $k=1\ldots K_i$, indicated by superscript $k$ as $\pi_{si}^k$ 21 | - **Cost**: Every such path also has a cost associated $c(\pi_{si}^k)$ that is the sum of all the individual arc costs $\sum c_{ab}$ for the arcs in the path 22 | - **Dynamic programming**: We use a dynamic programming algorithm to explore new paths as extensions of the current end point of a path 23 | - **Node list**: We keep track of all nodes that are still good candidates for extension in a list $L$ 24 | - **neighbor**: By neighbor we will consider all nodes that can be reached from a certain node, i.e. only out-edges 25 | 26 | #### High level steps 27 | - Initialization: 28 | - Set number of paths $K_i=1$ for all nodes $i$ 29 | - Set cost $c(\pi_{si}^1) = \infty$ for (the only path $1$ in) node $i$, making sure that each path found will be lower in cost 30 | - Set $L=[s]$: We'll start exploring with the souce node $s$ 31 | - First iteration 32 | - Pop the first node in our list $L$, which is at this moment also the only node $s$ and explore its neighbors $i$ 33 | - This first iteration all paths $\pi_{si}^k$ will automatically be best paths with cost equal to $c_{si}$ 34 | - Add all nodes $i$ that have new paths found to the list $L$ 35 | - Subsequent iterations 36 | - Go through the first node $u$ on the list $L$ 37 | - Start exploring its neighbors $v$ 38 | - Iterate over all current paths $\pi_{su}^k$ to $u$ and see if we can extend any of them to $v$ in an elementary way (i.e. without creating a cycle) 39 | - If this new path $\pi_{sv}^{k'} = \pi_{su}^k + (u,v)$ is cheaper than the worst currently stored path to $v$ (i.e. $c(\pi_{sv}^{k'}) < c(\pi_{sv}^{K_v})$): 40 | - We add it to the list of paths to $v$ 41 | - We evict the worst path if necessary to keep only $K_v$ paths 42 | - We also add $v$ to the list $L$ to make sure we will explore it later 43 | - If we detect a NCC when trying to extend to $v$: 44 | - If we can bypass it using another path to $u$ we just skip 45 | - If we cannot bypass it because we have run out of memory in $u$: 46 | - We increase $K_u$ by 1 47 | - We restart the algorithm with the new memory limit (see below for details) 48 | - We continue this process for all paths to $u$ 49 | - We continue this process for all neighbors $v$ of $u$ 50 | - We continue for all nodes in the list $L$ 51 | - At this point, we have found the best elementary paths from $s$ to all other nodes 52 | 53 | #### Condition for increasing Memory $K_u$ 54 | - The algorithm deals with NCCs by taking the next possible path down the list of paths to a node stored in the memory 55 | - However, when the memory is full and we still detect a NCC that cannot be bypassed, we need to increase the memory $K_u$ for some nodes $u$ in the NCC 56 | - The criteria to determine this situation are as follows: 57 | - We have found a negative cycle 58 | - We cannot avoid it using the current paths because every path we know involves this cycle 59 | - We have no room left in memory to look for other paths that might bypass this cycle 60 | - More formally (and in reverse order): 61 | 1. **Saturation Check** - $c(\pi_{su}^k) < \infty, \forall k \in \{1, \dots, K_{u}\}$: There are no free slots in the memory for node $u$ 62 | 2. **Elementarity/Cycle Check** - $\nexists \hat{k} : v \notin \pi_{su}^{\hat{k}}$: Node $v$ is present in all currently stored paths to node $u$ 63 | 3. **Negative Cost Check** - $\exists \bar{k} : v \in \pi_{su}^{\bar{k}}$ such that $c(\pi_{su}^{\bar{k}}) + c_{uv} < c(\pi_{sv}^1)$: There exist a negative cost path better than current best path to $v$ 64 | - In this case we need to increase $K_l$ for each $l$ in the NCC that we just identified 65 | 66 | Notes on condition 3, to make this crystal clear: 67 | - Assuming condition 2 was met, we know that all paths to $u$ go through $v$ 68 | - If we denote this by $s \rightarrow A \rightarrow v \rightarrow B \rightarrow u$, which we are considering extending to $v$, forming a cycle $s \rightarrow A \rightarrow v \rightarrow B \rightarrow u \rightarrow v$ 69 | - We will now call $s \rightarrow A \rightarrow v$ a prefix of the path to $u$ and $s \rightarrow A \rightarrow v \rightarrow B \rightarrow u \rightarrow v$ the extended path to $v$ 70 | - The resulting situation is summarized in the following table: 71 | | | Extended path is better than current best path to $v$ | Extended path is worse than current best path to $v$ | 72 | | ---------------------------------------------- | ----- | ----- | 73 | | current best path to $v$ is prefix | NCC: We should increase $K$ | We can skip safely | 74 | | current best path to $v$ is better than prefix | Certainly NCC, as it was even able to overcome the advantage of path over prefix: We should increase $K$ | Might be a NCC that we can only detect with fair comparison, replacing prefix by best path to $v$. This will certainly happen as due the propagation mechanism of the algorithm, the node $v$ is waiting in the queue $L$: We can skip safely | 75 | | current best path to $v$ is worse than prefix | Logical impossibility | Logical impossibility | 76 | - The last row is a logical impossibility because: 77 | - It is possible for new paths to have been found to $v$ that have not yet ended up in $u$'s paths, but they would have been equal or better 78 | - All paths to $u$ that have gone through $v$ must necessarily be worse or equal to the best path to $v$ 79 | 80 | 81 | #### Restarting the Algorithm with increased memory 82 | - We need to restart the algorithm when we increase the memory $K_l$ for all nodes $l$ that were part of the NCC 83 | - However, we do not need to start working from scratch again. This is a major advantage of the DLA approach 84 | - We can keep all the paths we have already found so far, as they are still valid 85 | - We just need to make sure we re-explore the nodes that may be affected by the increased memory 86 | - Therefore we add all the nodes in the NCC to the list $L$ to make sure we will re-explore them 87 | - In practice we don't really need to even restart the algorithm, we can just continue from where we left off after adding the NCC nodes to $L$ 88 | 89 | 90 | ## References 91 | [1] Di Puglia Pugliese, L. (2015). *On the shortest path problem with negative cost cycles*. DOI: 10.1007/s10589-015-9773-1 92 | 93 | [2] Boland, N., et al. (2006). *Accelerated label setting algorithms for the elementary resource constrained shortest path problem*. DOI: 10.1016/j.orl.2004.11.011 94 | 95 | ## Copyright 96 | Copyright 2018-2025 Toon Weyens, Daan van Vugt -------------------------------------------------------------------------------- /pylgrim/ESPP.py: -------------------------------------------------------------------------------- 1 | # Solve Elementary Shortest Path Problem without resource constraints. 2 | # The algorithm is based on [1]. 3 | # Features: 4 | # * single source / all targets 5 | # * no resources 6 | # * elementary paths are sought by requesting more and more paths for nodes which have been found to form part of a NCC (negative cost cycle), when there is no alternative. 7 | ## 8 | # Author: 9 | # Toon Weyens 10 | # 11 | # References: 12 | # [1]: "On the shortest path problem with negative cost cycles" by Di Puglia Pugliese, Luigi (DOI: 10.1007/s10589-015-9773-1) 13 | from collections import deque, OrderedDict 14 | import logging 15 | from . import tools as pt 16 | from . import path as pth 17 | 18 | # logging.basicConfig(level=logging.DEBUG) 19 | logging.basicConfig(level=logging.WARNING) 20 | logging.getLogger("matplotlib").setLevel(logging.INFO) 21 | logging.getLogger("matplotlib.font_manager").setLevel(logging.INFO) 22 | 23 | logger = logging.getLogger(__name__) 24 | 25 | 26 | 27 | def TLAdynK(G, source, K, L, paths=None, costs=None): 28 | """Truncated labelling algorithm for dynamic kSPP 29 | (based on algorithm 3 from [1])""" 30 | 31 | inf = float('inf') 32 | 33 | # 1. Initialization 34 | if paths is None or costs is None: 35 | paths = {n: [None] * K[n] for n in G.nodes()} 36 | costs = {n: [inf] * K[n] for n in G.nodes()} 37 | paths[source][0] = [source] 38 | costs[source][0] = 0 39 | 40 | L_q = deque(L) 41 | 42 | # 2. main loop for selected node 43 | while L_q: 44 | # select element FIFO 45 | u = L_q.popleft() 46 | L.remove(u) 47 | logger.debug(f' Popping element {u} with current paths') 48 | for n in range(K[u]): 49 | if paths[u][n] is None: 50 | break 51 | logger.debug(f' {n}: {pt.print_path(paths[u][n])} ({costs[u][n]})') 52 | 53 | # extend label for each child 54 | for v, e in G.succ[u].items(): 55 | logger.debug(f' treating extension to {v}, weight = {e["weight"]} with current paths:') 56 | for n in range(K[v]): 57 | if paths[v][n] is None: 58 | break 59 | logger.debug(f' {n}: {pt.print_path(paths[v][n])} ({costs[v][n]})') 60 | logger.debug('') 61 | 62 | # error if the source is a child. The in-edges of the source need to be separated from the out-edges. 63 | if v == source: 64 | log_str = 'ERROR: source cannot be a child' 65 | print(log_str) 66 | logger.critical(log_str) 67 | quit() 68 | 69 | # Set up check for NCC: 70 | # 1. Saturation check: We are out of memory for node u 71 | # 2. Elementarity/Cycle Check: Not possible to generate at least one elementary path 72 | # 3. Negative Cost Check: Extending u to v leads to lower cost than current best to v 73 | # For efficiency, we first perform test 1, and only if that is true, we perform 3, and then 2. 74 | NCC_conds = [False]*3 75 | 76 | # test 1: Saturation Check 77 | # We have filled up the entire memory for node u 78 | NCC_conds[0] = all(c < inf for c in costs[u]) 79 | # if NCC_conds[0]: 80 | # logger.debug(f' test 0 (saturation): {NCC_conds[0]} because memory filled up') 81 | 82 | # if first test indicates possible NCC, perform tests 3 and then 2 83 | if NCC_conds[0]: 84 | # We only need to test for the first path to u, which has lowest cost. 85 | # If this path doesn't give a NCC, the later paths will not either. 86 | NCC_conds[2] = costs[u][0] + e['weight'] < costs[v][0] 87 | # logger.debug(f' test 2 (NCC): {NCC_conds[2]} because lower cost') 88 | 89 | # if tests 1 and 3 indicate possible NCC, perform test 2 (elementarity) 90 | if NCC_conds[2]: 91 | NCC_conds[1] = True 92 | for ku in range(0,K[u]): 93 | if paths[u][ku] is None: 94 | break 95 | if v not in paths[u][ku]: 96 | # logger.debug(' {} not in {}'.format(v,pt.print_path(paths[u][ku]))) 97 | # logger.debug(' -> at least one elementary path {}'.format(ku)) 98 | NCC_conds[1] = False 99 | break 100 | # logger.debug(f' test 1 (elementarity): {NCC_conds[1]} because no elementary path') 101 | 102 | # unavoidable NCC detected 103 | if all(NCC_conds): 104 | # return all the nodes involved in the NCC 105 | pos_v_in_u = paths[u][0].index(v) 106 | NCC = paths[u][0][pos_v_in_u:] 107 | 108 | logger.debug(f' unavoidable NCC found with nodes {NCC}:') 109 | return paths, costs, NCC 110 | 111 | else: 112 | # Loop over all paths of u. 113 | for ku in range(K[u]): 114 | logger.debug(f' extending from path {ku} of node {u}') 115 | 116 | path_u = paths[u][ku] 117 | if path_u is None: 118 | break 119 | cost_u = costs[u][ku] 120 | 121 | # abandon this iteration if invalid path 122 | if v in path_u: 123 | logger.debug(f' skipping extension to {v} as it creates a cycle') 124 | continue 125 | 126 | # Loop over all paths of v. 127 | for kv in range(K[v]): 128 | path_v = paths[v][kv] 129 | cost_v = costs[v][kv] 130 | 131 | path_v_new = list(path_u) # lists makes a shallow copy 132 | path_v_new.append(v) 133 | cost_v_new = cost_u + e['weight'] 134 | 135 | if path_v_new in paths[v]: 136 | continue # potential path already present in paths[v] 137 | 138 | logger.debug(f' comparing potential new cost {cost_v_new} to cost {cost_v} of path {kv}') 139 | add_new_path = False 140 | if cost_v_new < cost_v: 141 | add_new_path = True 142 | elif cost_v_new == cost_v: 143 | add_new_path = path_v_new != path_v # equal cost is OK if we have a new path 144 | 145 | if (add_new_path): 146 | # insert new path and shift all next down as well 147 | logger.debug(f' inserting path with cost {cost_v_new} in path[{v}] at position {kv}') 148 | for kv2 in range(K[v]-1, kv, -1): 149 | costs[v][kv2] = costs[v][kv2-1] 150 | paths[v][kv2] = paths[v][kv2-1] 151 | 152 | costs[v][kv] = cost_v_new 153 | paths[v][kv] = path_v_new 154 | 155 | # possibly add node v to L 156 | if v not in L: 157 | logger.debug(' add node {} to set L'.format(v)) 158 | L.add(v) 159 | L_q.append(v) 160 | 161 | # skip all following kv to next path ku 162 | break 163 | else: 164 | logger.debug(f' not inserting path with cost {cost_v_new} in path[{v}] at position {kv}') 165 | 166 | 167 | logger.debug(' resulting paths to {}:'.format(v)) 168 | for n in range(0,len(paths[v])): 169 | if paths[v][n] is None: 170 | break 171 | logger.debug(' {}({})'.format(pt.print_path(paths[v][n]),costs[v][n])) 172 | logger.debug('') 173 | logger.debug(' {} elements in queue'.format(len(L))) 174 | logger.debug('') 175 | #print(' ------------------------------------------------------') 176 | #input(" Press Enter to continue...") 177 | #print(' ------------------------------------------------------') 178 | #print('') 179 | 180 | return paths, costs, [] 181 | 182 | 183 | def DLA(G, source, min_K=1, output_pos = False, log_summary=False, plot_K_updates=False): 184 | """Dynamic labelling algorithm 185 | (based on algorithm 4 from [1])""" 186 | 187 | logger.info('source: {}'.format(source)) 188 | inf = float('inf') 189 | 190 | # initialize K label to minimal value and not done 191 | K = {} 192 | for n in G.nodes(): 193 | K[n] = min_K 194 | 195 | # we will store paths and costs accross different TLAdynK calls 196 | paths = None 197 | costs = None 198 | L = set([source]) 199 | 200 | DLA_done = False 201 | 202 | viz_lines = 0 203 | 204 | while not DLA_done: 205 | paths, costs, NCC = TLAdynK(G, source, K, L, paths, costs) 206 | 207 | # output for tests 208 | if log_summary: 209 | logger.info('') 210 | logger.info('costs summary of this level:') 211 | costs_tot = dict() 212 | for n in G.nodes(): 213 | for p in range(0,len(paths.get(n,[]))): 214 | if paths[n][p] is not None: 215 | costs_tot[tuple(paths[n][p])] = costs[n][p] 216 | 217 | # sort (from https://stackoverflow.com/a/15179418/3229162) 218 | costs_sorted = OrderedDict(sorted(costs_tot.items(), key=lambda t: t[1])) 219 | c_id = 0 220 | for c in costs_sorted: 221 | c_id += 1 222 | if costs_sorted[c] < 0 or output_pos: 223 | path_short = pt.print_path(c) 224 | logger.info(' {}: {} for {}'.format(c_id,costs_sorted[c],path_short)) 225 | logger.info('') 226 | 227 | # Increase K for all nodes that are at their limit (fully populated) 228 | saturated_nodes = [n for n in G.nodes() if len(costs[n]) > 0 and costs[n][-1] < inf] 229 | 230 | if not saturated_nodes: 231 | break 232 | 233 | logger.debug('updating K for saturated nodes:') 234 | for n in saturated_nodes: 235 | K[n] += 1 236 | logger.debug(' K[{}] -> {}:'.format(n, K[n])) 237 | 238 | # Expand the memory for this node to match the new K[n]. 239 | paths[n].append(None) 240 | costs[n].append(inf) 241 | L.add(n) 242 | 243 | if plot_K_updates: 244 | viz_lines = pt.print_dynamic_k(K, previous_lines_printed=viz_lines) 245 | logger.debug('') 246 | 247 | # return 248 | rpaths = dict() 249 | for node in paths: 250 | rpaths[node] = list() 251 | for path in paths[node]: 252 | if path is not None: 253 | rpaths[node].append(pth.Path(G, path)) 254 | return rpaths, costs 255 | -------------------------------------------------------------------------------- /pylgrim/ESPPRC.py: -------------------------------------------------------------------------------- 1 | # Solve Elementary Shortest Path Problem with resource constraints. 2 | # The algorithm is based on [1]. 3 | # Features: 4 | # * single source / single target 5 | # * with resources 6 | # * elementary paths are sought by intelligently adding node resources to nodes that have been found to be in a NCC (negative cost cycle). 7 | # 8 | # Author: 9 | # Toon Weyens 10 | # 11 | # References: 12 | # [1]: "Accelerated label setting algorithms for the elementary resource constrained shortest path problem" by Boland, Natashia (DOI: 10.1016/j.orl.2004.11.011) 13 | import networkx as nx 14 | import numpy as np 15 | import logging 16 | from sys import exit 17 | from . import tools as pt 18 | from . import path as pth 19 | 20 | # logging.basicConfig(level=logging.DEBUG) 21 | logging.basicConfig(level=logging.WARNING) 22 | logging.getLogger("matplotlib").setLevel(logging.INFO) 23 | logging.getLogger("matplotlib.font_manager").setLevel(logging.INFO) 24 | 25 | logger = logging.getLogger(__name__) 26 | 27 | # global variables 28 | _resource_nr = 0 29 | _resource_name = 'res_cost' 30 | 31 | def prune_graph(G, source, target, max_res, res_name='res_cost'): 32 | """first step of graph {G} preprocessing 33 | (based on algorithm 2.1, step 0, from [1]) 34 | Prune the graph, reducing the number of nodes and arcs, by considering least resource paths from the path {source} node to each node in the graph and from each node in the graph to the path {target} node, for each resource subject to a maximum resource in {max_res}.""" 35 | 36 | global _resource_nr, _resource_name 37 | 38 | _resource_name = res_name 39 | 40 | logger.debug('Pre-process graph') 41 | 42 | # to start with, all nodes are assumed to be reachable 43 | n_res = G.graph['n_res'] 44 | reachable_nodes = set(G.nodes()) 45 | 46 | # iterate over all resources and delete nodes that are not reachable 47 | logger.debug('Delete unreachable nodes') 48 | for res in range(0,n_res): 49 | logger.debug('Treating resource {}'.format(res)) 50 | _resource_nr = res 51 | 52 | logger.debug('Calculate feasible paths from source for resource {}'.format(res)) 53 | lengths_source = dict(nx.single_source_dijkstra_path_length(G, source, cutoff=max_res[res], weight=_res_cost_i)) 54 | if target not in lengths_source: 55 | logger.error('target not reachable for resource {}'.format(res)) 56 | exit() 57 | 58 | logger.debug('Calculate feasible paths to target for resource {}'.format(res)) 59 | lengths_target = dict(nx.single_source_dijkstra_path_length(G.reverse(copy=True), target, cutoff=max_res[res], weight=_res_cost_i)) 60 | if source not in lengths_target: 61 | logger.error('source not reachable for resource {}'.format(res)) 62 | exit() 63 | 64 | nodes_to_remove = set() 65 | for node in reachable_nodes: 66 | if node not in lengths_source or node not in lengths_target: 67 | nodes_to_remove.add(node) 68 | elif lengths_source[node] + lengths_target[node] > max_res[res]: 69 | nodes_to_remove.add(node) 70 | 71 | logger.debug('Remove {} nodes due to violation of resource'.format(len(nodes_to_remove),)) 72 | for node in nodes_to_remove: 73 | reachable_nodes.remove(node) 74 | 75 | logger.debug('{} reachable nodes:'.format(len(reachable_nodes))) 76 | logger.debug(' {}'.format(reachable_nodes)) 77 | 78 | # set up reduced graph 79 | logger.debug('Set up reduced graph') 80 | H = nx.DiGraph(n_res=n_res) 81 | for node in reachable_nodes: 82 | for node2 in reachable_nodes: 83 | if G.has_edge(node, node2) and not H.has_edge(node,node2): 84 | H.add_edge(node, node2) 85 | for attr in G[node][node2]: 86 | H[node][node2][attr] = G[node][node2][attr] 87 | #nx.draw_circular(H,with_labels=True) 88 | #plt.show() 89 | 90 | # return pruned graph 91 | return H 92 | 93 | def setup_least_resource_paths_ESPPRC(G, res_name='res_cost'): 94 | """second step of graph {G} preprocessing 95 | (based on algorithm 2.1, step 0, from [1]) 96 | Solve the all-pairs shortest path problem on the graph, with lengths set to {_res_cost_i} , for each resource r.""" 97 | 98 | global _resource_nr, _resource_name 99 | 100 | _resource_name = res_name 101 | 102 | # iterate over all resources and calculate least-resource paths for all pairs 103 | n_res = G.graph['n_res'] 104 | logger.debug('Calculate least-resource pairs') 105 | res_min = list() 106 | for res in range(0,n_res): 107 | logger.debug('Treating resource {}'.format(res)) 108 | _resource_nr = res 109 | res_min.append(dict(nx.all_pairs_dijkstra_path_length(G, weight=_res_cost_i))) 110 | 111 | # return preprocessed network and least-resource paths 112 | return res_min 113 | 114 | def preprocess(G, source, target, max_res, res_name='res_cost'): 115 | """preprocess graph {G} 116 | (based on algorithm 2.1, step 0, from [1])""" 117 | 118 | # 1. prune graph 119 | H = prune_graph(G, source, target, max_res, res_name=res_name) 120 | 121 | # 2. set up least resource paths 122 | res_min = setup_least_resource_paths_ESPPRC(H, res_name=res_name) 123 | 124 | # return preprocessed network and least-resource paths 125 | return H, res_min 126 | 127 | def GLSA(G, S, source, target, max_res, res_min, res_name='res_cost'): 128 | """General Label Setting Algorithm 129 | (based on algorithm 2.1, step 1 and 2, from [1])""" 130 | 131 | # test 132 | if target == source: 133 | logger.error('target cannot be source') 134 | exit() 135 | 136 | # 1. Initialization 137 | inf = float('inf') 138 | n_res = G.graph['n_res'] 139 | # paths for each node 140 | paths = {source: list()} 141 | paths[source].append([source]) 142 | # labels for each path (cost, resources): 143 | labels = {source: list()} 144 | labels[source].append((0,np.zeros(n_res+len(S)))) 145 | # labels to treat: start with 0th label of path ending at source 146 | L = set([(source,0)]) 147 | 148 | # 2. select lexicographically minimal label 149 | logger.debug('Loop over labels to be extended') 150 | while L: 151 | # select lexicographically minimal label: 152 | # l1 < l2 if there is a r' ∈ {1...R'}, w1 = w2 for all r = 1...r' but l1^r' < l2^r' 153 | # i.e. 1 2 0 < 1 3 0 154 | # 0 1 0 < 1 5 8 155 | # etc. 156 | logger.debug('Select lexicographically minimal label:') 157 | LML_for_prev_res = L 158 | for res in range(0,n_res+len(S)): 159 | LML_for_this_res = [] 160 | res_LML = inf 161 | for label in LML_for_prev_res: 162 | res_loc = labels[label[0]][label[1]][1][res] 163 | if res_loc <= res_LML: 164 | LML_for_this_res.append(label) 165 | if len(LML_for_this_res) == 0: 166 | logger.error('Could not find labels to select') 167 | exit() 168 | elif len(LML_for_this_res) > 1: 169 | # go to next level with restricted set 170 | logger.debug('Go to next level with restricted set {}'.format(LML_for_this_res)) 171 | LML_for_prev_res = LML_for_this_res 172 | else: 173 | # done 174 | break 175 | u_label = LML_for_this_res[0] 176 | u = u_label[0] 177 | l = u_label[1] # noqa: E741 178 | logger.debug('found lexically minimal label {}'.format(u_label)) 179 | 180 | L.remove(u_label) 181 | 182 | logger.debug('{}th label of node {} chosen:'.format(l,u)) 183 | logger.debug('{} (C {} | R {})'.format(pt.print_path(paths[u][l]),labels[u][l][0],labels[u][l][1])) 184 | 185 | # extend label for each child 186 | for v, e in G.succ[u].items(): 187 | logger.debug('treating edge {} -> {} (C {} | R {})'.format(u,v,e['weight'],e[res_name])) 188 | if len(paths.get(v,[])) > 0: 189 | logger.debug(' with current paths:') 190 | for n in range(0,len(paths.get(v,[]))): 191 | logger.debug('{} (C {} | R {})'.format(pt.print_path(paths[v][n]),labels[v][n][0],labels[v][n][1])) 192 | 193 | # error if the source is a child. The in-edges of the source need to be separated from the out-edges. 194 | if v == source: 195 | logger.critical('ERROR: source cannot be a child') 196 | quit() 197 | 198 | # determine whether to create a new label on the child node 199 | e_loc = np.zeros(n_res+len(S)) 200 | e_loc[0:n_res] = G[u][v][res_name] 201 | if v in S: 202 | e_loc[n_res+S.index(v)] = 1 203 | v_label = (labels[u][l][0] + G[u][v]['weight'], labels[u][l][1] + e_loc) 204 | add_label = True 205 | 206 | # check edge resources 207 | for res in range(0,n_res): 208 | if v_label[1][res] + res_min[res][v].get(target,0.0) > max_res[res]: 209 | add_label = False 210 | logger.debug('at least {} more of resource {} is needed to reach target'.format(res_min[res][v].get(target,0.0),res)) 211 | break 212 | 213 | # check node resources 214 | for res in range(0,len(S)): 215 | if v_label[1][n_res+res] > 1: 216 | add_label = False 217 | logger.debug('node {} was used twice'.format(S[res])) 218 | break 219 | 220 | # add 221 | if add_label: 222 | # check subset of all labels that belong to the same node for domination 223 | label_dominated = False 224 | if len(labels.get(v,[])) > 0: 225 | for label in labels.get(v,[]): 226 | label_dominated = _is_dominated(v_label, label) 227 | if label_dominated: 228 | break 229 | 230 | if label_dominated: 231 | logger.debug('but label was dominated') 232 | else: 233 | # setup label and path 234 | if labels.get(v, None) is None: 235 | paths[v] = list() 236 | labels[v] = list() 237 | v_path = list(paths[u][l]) 238 | v_path.append(v) 239 | 240 | logger.debug('add undominated label {} (C {} | R {})'.format(pt.print_path(v_path),v_label[0],v_label[1])) 241 | 242 | # strong dominance: set node resource to one for nodes in S that cannot 243 | # be feasibly visited with edge resources 244 | for n in S: 245 | for res in range(0,n_res): 246 | if v_label[1][res] + res_min[res][v].get(n,0.0) + res_min[res][n].get(target,0.0) > max_res[res]: 247 | if v_label[1][n_res+S.index(n)] == 0: 248 | logger.debug('set strong dominance for node resource {}'.format(S.index(n))) 249 | v_label[1][n_res+S.index(n)] = 1 250 | 251 | # remove dominated labels 252 | # Note: It is possible that two labels are identical but have different paths. 253 | # The iteration therefore has to be using i_label, and not, for example, using 254 | # for label in labels.get(v,[]): 255 | i_label = 0 256 | n_labels = len(labels.get(v,[])) 257 | while i_label < n_labels: 258 | label = labels[v][i_label] 259 | if _is_dominated(label, v_label): 260 | logger.debug('remove dominated label {} (C {} | R {})'.format(pt.print_path(paths[v][i_label]),label[0],label[1])) 261 | labels[v].pop(i_label) 262 | paths[v].pop(i_label) 263 | L_rename = set() 264 | if (v, i_label) in L: 265 | L.remove((v, i_label)) 266 | for i in range(i_label+1, len(labels[v])+1): 267 | if (v, i) in L: 268 | L_rename.add((v,i-1)) 269 | L.remove((v,i)) 270 | L.update(L_rename) 271 | i_label -= 1 272 | n_labels -= 1 273 | i_label += 1 274 | 275 | # add label and path 276 | paths[v].append(v_path) 277 | labels[v].append(v_label) 278 | 279 | # add to list L 280 | L.add((v, len(labels[v])-1)) 281 | else: 282 | logger.debug('therefore do not add unfeasible label {}'.format(v_label[1])) 283 | 284 | 285 | # return cheapest paths with label 286 | logger.debug('Select cheapest path to {}'.format(target)) 287 | 288 | least_cost = inf 289 | for p in range(0,len(labels[target])): 290 | if labels[target][p][0] < least_cost: 291 | best_path = paths[target][p] 292 | best_label = labels[target][p] 293 | least_cost = best_label[0] 294 | return best_path, best_label 295 | 296 | def GSSA(G, source, target, max_res, res_min, res_name='res_cost'): 297 | """General State Space Augmenting Algorithm 298 | (based on algorithm 2.2, from [1]) 299 | Note: The graph must have been preprocessed so that it is reduced and has the minimal resource information in {res_min}.""" 300 | 301 | logger.debug('Searching for shortest path {} -> {}'.format(source, target)) 302 | 303 | # initialize node resources and not done 304 | S = list([]) 305 | DLA_done = False 306 | 307 | while not DLA_done: 308 | # Run dynamic labelling algorithm 309 | path, label = GLSA(G, S, source, target, max_res, res_min, res_name=res_name) 310 | logger.debug('found path {} (C {} | R {})'.format(pt.print_path(path, max_path_len_for_print=len(path)), label[0], label[1])) 311 | path_elems = pt.count_elems(path) 312 | path_max_mult = max(path_elems.values()) 313 | if path_max_mult == 1: 314 | logger.debug('it is elementary') 315 | DLA_done = True 316 | else: 317 | logger.debug('but is it not elementary') 318 | node_max_mult = max(path_elems, key=path_elems.get) 319 | S.append(node_max_mult) 320 | logger.debug('Incrementing node {}, which had multiplicity {}:'.format(node_max_mult, path_max_mult)) 321 | logger.debug('S = {}'.format(S)) 322 | #input('PAUSED') 323 | 324 | return pth.Path(G,path), label 325 | 326 | def _is_dominated(a, b): 327 | """returns whether a label {a} is dominated by another label {b}""" 328 | 329 | logger.debug('check for domination of {} by {}'.format(a,b)) 330 | if a[0] == b[0] and all(a[1] == b[1]): 331 | label_dominated = False 332 | else: 333 | label_dominated = True 334 | if a[0] < b[0]: 335 | label_dominated = False 336 | if any(a[1] < b[1]): 337 | label_dominated = False 338 | return label_dominated 339 | 340 | def _res_cost_i(u,v,e): 341 | """returns weight of certain resource with index {_resource_nr} of edge {e} from node {u} to {v}, given by variable {_resource_name}. 342 | It is used by all_pairs_dijkstra_path_length: 343 | 'The weight of an edge is the value returned by the function. 344 | The function must accept exactly three positional arguments: the two endpoints of an edge and the dictionary of edge attributes for that edge. 345 | The function must return a number.'""" 346 | 347 | global _resource_nr, _resource_name 348 | 349 | return e[_resource_name][_resource_nr] 350 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------