File size: 11,444 Bytes
6d3697a
 
 
cd6510a
f231efc
6d3697a
 
 
4b0a34a
 
 
 
cd6510a
 
 
4b0a34a
 
 
 
 
 
 
39f5afc
4b0a34a
39f5afc
4b0a34a
39f5afc
4b0a34a
 
83cff4c
4b0a34a
 
 
 
83cff4c
4b0a34a
83cff4c
 
 
 
 
 
6d3697a
 
4b0a34a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d3697a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95902a6
6d3697a
 
 
 
 
275ca2d
 
 
 
 
6d3697a
 
 
 
275ca2d
6d3697a
95902a6
f231efc
 
 
cd6510a
95902a6
cd6510a
6d3697a
f231efc
4b0a34a
 
 
 
f231efc
 
6d3697a
f231efc
 
6d3697a
f231efc
 
 
 
 
 
 
6d3697a
f231efc
 
6d3697a
f231efc
 
6d3697a
f231efc
6d3697a
f231efc
 
 
6d3697a
f231efc
 
 
6d3697a
f231efc
 
 
 
 
6d3697a
f231efc
6d3697a
671b8d8
f231efc
 
 
 
 
cd6510a
f231efc
cd6510a
671b8d8
f231efc
 
 
671b8d8
95902a6
671b8d8
95902a6
 
 
 
6d3697a
 
83cff4c
 
f231efc
 
83cff4c
 
 
4b0a34a
cd6510a
 
 
 
f231efc
cd6510a
4b0a34a
 
 
6d3697a
f231efc
 
 
 
 
 
 
 
 
6d3697a
4b0a34a
f231efc
 
4b0a34a
 
83cff4c
4b0a34a
 
cd6510a
 
 
f231efc
 
 
cd6510a
 
 
 
 
 
4b0a34a
f231efc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95902a6
8c9e35f
 
 
 
 
 
 
 
 
 
4b0a34a
83cff4c
 
95902a6
 
4b0a34a
f231efc
8c9e35f
 
95902a6
8c9e35f
95902a6
8c9e35f
 
 
 
 
 
 
 
 
95902a6
8c9e35f
 
f231efc
 
 
 
 
 
 
 
 
8c9e35f
6d3697a
4b0a34a
 
f231efc
6d3697a
f231efc
 
6d3697a
4b0a34a
 
 
6d3697a
 
 
 
b64d569
 
6d3697a
 
 
 
f231efc
 
95902a6
8c9e35f
b64d569
8c9e35f
b64d569
 
 
6d3697a
4b0a34a
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import gradio as gr
import pandas as pd
import numpy as np
from numpy.typing import NDArray
from pyscipopt import Model, quicksum

# Define the quality tiers and names for the plants
PLANTS_TIERS = {
    "radiant": "RADIANT",
    "flourishing": "FLOURISHING",
    "hardy": "HARDY",
    "feeble": "FEEBLE",
    "radiant_rarecolor": "RADIANT+RARE",
    "flourishing_rarecolor": "FLOURISHING+RARE",
    "hardy_rarecolor": "HARDY+RARE",
}

PLANTS_LABLES = {
    "fanged_geranium": "Fanged Geranium",
    "gillyweed": "Gillyweed",
    "rose": "Rose",
    "puffapod": "Puffapod",
    "wild_pansy": "Wild Pansy",
    "nifflers_fancy": "Niffler's Fancy",
    "fanwort": "Fanwort",
    "ladys_mantle": "Lady's Mantle",
    "kelp": "Kelp",
    "mandrake": "Mandrake",
    "chinese_chomping_cabbage": "Chinese Chomping Cabbage",
    "dragons_breath_macroalgae": "Dragon's Breath Macroalgae",
    "peony": "Peony",
    "begonia": "Begonia",
    "mayflower": "Mayflower",
    "hydrangea": "Hydrangea",
    "ludwigia_glandulosa": "Ludwigia Glandulosa",
    "daffodil": "Daffodil",
    "water_hyacinth": "Water Hyacinth",
    "lily_of_the_valley": "Lily of the Valley",
    "mosaic_flower": "Mosaic Flower",
    "sunflower": "Sunflower",
    "mimbulus_mimbletonia": "Mimbulus Mimbletonia",
    "water_lily": "Water Lily",
}

INTERFACE_TEXTS = {
    "cn": {
        "gold_label": "葭碧の金币预算:",
        "strategies_label": "请选择凑单策略:",
        "clear_btn_label": "❌清除",
        "calculate_btn_label": "🛠计算",
        "output_label": "计算结果:",
        "strategy_options": [
            ("最小化售出株数(优先出售高价植物)", "MaximizeStock"),
            ("最大化售出株数(优先出售低价植物)", "MinimizeStock"),
        ],
    },
    "en": {
        "gold_label": "Gabby's Gold Budget:",
        "strategies_label": "Select a strategy:",
        "clear_btn_label": "❌Clear",
        "calculate_btn_label": "🛠Calculate",
        "output_label": "Output:",
        "strategy_options": [
            (
                "Minimize the number of plants sold (prioritize high-priced plants)",
                "MaximizeStock",
            ),
            (
                "Maximize the number of plants sold (prioritize low-priced plants)",
                "MinimizeStock",
            ),
        ],
    },
}

# Import and process plant data
df = pd.read_csv("plants.csv")

# Convert columns to Categorical type and remove rows with NaN in 'gold' column
df["species"] = pd.Categorical(df["species"])
df["tier"] = pd.Categorical(df["tier"])
df = df.dropna(subset=["gold"])
df = df.astype(
    {
        "gold": int,
        "gems": int,
    }
)


def calculator(currency, budget, strategy, extra_rate, *amount):
    """

    Calculate the optimal solution of plant sales based on the given budget

    and inventory constraints.



    Args:

        *args (tuple): A tuple containing:

            - budget (int): Gabby's gold budget.

            - strategy (str): The selected strategy for selling plants ("MaximizeStock" or "MinimizeStock").

            - extra_rate (int): The premium rate for selling plants.

            - stocks (list of int): Stock levels of each plant type.



    Returns:

        str: A description of the optimal solution, including which plants to sell,

             the total gold earned, and the remaining inventory.

             Returns an error message if no solution is found.

    """
    # currency: str, budget: int, strategy:str, extra_rate:int = args[0:4]
    # budget: int = args[0]  # 葭碧预算
    # strategy: str = args[1]  # 出售策略
    # extra_rate: int = args[2]  # 高价收购倍率
    stocks: NDArray[np.int_ | np.integer] = np.array(
        [x if x else 0 for x in amount]
    )  # 植物库存

    # Plant names and prices
    plants_names = [
        f"{PLANTS_TIERS[row['tier']]} {PLANTS_LABLES[row['species']]}"
        for index, row in df.iterrows()
    ]
    price = df[currency]  # 植物单价
    sold_prices = np.array(price * (1 + extra_rate))

    # Initialize the master problem
    model = Model("BewilderingBlossom")

    # Decision variables in master problem
    x = [
        model.addVar(
            vtype="I", name=f"x_{i}", lb=0, ub=int(stocks[i]) if stocks[i] else 0
        )
        for i in range(len(stocks))
    ]

    obj1 = quicksum(sold_prices[i] * x[i] for i in range(len(stocks)))
    obj2 = quicksum(x[i] for i in range(len(stocks)))

    # Objective: maximize total value of sold plants
    model.setObjective(obj1, "maximize")

    model.addCons(obj1 <= budget)

    # first optimize
    model.hideOutput()
    model.optimize()

    if model.getStatus() == "optimal":
        optimal_total_value = model.getObjVal()
        model.freeTransform()

        model.setObjective(
            obj2, "maximize" if strategy == "MinimizeStock" else "minimize"
        )
        model.addCons(obj1 == optimal_total_value)
        model.optimize()

        # Final solution processing
        solution = []
        total_price = 0
        # total_count = 0

        if model.getStatus() == "optimal":
            for i, var in enumerate(x):
                if (v := int(model.getVal(var))) > 0 and sold_prices[i] > 0:
                    solution.append(
                        f"{plants_names[i]} ({sold_prices[i]} {currency}): {v}\n"
                    )
                    total_price += v * sold_prices[i]
                    # total_count += v

            if optimal_total_value == budget:
                return f"Great! Found a combination of items with a total value equal to the budget ({budget} {currency}).😃\n\n{''.join(solution)}\nTotal value: {int(total_price)} {currency}\n"  # Count: {int(model.getObjVal())}

            return f"Oops! {int(budget - optimal_total_value)} {currency} short of the target value ({budget} {currency}).😣\n\n{''.join(solution)}\nTotal value: {int(total_price)} {currency}\n"  # Count: {int(model.getObjVal())}

        return "No solution found for the second optimization!"

    return "No solution found for the first optimization!"


# 高亮每种植物的最高品质
css = """

.first-gold-box {background-color: #fafad2}

.first-gems-box {background-color: #fed9b4}

"""

with gr.Blocks(css=css) as demo:
    gr.Markdown(
        """

        <center><font size=8>HP-Magic-Awakened Herbologist Toolkit👾</font></center>



        This program is essentially a solver for a variant of the knapsack problem. 

        Another more versatile [application](https://huggingface.co/spaces/oh-my-dear-ai/easy-knapsack-problem).

        """
    )

    # Create a Gradio interface with a column layout
    with gr.Column():
        # Add a row for the currency selection
        currency_radio = gr.Radio(
            choices=["gold", "gems"],
            value="gold",
            type="value",
            label="Currency",
            info="Select the currency:",
            render=True,
        )
        # Add a row for the budget input
        budget = gr.Number(
            label="Target",
            info="Gabby's Budget:",  # "葭碧の金币预算:",
            value=0,
            minimum=0,
            maximum=20000,
            step=100,
        )
        acquisition_rate = gr.Dropdown(
            choices=[
                "0(Gabby's Acquisition)",
                "+100%(HVA for Budding & Novice)",
                "+200%(HVA for Junior & Practiced)",
                "+300%(HVA for Natural & Master)",
            ],
            value="0(Gabby's Acquisition)",
            type="index",
            label="Extra Acquisition Rate",
            info="Select your high-value acquisition rate:",
        )

        # Add a radio selection for the strategy
        selected_strategy = gr.Radio(
            [
                (
                    "Minimize the number of plants sold (prioritize high-priced plants)",
                    "MaximizeStock",
                ),
                (
                    "Maximize the number of plants sold (prioritize low-priced plants)",
                    "MinimizeStock",
                ),
            ],
            value="MaximizeStock",
            label="Strategies",
            info="Select a strategy:",
        )

        # TODO: Add a checkbox group for selecting plants
        # selected_plants = gr.CheckboxGroup(
        #     choices=list(PLANTS_LABLES.values()),
        #     type="index",
        #     label="Plants",
        #     info="Select plants:",
        #     value=list(PLANTS_LABLES.values()),
        #     interactive=True,
        # )

    def show_plant_boxes(currency):
        inventory = {}
        species_set = set()
        species_count = 0
        new_species = False

        for _, row in df.iterrows():
            # Check if the plant should be shown based on the selected currency
            if row[currency] != 0 and row["tier"] != "feeble":
                species_set.add(row["species"])
                new_species = len(species_set) > species_count
                # Create the Number component for the plant inventory

                inventory[f"{row['species']}_{row['tier']}"] = gr.Number(
                    label=PLANTS_LABLES[row["species"]],
                    info=f"{PLANTS_TIERS[row['tier']]} ${row[currency]}",
                    value=0,
                    precision=0,
                    minimum=0,
                    maximum=500,
                    step=10,
                    visible=True,
                    elem_classes=(f"first-{currency}-box" if new_species else None),
                )
                species_count = len(species_set)
            else:
                # If not shown, create a dummy invisible component
                inventory[f"{row['species']}_{row['tier']}"] = gr.Number(visible=False)

        # Return the updated inventory components
        return list(inventory.values())

    # Create the dynamic plant inventory inputs
    with gr.Row() as inventory_row:
        inventory = show_plant_boxes(currency_radio.value)

    # Add a row for the Clear and Calculate buttons
    with gr.Row():
        clear_btn = gr.ClearButton(inventory, size="sm", value="❌Clear")

    # Add a button to trigger the calculation
    submit_btn = gr.Button(value="🛠Calculate")

    # Add a row for the result textbox
    with gr.Row():
        result = gr.Textbox(label="Output")

    # Set up the button click event to call the calculator function
    submit_btn.click(
        calculator,
        inputs=[currency_radio, budget, selected_strategy, acquisition_rate]
        + inventory,
        outputs=[result],
        api_name=False,
    )

    # Update the inventory when the currency changes
    currency_radio.change(
        fn=lambda selected_currency: show_plant_boxes(
            selected_currency
        ),  # Adjusted function to return only the components
        inputs=[currency_radio],
        outputs=inventory,  # Update each child in the inventory_row
    )

# Launch the Gradio application
demo.queue(api_open=False)
demo.launch(max_threads=5, share=False)