master > master: code py - korrigierte Darstellung für fractional-Fall

This commit is contained in:
RD 2022-06-14 20:39:01 +02:00
parent 92f038d4dd
commit 7b2950fc7a
2 changed files with 19 additions and 17 deletions

View File

@ -57,25 +57,25 @@ def rucksack_greedy_algorithm(
# führe greedy aus:
n = len(costs);
cost_total = 0;
vector = [ Fraction(0) for _ in range(n) ];
choice = [ 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];
vector[i] = Fraction(1);
choice[i] = Fraction(1);
# falls Bruchteile erlaubt sind, füge einen Bruchteil des i. Items hinzu und abbrechen
elif fractional:
vector[i] = Fraction(Fraction(max_cost - cost_total)/Fraction(costs[i]), _normalize=False);
choice[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(vector) if v > 0]; # Indexes von Items im Rucksack
rucksack = [i for i, v in enumerate(choice) if v > 0]; # Indexes von Items im Rucksack
soln = Solution(
order = order,
choice = vector,
choice = choice,
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[rucksack], costs=costs[rucksack], values=values[rucksack]);
repr_rucksack = display_rucksack(items=items[rucksack], costs=costs[rucksack], values=values[rucksack], choice=np.asarray(choice)[rucksack]);
print('\x1b[1mEingeschätzte Lösung\x1b[0m');
print('');
print(f'Mask: [{", ".join(map(str, soln.choice))}]');
@ -122,10 +122,10 @@ def rucksack_branch_and_bound_algorithm(
print('');
logged_steps = [];
vector = empty_mask(n=len(costs));
mask = empty_mask(n=len(costs));
lb_estimate = np.inf;
S = Stack();
S.push(vector);
S.push(mask);
while not S.empty():
lb, choice, order_, pad = estimate_lower_bound(mask=S.top(), max_cost=max_cost, costs=costs, values=values, items=items);
if verbose:
@ -139,7 +139,7 @@ def rucksack_branch_and_bound_algorithm(
# falls A als einelementige Menge betrachtet werden kann, ersetze unbekannte Werte:
if pad != MaskValue.UNSET:
A = A.pad(pad);
vector = A;
mask = A;
# Branch sonst
else:
B, C = A.split();
@ -149,10 +149,10 @@ def rucksack_branch_and_bound_algorithm(
S.push(C);
# Aspekte der Lösung speichern
rucksack = vector.indexes_one; # Indexes von Items im Rucksack
rucksack = mask.indexes_one; # Indexes von Items im Rucksack
soln = Solution(
order = order,
choice = vector.choice,
choice = mask.choice,
items = items[rucksack].tolist(),
values = values[rucksack].tolist(),
costs = costs[rucksack].tolist(),
@ -161,7 +161,7 @@ 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[rucksack], costs=costs[rucksack], values=values[rucksack]);
repr_rucksack = display_rucksack(items=items[rucksack], costs=costs[rucksack], values=values[rucksack], choice=np.asarray(mask.choice)[rucksack]);
print('\x1b[1mLösung\x1b[0m');
print('');
print(repr);
@ -201,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(vector)` im Skript bezeichnet.
NOTE: Diese Funktion wird `g(mask)` im Skript bezeichnet.
'''
indexes_one = mask.indexes_one;
indexes_unset = mask.indexes_unset;

View File

@ -62,18 +62,20 @@ def display_rucksack(
items: np.ndarray,
costs: np.ndarray,
values: np.ndarray,
choice: np.ndarray,
) -> str:
render = lambda r: f'{r:g}';
table = pd.DataFrame({
'items': items.tolist() + ['----', ''],
'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'],
'nr': list(map(str, choice)) + ['----', f'{float(sum(choice)):g}'],
'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'],
});
repr = tabulate(
table,
headers=['item', 'cost', 'value'],
headers=['item', 'nr', 'cost', 'value'],
showindex=False,
colalign=('left', 'center', 'center'),
colalign=('left', 'center', 'center', 'center'),
tablefmt='rst'
);
return repr;