Compare commits

...

3 Commits

21 changed files with 557 additions and 4 deletions

View File

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

View File

@ -150,6 +150,51 @@ components:
type: string type: string
default: [] 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 # Algorithm: Euklidean algorithm
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CommandEuklid: CommandEuklid:
@ -190,6 +235,44 @@ components:
default: 2 default: 2
minimum: 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 # Enum Algorithm Names
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EnumAlgorithmNames: EnumAlgorithmNames:
@ -201,6 +284,8 @@ components:
- TSP - TSP
- HIRSCHBERG - HIRSCHBERG
- RUCKSACK - RUCKSACK
- RANDOM-WALK
- GENETIC
- EUKLID - EUKLID
- POLLARD-RHO - POLLARD-RHO
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -223,3 +308,29 @@ components:
enum: enum:
- GREEDY - GREEDY
- BRANCH-AND-BOUND - 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

View File

@ -54,6 +54,8 @@ components:
- tarjan - tarjan
- hirschberg - hirschberg
- rucksack - rucksack
- random-walk
- genetic
- euklid - euklid
- pollard-rho - pollard-rho
properties: properties:
@ -129,6 +131,22 @@ components:
items: items:
$ref: '#/components/schemas/EnumRucksackShow' $ref: '#/components/schemas/EnumRucksackShow'
default: [] 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: euklid:
type: object type: object
required: required:

View File

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

View File

@ -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;

View File

@ -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 '';

View File

@ -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',
];

View File

@ -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;

View File

@ -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 '';

View File

@ -40,6 +40,10 @@ def run_command(command: Command) -> Result[CallResult, CallError]:
return endpoint_hirschberg(command); return endpoint_hirschberg(command);
elif isinstance(command, CommandRucksack): elif isinstance(command, CommandRucksack):
return endpoint_rucksack(command); 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): elif isinstance(command, CommandEuklid):
return endpoint_euklid(command); return endpoint_euklid(command);
elif isinstance(command, CommandPollard): elif isinstance(command, CommandPollard):

View File

@ -9,6 +9,8 @@ from src.endpoints.ep_algorithm_hirschberg import *;
from src.endpoints.ep_algorithm_tarjan import *; from src.endpoints.ep_algorithm_tarjan import *;
from src.endpoints.ep_algorithm_tsp import *; from src.endpoints.ep_algorithm_tsp import *;
from src.endpoints.ep_algorithm_rucksack 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_euklid import *;
from src.endpoints.ep_algorithm_pollard_rho import *; from src.endpoints.ep_algorithm_pollard_rho import *;
@ -21,6 +23,8 @@ __all__ = [
'endpoint_tarjan', 'endpoint_tarjan',
'endpoint_tsp', 'endpoint_tsp',
'endpoint_rucksack', 'endpoint_rucksack',
'endpoint_random_walk',
'endpoint_genetic',
'endpoint_euklid', 'endpoint_euklid',
'endpoint_pollard_rho', 'endpoint_pollard_rho',
]; ];

View File

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

View File

@ -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));

View File

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

View File

@ -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));

View File

@ -50,5 +50,5 @@ def endpoint_rucksack(command: CommandRucksack) -> Result[CallResult, CallError]
verbose = config.OPTIONS.rucksack.verbose, verbose = config.OPTIONS.rucksack.verbose,
); );
case _ as alg: 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)); return Ok(CallResult(action_taken=True, message=result));

View File

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

View File

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

View File

@ -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.');

View File

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