Compare commits

..

No commits in common. "059f9d8742e6313da9d79be4e08d7ded3c16b209" and "3791220cee6ffe3eca2433e1fe8ddfca9aef5f42" have entirely different histories.

17 changed files with 65 additions and 261 deletions

View File

@ -75,40 +75,20 @@
# Beispiele für Seminarwoche 11 (Blatt 10)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- name: RUCKSACK
- &rucksack_1
name: RUCKSACK
algorithm: GREEDY
allow-fractional: true
# allow-fractional: false
allow-fractional: false
max-cost: 10
items: [a, b, c, d, e]
costs:
[3, 4, 5, 2, 1]
values:
[8, 7, 8, 3, 2]
- name: RUCKSACK
algorithm: BRANCH-AND-BOUND
- <<: *rucksack_1
allow-fractional: true
# allow-fractional: false
max-cost: 10
items: [a, b, c, d, e]
costs:
[3, 4, 5, 2, 1]
values:
[8, 7, 8, 3, 2]
- name: RUCKSACK
- <<: *rucksack_1
algorithm: BRANCH-AND-BOUND
max-cost: 460
items: [
'Lakritze',
'Esspapier',
'Gummibärchen',
'Schokolade',
'Apfelringe',
]
costs:
[220, 80, 140, 90, 100]
values:
[100, 10, 70, 80, 100]
- name: RUCKSACK
algorithm: BRANCH-AND-BOUND
max-cost: 90

View File

@ -22,17 +22,11 @@ options:
diagonal: 0
horizontal: 1
vertical: 2
# verbose: []
verbose:
- COSTS
- MOVES
# show: []
show:
# - ATOMS
- TREE
rucksack:
verbose: true
# show: []
show:
- ALL-WEIGHTS
- ALL-SUMS

View File

@ -1 +1 @@
0.2.0
0.1.0

View File

@ -8,7 +8,7 @@ Name | Type | Description | Notes
**tarjan** | [**AppOptions_tarjan**](AppOptions_tarjan.md) | | [default to null]
**tsp** | [**AppOptions_tarjan**](AppOptions_tarjan.md) | | [default to null]
**hirschberg** | [**AppOptions_hirschberg**](AppOptions_hirschberg.md) | | [default to null]
**rucksack** | [**AppOptions_rucksack**](AppOptions_rucksack.md) | | [default to null]
**rucksack** | [**AppOptions_tarjan**](AppOptions_tarjan.md) | | [optional] [default to null]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,10 +0,0 @@
# AppOptionsRucksack
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**verbose** | [**Boolean**](boolean.md) | | [optional] [default to false]
**show** | [**List**](EnumRucksackShow.md) | | [optional] [default to []]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -1,8 +0,0 @@
# EnumRucksackShow
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

View File

@ -15,13 +15,11 @@ Class | Method | HTTP request | Description
- [AppOptions](.//Models/AppOptions.md)
- [AppOptionsHirschberg](.//Models/AppOptionsHirschberg.md)
- [AppOptionsHirschbergMovePriorities](.//Models/AppOptionsHirschbergMovePriorities.md)
- [AppOptionsRucksack](.//Models/AppOptionsRucksack.md)
- [AppOptionsTarjan](.//Models/AppOptionsTarjan.md)
- [Config](.//Models/Config.md)
- [EnumHirschbergShow](.//Models/EnumHirschbergShow.md)
- [EnumHirschbergVerbosity](.//Models/EnumHirschbergVerbosity.md)
- [EnumLogLevel](.//Models/EnumLogLevel.md)
- [EnumRucksackShow](.//Models/EnumRucksackShow.md)
- [Info](.//Models/Info.md)

View File

@ -1,6 +1,6 @@
openapi: 3.0.3
info:
version: 0.2.0
version: 0.1.0
title: Schemata for command instructions
servers:
- url: "."

View File

@ -1,6 +1,6 @@
openapi: 3.0.3
info:
version: 0.2.0
version: 0.1.0
title: Schemata for config models
servers:
- url: "."
@ -53,7 +53,7 @@ components:
- tsp
- tarjan
- hirschberg
- rucksack
- rucksack-branch-and-bound
properties:
log-level:
$ref: '#/components/schemas/EnumLogLevel'
@ -117,16 +117,12 @@ components:
default: []
rucksack:
type: object
required: []
required:
- verbose
properties:
verbose:
type: boolean
default: false
show:
type: array
items:
$ref: '#/components/schemas/EnumRucksackShow'
default: []
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Enum LogLevel
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -152,18 +148,8 @@ components:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EnumHirschbergShow:
description: |-
Enumeration of display options for Hirschberg
Enumeration of verbosity options for Hirschberg
type: string
enum:
- TREE
- ATOMS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Enum Rucksack - display options
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
EnumRucksackShow:
description: |-
Enumeration of display options for the Rucksack problem
type: string
enum:
- ALL-WEIGHTS
- ALL-SUMS

View File

@ -1,6 +1,6 @@
[project]
name = "uni-leipzig-ads-2-2022"
version = "0.2.0"
version = "1.0.0"
description = "Zusatzcode, um Algorithmen und Datenstrukturen im Kurs ADS2 zu demonstrieren."
authors = [ "Raj Dahya" ]
maintainers = [ "raj_mathe" ]

View File

@ -57,25 +57,25 @@ def rucksack_greedy_algorithm(
# führe greedy aus:
n = len(costs);
cost_total = 0;
choice = [ Fraction(0) for _ in range(n) ];
vector = [ Fraction(0) for _ in range(n) ];
for i in order:
# füge Item i hinzu, solange das Gesamtgewicht noch <= Schranke
if cost_total + costs[i] <= max_cost:
cost_total += costs[i];
choice[i] = Fraction(1);
vector[i] = Fraction(1);
# falls Bruchteile erlaubt sind, füge einen Bruchteil des i. Items hinzu und abbrechen
elif fractional:
choice[i] = Fraction(Fraction(max_cost - cost_total)/Fraction(costs[i]), _normalize=False);
vector[i] = Fraction(Fraction(max_cost - cost_total)/Fraction(costs[i]), _normalize=False);
break;
# ansonsten weiter machen:
else:
continue;
# Aspekte der Lösung speichern:
rucksack = [i for i, v in enumerate(choice) if v > 0]; # Indexes von Items im Rucksack
rucksack = [i for i, v in enumerate(vector) if v > 0]; # Indexes von Items im Rucksack
soln = Solution(
order = order,
choice = choice,
choice = vector,
items = items[rucksack].tolist(),
costs = costs[rucksack].tolist(),
values = values[rucksack].tolist(),
@ -83,7 +83,7 @@ def rucksack_greedy_algorithm(
# verbose output hier behandeln (irrelevant für Algorithmus):
if verbose:
repr_rucksack = display_rucksack(items=items, costs=costs, values=values, choice=choice);
repr_rucksack = display_rucksack(items=items[rucksack], costs=costs[rucksack], values=values[rucksack]);
print('\x1b[1mEingeschätzte Lösung\x1b[0m');
print('');
print(f'Mask: [{", ".join(map(str, soln.choice))}]');
@ -122,31 +122,24 @@ def rucksack_branch_and_bound_algorithm(
print('');
logged_steps = [];
step: Step;
mask = empty_mask(n=len(costs));
bound = np.inf;
vector = empty_mask(n=len(costs));
lb_estimate = np.inf;
S = Stack();
S.push(mask);
S.push(vector);
while not S.empty():
# top-Element auslesen und Bound berechnen:
A: Mask = S.top();
bound_subtree, choice, order_, pad = estimate_lower_bound(mask=A, max_cost=max_cost, costs=costs, values=values, items=items);
# für logging:
lb, choice, order_, pad = estimate_lower_bound(mask=S.top(), max_cost=max_cost, costs=costs, values=values, items=items);
if verbose:
step = Step(bound=bound, bound_subtree=bound_subtree, stack_str=str(S), choice=choice, order=order_, indexes=A.indexes_unset, pad=pad);
S.pop();
logged_steps.append((lb_estimate, lb, str(S), choice, order_, pad));
# Update nur nötig, wenn die (eingeschätzte) untere Schranke von A das bisherige Minimum verbessert:
if bound_subtree < bound:
# Bound aktualisieren, wenn sich A nicht weiter aufteilen od. wenn sich A wie eine einelementige Option behandeln läst:
A: Mask = S.pop();
if lb < lb_estimate:
# Bound, wenn sich A nicht weiter aufteilen lässt od. man A wie eine einelementige Option behandeln kann:
if not A.splittable() or pad != MaskValue.UNSET:
bound = bound_subtree;
lb_estimate = lb;
# falls A als einelementige Menge betrachtet werden kann, ersetze unbekannte Werte:
if pad != MaskValue.UNSET:
A = A.pad(pad);
mask = A;
# für logging:
if verbose:
step.move = EnumBranchAndBoundMove.BOUND;
vector = A;
# Branch sonst
else:
B, C = A.split();
@ -154,17 +147,12 @@ def rucksack_branch_and_bound_algorithm(
# Nur dann C auf Stack legen, wenn mind. eine Möglichkeit in C die Kapazitätsschranke erfüllt:
if sum(costs[C.indexes_one]) <= max_cost:
S.push(C);
# für logging:
if verbose:
step.move = EnumBranchAndBoundMove.BRANCH;
if verbose:
logged_steps.append(step);
# Aspekte der Lösung speichern
rucksack = mask.indexes_one; # Indexes von Items im Rucksack
rucksack = vector.indexes_one; # Indexes von Items im Rucksack
soln = Solution(
order = order,
choice = mask.choice,
choice = vector.choice,
items = items[rucksack].tolist(),
values = values[rucksack].tolist(),
costs = costs[rucksack].tolist(),
@ -173,11 +161,11 @@ def rucksack_branch_and_bound_algorithm(
# verbose output hier behandeln (irrelevant für Algorithmus):
if verbose:
repr = display_branch_and_bound(values=values, steps=logged_steps);
repr_rucksack = display_rucksack(items=items, costs=costs, values=values, choice=mask.choice);
print(repr);
print('');
repr_rucksack = display_rucksack(items=items[rucksack], costs=costs[rucksack], values=values[rucksack]);
print('\x1b[1mLösung\x1b[0m');
print('');
print(repr);
print('');
print(f'Mask: [{", ".join(map(str, soln.choice))}]');
print('Rucksack:');
print(repr_rucksack);
@ -213,7 +201,7 @@ def estimate_lower_bound(
mit Greedy-Algorithmus »lösen«,
um schnell eine gute Einschätzung zu bestimmen.
NOTE: Diese Funktion wird `g(mask)` im Skript bezeichnet.
NOTE: Diese Funktion wird `g(vector)` im Skript bezeichnet.
'''
indexes_one = mask.indexes_one;
indexes_unset = mask.indexes_unset;

View File

@ -9,8 +9,6 @@ from src.thirdparty.code import *;
from src.thirdparty.maths import *;
from src.thirdparty.types import *;
from src.setup import config;
from models.generated.config import *;
from src.models.stacks import *;
from src.models.rucksack import *;
@ -64,31 +62,18 @@ def display_rucksack(
items: np.ndarray,
costs: np.ndarray,
values: np.ndarray,
choice: List[Fraction],
) -> str:
show_options = config.OPTIONS.rucksack.show;
render = lambda r: f'{r:g}';
choice = np.asarray(choice);
rucksack = np.where(choice > 0);
if not(EnumRucksackShow.all_weights in show_options):
items = items[rucksack];
costs = costs[rucksack];
values = values[rucksack];
choice = choice[rucksack];
table = pd.DataFrame({
'items': items.tolist() + ['----', ''],
'nr': list(map(str, choice))
+ ['----', f'\x1b[92;1m{float(sum(choice)):g}\x1b[0m'],
'costs': list(map(render, costs))
+ ['----', f'\x1b[92;1m{sum(choice*costs):g}\x1b[0m'],
'values': list(map(render, values))
+ ['----', f'\x1b[92;1m{sum(choice*values):g}\x1b[0m'],
'costs': list(map(render, costs)) + ['', f'\x1b[92;1m{sum(costs):g}\x1b[0m'],
'values': list(map(render, values)) + ['', f'\x1b[92;1m{sum(values):g}\x1b[0m'],
});
repr = tabulate(
table,
headers=['item', 'nr', 'cost', 'value'],
headers=['item', 'cost', 'value'],
showindex=False,
colalign=('left', 'center', 'center', 'center'),
colalign=('left', 'center', 'center'),
tablefmt='rst'
);
return repr;
@ -97,39 +82,30 @@ def display_rucksack(
# METHOD display result of branch and bound
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def display_branch_and_bound(values: np.ndarray, steps: List[Step]) -> str:
show_options = config.OPTIONS.rucksack.show;
show_all_sums = (EnumRucksackShow.all_sums in show_options);
def display_branch_and_bound(
values: np.ndarray,
steps: List[Tuple[float, float, Stack, List[Fraction], List[int], MaskValue]],
) -> str:
# füge Summen-Ausdrücke für Greedy-Alg hinzu:
rows = [];
used_choices = [];
index_soln = max([-1] + [ i for i, step in enumerate(steps) if step.move == EnumBranchAndBoundMove.BOUND ]);
for i, step in enumerate(steps):
if show_all_sums or step.choice not in used_choices:
# Füge Summen-Ausdrücke für Greedy-Alg hinzu:
used_choices.append(step.choice);
expr = display_sum(choice=step.choice, values=values, as_maximum=False, order=step.order, indexes=step.indexes);
for lb_estimate, lb, S, choice, order, pad in steps:
if choice in used_choices:
expr = f'{lb:g}';
else:
expr = f'{step.bound_subtree:g}';
pad_str = ('' if step.pad == MaskValue.UNSET else step.pad.value);
move_str = ('' if step.move == EnumBranchAndBoundMove.NONE else step.move.value);
if i == index_soln:
move_str = f'{move_str} *';
rows.append({
'bound': f'{step.bound:+g}',
'bound_subtree': expr,
'stack': step.stack_str,
'pad': f'\x1b[2m{pad_str}\x1b[0m',
'move': f'\x1b[2m{move_str}\x1b[0m',
});
used_choices.append(choice);
expr = display_sum(choice=choice, values=values, as_maximum=False, order=order);
rows.append((f'{lb_estimate:g}', expr, ('' if pad == MaskValue.UNSET else pad.value), S));
table = pd.DataFrame(rows).reset_index(drop=True);
table = pd.DataFrame(rows) \
.rename(columns={0: 'b', 1: 'g(TOP(S))', 2: 'pad?', 3: 'S'}) \
.reset_index(drop=True);
# benutze pandas-Dataframe + tabulate, um schöner darzustellen:
repr = tabulate(
table,
headers=['bound', 'g(TOP(S))', 'S — stack', '\x1b[2mpad?\x1b[0m', '\x1b[2mmove\x1b[0m'],
headers=['b', 'g(TOP(S))', 'pad?', 'S'],
showindex=False,
colalign=('left', 'left', 'right', 'center', 'left'),
colalign=('left', 'left', 'center', 'right'),
tablefmt='rst'
);
return repr;
@ -142,31 +118,17 @@ def display_sum(
choice: List[Fraction],
values: np.ndarray,
order: Optional[List[int]] = None,
indexes: List[int] = [],
as_maximum: bool = True,
) -> str:
show_options = config.OPTIONS.rucksack.show;
show_all_weights = (EnumRucksackShow.all_weights in show_options);
def render(x: Tuple[bool, Fraction, float]):
b, u, value = x;
if u == 0:
expr = f'\x1b[94;2m{value:g}\x1b[0m' if b else f'\x1b[2m{value:g}\x1b[0m';
else:
expr = f'\x1b[94m{value:g}\x1b[0m' if b else f'\x1b[0m{value:g}\x1b[0m';
if not show_all_weights and u == 1:
return expr;
return f'\x1b[2;4m{u}\x1b[0m\x1b[2m·\x1b[0m{expr}';
parts = [ (i in indexes, u, x) for i, (u, x) in enumerate(zip(choice, values)) ];
parts = [ (u, x) for u, x in zip(choice, values)];
if not (order is None):
parts = [ parts[j] for j in order ];
if not show_all_weights:
parts = list(filter(lambda x: x[1] > 0, parts));
value = sum([ u*x for _, u, x in parts ]);
expr = '\x1b[2m+\x1b[0m'.join(map(render, parts));
value = sum([ u*x for u, x in parts]);
expr = '+'.join([
f'{x:g}' if u == 1 else f'{u}·{x:g}'
for u, x in parts if u > 0
]);
if as_maximum:
return f'{value:g} \x1b[2m=\x1b[0m {expr}';
return f'-{value:g} \x1b[2m= -(\x1b[0m{expr}\x1b[2m)\x1b[0m';
return f'{value:g} = {expr}';
else:
return f'-{value:g} = -({expr})';

View File

@ -7,7 +7,6 @@
from src.models.rucksack.mask import *;
from src.models.rucksack.solution import *;
from src.models.rucksack.logging import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
@ -18,6 +17,4 @@ __all__ = [
'MaskValue',
'Mask',
'Solution',
'EnumBranchAndBoundMove',
'Step',
];

View File

@ -1,47 +0,0 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# IMPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
from __future__ import annotations;
from src.thirdparty.maths import *;
from src.thirdparty.types import *;
from src.models.rucksack.mask import *;
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# EXPORTS
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
__all__ = [
'EnumBranchAndBoundMove',
'Step',
];
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# CLASS Move
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class EnumBranchAndBoundMove(Enum):
NONE = -1;
BOUND = 'bound';
BRANCH = 'branch';
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# CLASS Step
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@dataclass
class Step():
bound: float = field();
bound_subtree: float = field();
stack_str: str = field();
choice: List[Fraction] = field();
order: List[int] = field();
# the indexes upon which the greedy algorithm is carried out:
indexes: List[int] = field();
pad: MaskValue = field();
move: EnumBranchAndBoundMove = field(default=EnumBranchAndBoundMove.NONE);

View File

@ -12,10 +12,8 @@ Inhaltsverzeichnis
- [Vorlesungswoche 7](./woche4.md)
- [Vorlesungswoche 8](./woche4.md)
- [Vorlesungswoche 9](./woche4.md)
-->
- [Vorlesungswoche 10](./woche10.md)
- [Vorlesungswoche 11](./woche11.md)
<!--
- [Vorlesungswoche 12](./woche12.md)
- [Vorlesungswoche 13](./woche13.md)
- [Vorlesungswoche 14](./woche14.md)

View File

@ -1,14 +0,0 @@
# Vorlesungswoche 10 (6.12. Juni 2022) #
## Agenda ##
- [x] Hirschbergalgorithmus
Implementierung zum Austesten findet man in [code/python](./../code/python). _Beachte:_
- Der Code ist etwas ineffizient implementiert,
weil extra (unnötige) Informationen zwecks schöner Darstellung gespeichert wird.
Die Schritte sind jedoch korrekt.
- Man kann die Aspekte der Probleme
in dem [assets](./../code/python/assets) Ordner anpassen,
wie bspw. die Prioritäten der Bewegungen innerhalb der Editmatrix.

View File

@ -1,20 +0,0 @@
# Vorlesungswoche 11 (13.19. Juni 2022) #
## Agenda ##
- [ ] Rucksackproblem
- Greedyalgorithmus
- Branch & Bound
## Implementierung ##
Implementierung zum Austesten findet man in [code/python](./../code/python). _Beachte:_
- Der Code ist etwas ineffizient implementiert,
weil extra (unnötige) Informationen zwecks schöner Darstellung gespeichert wird.
Die Schritte sind jedoch korrekt.
- Man kann die Aspekte der Probleme
in dem [assets](./../code/python/assets) Ordner anpassen,
wie bspw. ob alle Gewichte und alle Summen angezeigt werden sollen.
In den Beispielen wird _mehr als nötig_ ausgegeben. Die extra Spalten sowie die etwas unnötig ausführlich aufgeschriebenen Summen sollen nur didaktischen Zwecken dienen. Sobald man alles kapiert hat, kann man selbstverständlich auf die zusätzlichen Teile verzichten.