Compare commits

...

3 Commits

  1. 4
      code/python/assets/config.yaml
  2. 111
      code/python/models/commands-schema.yaml
  3. 18
      code/python/models/config-schema.yaml
  4. 16
      code/python/src/algorithms/genetic/__init__.py
  5. 38
      code/python/src/algorithms/genetic/algorithms.py
  6. 30
      code/python/src/algorithms/genetic/display.py
  7. 18
      code/python/src/algorithms/random_walk/__init__.py
  8. 75
      code/python/src/algorithms/random_walk/algorithms.py
  9. 30
      code/python/src/algorithms/random_walk/display.py
  10. 4
      code/python/src/api.py
  11. 4
      code/python/src/endpoints/__init__.py
  12. 2
      code/python/src/endpoints/ep_algorithm_euklid.py
  13. 34
      code/python/src/endpoints/ep_algorithm_genetic.py
  14. 2
      code/python/src/endpoints/ep_algorithm_pollard_rho.py
  15. 59
      code/python/src/endpoints/ep_algorithm_random_walk.py
  16. 2
      code/python/src/endpoints/ep_algorithm_rucksack.py
  17. 4
      code/python/src/models/config/commands.py
  18. 0
      code/python/src/models/genetic/__init__.py
  19. 16
      code/python/src/models/random_walk/__init__.py
  20. 90
      code/python/src/models/random_walk/landscape.py
  21. 4
      code/python/src/thirdparty/misc.py

4
code/python/assets/config.yaml

@ -36,6 +36,10 @@ options:
# show:
# - ALL-WEIGHTS
# - ALL-SUMS
genetic:
verbose: *ref_verbose
random-walk:
verbose: *ref_verbose
euklid:
verbose: *ref_verbose
pollard-rho:

111
code/python/models/commands-schema.yaml

@ -150,6 +150,51 @@ components:
type: string
default: []
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Algorithm: Random Walk
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CommandRandomWalk:
description: |-
Instructions for execution of random walks to determine local extrema in a fitness landscape
type: object
required:
- name
- algorithm
- landscape
- optimise
properties:
name:
$ref: '#/components/schemas/EnumAlgorithmNames'
algorithm:
$ref: '#/components/schemas/EnumWalkMode'
landscape:
$ref: '#/components/schemas/DataTypeLandscapeGeometry'
optimise:
$ref: '#/components/schemas/EnumOptimiseMode'
annealing:
type: boolean
default: false
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Algorithm: Genetic Algorithm
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CommandGenetic:
description: |-
Instructions for execution of the Genetic algorithm
type: object
required:
- name
- population
properties:
name:
$ref: '#/components/schemas/EnumAlgorithmNames'
population:
type: array
items:
type: array
items:
type: string
minItems: 2
# maxItems: 2 # FIXME: does not work!
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Algorithm: Euklidean algorithm
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CommandEuklid:
@ -190,6 +235,44 @@ components:
default: 2
minimum: 2
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Data-type Landscape Geometry, Landscape Values
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DataTypeLandscapeGeometry:
description: |-
Structure for the geometry of a fitness landscape
type: object
required:
- neighbourhoods
- values
properties:
neighbourhoods:
$ref: '#/components/schemas/DataTypeLandscapeNeighbourhoods'
values:
$ref: '#/components/schemas/DataTypeLandscapeValues'
DataTypeLandscapeNeighbourhoods:
description: |-
Options for the definition of discrete neighbourhoods of a fitness landscape
type: object
required:
- metric
properties:
radius:
type: number
minimum: 1
default: 1
metric:
$ref: '#/components/schemas/EnumLandscapeMetric'
DataTypeLandscapeValues:
description: |-
A (potentially multi-dimensional) array of values for the fitness landscape.
oneOf:
- type: array
items:
type: number
- type: array
items:
$ref: '#/components/schemas/DataTypeLandscapeValues'
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Enum Algorithm Names
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EnumAlgorithmNames:
@ -201,6 +284,8 @@ components:
- TSP
- HIRSCHBERG
- RUCKSACK
- RANDOM-WALK
- GENETIC
- EUKLID
- POLLARD-RHO
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -223,3 +308,29 @@ components:
enum:
- GREEDY
- BRANCH-AND-BOUND
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Enum Type of walk mode for fitness walk algorithm
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EnumWalkMode:
description: |-
Enumeration of walk mode for fitness walk algorithm
- `ADAPTIVE` - points uniformly randomly chosen from nbhd.
- `GRADIENT` - points uniformly randomly chosen amongst points in nbhd with steepest gradient.
- `METROPOLIS` - points uniformly randomly chosen from nbhd. or by entropy.
type: string
enum:
- ADAPTIVE
- GRADIENT
- METROPOLIS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Enum for metric for neighbourhoods in fitness landscape
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EnumLandscapeMetric:
description: |-
Enumeration of mode for Rucksack problem
- `MAXIMUM` - `Q` is a neighbour of `P` <==> `max_i d(P_i, Q_i) <= r`
- `MANHATTAN` - `Q` is a neighbour of `P` <==> `sum_i d(P_i, Q_i) <= r`
type: string
enum:
- MAXIMUM
- MANHATTAN

18
code/python/models/config-schema.yaml

@ -54,6 +54,8 @@ components:
- tarjan
- hirschberg
- rucksack
- random-walk
- genetic
- euklid
- pollard-rho
properties:
@ -129,6 +131,22 @@ components:
items:
$ref: '#/components/schemas/EnumRucksackShow'
default: []
random-walk:
type: object
required:
- verbose
properties:
verbose:
type: boolean
default: false
genetic:
type: object
required:
- verbose
properties:
verbose:
type: boolean
default: false
euklid:
type: object
required:

16
code/python/src/algorithms/genetic/__init__.py

@ -0,0 +1,16 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from src.algorithms.genetic.algorithms import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'genetic_algorithm',
];

38
code/python/src/algorithms/genetic/algorithms.py

@ -0,0 +1,38 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from src.thirdparty.types import *;
from src.thirdparty.maths import *;
from models.generated.config import *;
from src.core.log import *;
from src.core.utils import *;
from src.models.genetic import *;
from src.algorithms.genetic.display import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'genetic_algorithm',
];
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# METHOD genetic algorithm
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def genetic_algorithm(
individual1: List[str],
individual2: List[str],
verbose: bool,
):
'''
Führt den genetischen Algorithmus auf 2 Individuen aus.
'''
log_warn('Noch nicht implementiert!');
return;

30
code/python/src/algorithms/genetic/display.py

@ -0,0 +1,30 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from src.thirdparty.code import *;
from src.thirdparty.maths import *;
from src.thirdparty.types import *;
from src.core.log import *;
from src.models.genetic import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'display_table',
];
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# METHOD display table
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def display_table(
) -> str:
log_warn('Noch nicht implementiert!');
return '';

18
code/python/src/algorithms/random_walk/__init__.py

@ -0,0 +1,18 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from src.algorithms.random_walk.algorithms import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'adaptive_walk_algorithm',
'gradient_walk_algorithm',
'metropolis_walk_algorithm',
];

75
code/python/src/algorithms/random_walk/algorithms.py

@ -0,0 +1,75 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from src.thirdparty.types import *;
from src.thirdparty.maths import *;
from models.generated.config import *;
from models.generated.commands import *;
from src.core.log import *;
from src.core.utils import *;
from src.models.random_walk import *;
from src.algorithms.random_walk.display import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'adaptive_walk_algorithm',
'gradient_walk_algorithm',
'metropolis_walk_algorithm',
];
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# METHOD adaptive walk
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def adaptive_walk_algorithm(
landscape: Landscape,
r: float,
optimise: EnumOptimiseMode,
verbose: bool,
):
'''
Führt den Adapative-Walk Algorithmus aus, um ein lokales Minimum zu bestimmen.
'''
log_warn('Noch nicht implementiert!');
return;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# METHOD gradient walk
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def gradient_walk_algorithm(
landscape: Landscape,
r: float,
optimise: EnumOptimiseMode,
verbose: bool,
):
'''
Führt den Gradient-Descent (bzw. Ascent) Algorithmus aus, um ein lokales Minimum zu bestimmen.
'''
log_warn('Noch nicht implementiert!');
return;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# METHOD metropolis walk
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def metropolis_walk_algorithm(
landscape: Landscape,
r: float,
annealing: bool,
optimise: EnumOptimiseMode,
verbose: bool,
):
'''
Führt den Metropolis-Walk Algorithmus aus, um ein lokales Minimum zu bestimmen.
'''
log_warn('Noch nicht implementiert!');
return;

30
code/python/src/algorithms/random_walk/display.py

@ -0,0 +1,30 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from src.thirdparty.code import *;
from src.thirdparty.maths import *;
from src.thirdparty.types import *;
from src.core.log import *;
from src.models.random_walk import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'display_table',
];
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# METHOD display table
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def display_table(
) -> str:
log_warn('Noch nicht implementiert!');
return '';

4
code/python/src/api.py

@ -40,6 +40,10 @@ def run_command(command: Command) -> Result[CallResult, CallError]:
return endpoint_hirschberg(command);
elif isinstance(command, CommandRucksack):
return endpoint_rucksack(command);
elif isinstance(command, CommandRandomWalk):
return endpoint_random_walk(command);
elif isinstance(command, CommandGenetic):
return endpoint_genetic(command);
elif isinstance(command, CommandEuklid):
return endpoint_euklid(command);
elif isinstance(command, CommandPollard):

4
code/python/src/endpoints/__init__.py

@ -9,6 +9,8 @@ from src.endpoints.ep_algorithm_hirschberg import *;
from src.endpoints.ep_algorithm_tarjan import *;
from src.endpoints.ep_algorithm_tsp import *;
from src.endpoints.ep_algorithm_rucksack import *;
from src.endpoints.ep_algorithm_genetic import *;
from src.endpoints.ep_algorithm_random_walk import *;
from src.endpoints.ep_algorithm_euklid import *;
from src.endpoints.ep_algorithm_pollard_rho import *;
@ -21,6 +23,8 @@ __all__ = [
'endpoint_tarjan',
'endpoint_tsp',
'endpoint_rucksack',
'endpoint_random_walk',
'endpoint_genetic',
'endpoint_euklid',
'endpoint_pollard_rho',
];

2
code/python/src/endpoints/ep_algorithm_euklid.py

@ -29,6 +29,6 @@ def endpoint_euklid(command: CommandEuklid) -> Result[CallResult, CallError]:
result = euklidean_algorithm(
a = command.numbers[0].__root__,
b = command.numbers[1].__root__,
verbose = config.OPTIONS.tsp.verbose,
verbose = config.OPTIONS.euklid.verbose,
);
return Ok(CallResult(action_taken=True, message=result));

34
code/python/src/endpoints/ep_algorithm_genetic.py

@ -0,0 +1,34 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from src.thirdparty.code import *;
from models.generated.commands import *;
from src.core.calls import *;
from src.setup import config;
from src.algorithms.genetic import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'endpoint_genetic',
];
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ENDPOINT
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@run_safely()
def endpoint_genetic(command: CommandGenetic) -> Result[CallResult, CallError]:
result = genetic_algorithm(
individual1 = command.population[0],
individual2 = command.population[1],
verbose = config.OPTIONS.genetic.verbose,
);
return Ok(CallResult(action_taken=True, message=result));

2
code/python/src/endpoints/ep_algorithm_pollard_rho.py

@ -29,6 +29,6 @@ def endpoint_pollard_rho(command: CommandPollard) -> Result[CallResult, CallErro
result = pollard_rho_algorithm(
n = command.number,
x_init = command.x_init,
verbose = config.OPTIONS.tsp.verbose,
verbose = config.OPTIONS.pollard_rho.verbose,
);
return Ok(CallResult(action_taken=True, message=result));

59
code/python/src/endpoints/ep_algorithm_random_walk.py

@ -0,0 +1,59 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from src.thirdparty.code import *;
from models.generated.commands import *;
from src.core.calls import *;
from src.setup import config;
from src.models.random_walk import *;
from src.algorithms.random_walk import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'endpoint_random_walk',
];
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ENDPOINT
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@run_safely()
def endpoint_random_walk(command: CommandRandomWalk) -> Result[CallResult, CallError]:
landscape = Landscape(
values = command.landscape.values,
metric = command.landscape.neighbourhoods.metric,
);
match command.algorithm:
case EnumWalkMode.adaptive:
result = adaptive_walk_algorithm(
landscape = landscape,
r = command.landscape.neighbourhoods.radius,
optimise = command.optimise,
verbose = config.OPTIONS.random_walk.verbose
);
case EnumWalkMode.gradient:
result = gradient_walk_algorithm(
landscape = landscape,
r = command.landscape.neighbourhoods.radius,
optimise = command.optimise,
verbose = config.OPTIONS.random_walk.verbose
);
case EnumWalkMode.metropolis:
result = metropolis_walk_algorithm(
landscape = landscape,
r = command.landscape.neighbourhoods.radius,
annealing = command.annealing,
optimise = command.optimise,
verbose = config.OPTIONS.random_walk.verbose
);
case _ as alg:
raise Exception(f'No algorithm implemented for {alg.value}.');
return Ok(CallResult(action_taken=True, message=result));

2
code/python/src/endpoints/ep_algorithm_rucksack.py

@ -50,5 +50,5 @@ def endpoint_rucksack(command: CommandRucksack) -> Result[CallResult, CallError]
verbose = config.OPTIONS.rucksack.verbose,
);
case _ as alg:
raise Exception(f'No algorithm implemented for {alg.value}.')
raise Exception(f'No algorithm implemented for {alg.value}.');
return Ok(CallResult(action_taken=True, message=result));

4
code/python/src/models/config/commands.py

@ -44,6 +44,10 @@ def interpret_command(command: Command) -> Command:
return CommandHirschberg(**command.dict());
case EnumAlgorithmNames.rucksack:
return CommandRucksack(**command.dict());
case EnumAlgorithmNames.random_walk:
return CommandRandomWalk(**command.dict());
case EnumAlgorithmNames.genetic:
return CommandGenetic(**command.dict());
case EnumAlgorithmNames.euklid:
return CommandEuklid(**command.dict());
case EnumAlgorithmNames.pollard_rho:

0
code/python/src/models/genetic/__init__.py

16
code/python/src/models/random_walk/__init__.py

@ -0,0 +1,16 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from src.models.random_walk.landscape import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'Landscape',
];

90
code/python/src/models/random_walk/landscape.py

@ -0,0 +1,90 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from __future__ import annotations;
from src.thirdparty.maths import *;
from src.thirdparty.misc import *;
from src.thirdparty.types import *;
from models.generated.commands import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'Landscape',
];
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# METHOD fitness function -> Array
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class Landscape():
_fct: np.ndarray;
_metric: EnumLandscapeMetric;
_radius: float;
def __init__(
self,
values: DataTypeLandscapeValues,
metric: EnumLandscapeMetric = EnumLandscapeMetric.maximum,
):
self._fct = convert_to_nparray(values);
self._metric = metric;
return;
@property
def shape(self) -> tuple:
return self._fct.shape;
@property
def dim(self) -> int:
return len(self._fct.shape);
def fitness(self, *x: int) -> float:
return self._fct[x];
def neighbourhood(self, *x: int, r: float, strict: bool = False) -> List[tuple]:
sides = [
[ xx - j for j in range(1,r+1) if xx - j in range(s) ]
+ ([ xx ] if xx in range(s) else [])
+ [ xx + j for j in range(1,r+1) if xx + j in range(s) ]
for xx, s in zip(x, self.shape)
];
match self._metric:
case EnumLandscapeMetric.maximum:
umg = list(itertools_product(*sides));
case EnumLandscapeMetric.manhattan:
umg = [
(*x[:i], xx, *x[(i+1):])
for i, side in enumerate(sides)
for xx in side
];
case _:
umg = [ x ];
if strict:
umg = [ p for p in umg if p != x ];
return umg;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# AUXILIARY METHODS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def convert_to_array(values: DataTypeLandscapeValues) -> list:
return [
x if isinstance(x, float) else convert_to_array(x)
for x in values.__root__
];
def convert_to_nparray(values: DataTypeLandscapeValues) -> np.ndarray:
try:
list_of_lists = convert_to_array(values);
return np.asarray(list_of_lists, dtype=float);
except:
raise ValueError('Could not convert to a d-dimensional array! Ensure that the dimensions are consistent.');

4
code/python/src/thirdparty/misc.py vendored

@ -7,6 +7,7 @@
from datetime import datetime;
from datetime import timedelta;
from itertools import product as itertools_product;
import lorem;
import re;
from textwrap import dedent;
@ -16,9 +17,10 @@ from textwrap import dedent;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'lorem',
'datetime',
'timedelta',
'itertools_product',
'lorem',
're',
'dedent',
];

Loading…
Cancel
Save