/ -*- coding: utf-8 -*-
/ ---
/ jupyter:
/   jupytext:
/     text_representation:
/       extension: .q
/       format_name: light
/       format_version: '1.5'
/       jupytext_version: 1.14.4
/ ---

/ + cell_id="00b59c84-25b7-4c1f-aa19-7cfc21acad96" deepnote_cell_height=225 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=2403 execution_start=1647057553942 source_hash="9a04bb9a" tags=[]
from time import time

import json
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from deap import algorithms, base, creator, tools

/ + [markdown] cell_id="8042aa05-6f32-4bd5-9cce-9e29752c3891" deepnote_cell_height=82 deepnote_cell_type="text-cell-h1" is_collapsed=false tags=[]
/ # Lectura de información

/ + cell_id="aae26334-c33d-446f-a923-e862fe6e2f08" deepnote_cell_height=117 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=293 execution_start=1647057556346 source_hash="94d8aefd" tags=[]
PRODUCTS = pd.read_csv("/work/games_seeker/data/interim/pc_components.csv", sep="|")
with open("/work/games_seeker/data/interim/products_weights.json", "r") as f:
    WEIGHTS = json.load(f)

/ + cell_id="2eb6d3da-d29b-4f7d-a304-daec6dcecc90" deepnote_cell_height=598 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=132 execution_start=1647057556671 source_hash="9a022219" tags=[]
PRODUCTS

/ + cell_id="1d4dd22b-88b5-41a0-8392-6fddcf70b4ea" deepnote_cell_height=118.1875 deepnote_cell_type="code" deepnote_output_heights=[21.1875] deepnote_to_be_reexecuted=false execution_millis=41 execution_start=1647057556824 source_hash="5780dd38" tags=[]
WEIGHTS.keys()

/ + [markdown] cell_id="f55ab7c2-2626-46fd-9b65-64e8871bec30" deepnote_cell_height=82 deepnote_cell_type="text-cell-h1" is_collapsed=false tags=[]
/ # Constantes

/ + cell_id="2599051a-d0e5-4901-8c17-a5831dc41f71" deepnote_cell_height=99 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=506697 execution_start=1647057556873 source_hash="be19c1be" tags=[]
PRESUPUESTO = 2900
COMPONENTS_ORDER = ("CPU", "Mother Board", "RAM", "Storage", "GPU", "Refrigeration", "Power Supply", "Chasis")

/ + [markdown] cell_id="e47f1dfe-3f4f-4aa3-a44e-9af75017ad7d" deepnote_cell_height=82 deepnote_cell_type="text-cell-h1" is_collapsed=false tags=[]
/ # Creación de objetos para definir el problema y el tipo de individuo

/ + cell_id="8c593f7a-9532-4d56-96e8-93c53b08986f" deepnote_cell_height=137.375 deepnote_cell_type="code" deepnote_output_heights=[40.375] deepnote_to_be_reexecuted=false execution_millis=906108 execution_start=1647057556896 source_hash="168781b9" tags=[]
PRODUCTS["type"].unique()

/ + cell_id="cf89123a-a57b-4740-8352-f4d4c29f1cd2" deepnote_cell_height=153 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=906123 execution_start=1647057556923 source_hash="5a8b8175" tags=[]
def create_individual():
    return [
        random.choice(PRODUCTS[PRODUCTS["type"] == product].index)
        for product in COMPONENTS_ORDER
    ]

/ + cell_id="9056a513-ced5-4803-8083-e212c6331f69" deepnote_cell_height=118.1875 deepnote_cell_type="code" deepnote_output_heights=[21.1875] deepnote_to_be_reexecuted=false execution_millis=906115 execution_start=1647057556940 source_hash="7823f61b" tags=[]
create_individual()

/ + cell_id="3631aa65-7144-43d1-83c1-17be64683b48" deepnote_cell_height=351 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=906150 execution_start=1647057556972 source_hash="a8533875" tags=[]
def register_initial_components():
    for _class in ("FitnessMax", "Individual"):
        if _class in dir(creator):
            delattr(creator, _class)

    creator.create("FitnessMax", base.Fitness, weights=(1.0,))
    creator.create("Individual", list, fitness=creator.FitnessMax)

    toolbox = base.Toolbox()

    # Generación del individuo
    toolbox.register("indices", create_individual)
    toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.indices)
    toolbox.register("population", tools.initRepeat, list, toolbox.individual)

    return toolbox

/ + cell_id="ccf803c2-3402-4db8-b125-df4023984801" deepnote_cell_height=207 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=906134 execution_start=1647057557001 source_hash="d5e8731a" tags=[]
def eval_budget(individual):
    """Funcion objetivo, calcula el valor de los componentes"""
    prices = [PRODUCTS.loc[idx, "price"] for idx in individual]
    total =  sum(prices)
    _, counts = np.unique(individual, return_counts=True)
    if not all(counts == 1):
        return -1,
    return (total,) if total <= PRESUPUESTO else (-1,)

/ + cell_id="34f71e49-d794-43c4-a368-63ef7040aab1" deepnote_cell_height=189 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=906161 execution_start=1647057557029 source_hash="ac59bd00" tags=[]
def register_genetic_operators(toolbox):
    toolbox.register("mate", tools.cxOnePoint)
    toolbox.register("mutate", tools.mutFlipBit, indpb=0.1)
    toolbox.register("select", tools.selTournament, tournsize=3)
    toolbox.register("evaluate", eval_budget)
    return toolbox


/ + cell_id="f816b52c-0eb4-4e31-9bc9-2a870c53ee3c" deepnote_cell_height=351 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=906179 execution_start=1647057557060 source_hash="ca919d56" tags=[]
def plot_evolution(log):
    gen = log.select("gen")
    fit_mins = log.select("min")
    fit_maxs = log.select("max")
    fit_avg = log.select("avg")

    fig, ax1 = plt.subplots(figsize=(8,8))
    ax1.plot(gen, fit_mins, "b")
    ax1.plot(gen, fit_maxs, "r")
    ax1.plot(gen, fit_avg, "--k")
    ax1.fill_between(gen , fit_mins , fit_maxs, facecolor='g', alpha = 0.2)
    ax1.set_title("Maximizar compra PC segun presupuesto mediante algoritmos geneticos")
    ax1.set_xlabel("Generation")
    ax1.set_ylabel("Fitness")
    ax1.legend (["Min", "Max", "Avg"], loc="upper right")
    plt.grid(True)

/ + cell_id="1d12476a-fe80-442f-8a29-fc2f5af3ff92" deepnote_cell_height=441 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=2 execution_start=1647057557088 source_hash="b73d9d74" tags=[]
def simulate(toolbox, CXPB, MUTPB, NGEN, NIND=50, verbose=False, **kwargs):
    pop = toolbox.population(NIND)
    hof = tools.HallOfFame(1)

    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", np.mean)
    stats.register("std", np.std)
    stats.register("min", np.min)
    stats.register("max", np.max)

    pop, logbook = algorithms.eaSimple(
        pop,
        toolbox,
        CXPB,
        MUTPB,
        NGEN,
        stats=stats,
        halloffame=hof,
        verbose=verbose
    )
    return pop, logbook

/ + cell_id="f3a9e957-7015-44b8-ba3a-bab26f4eb9f9" deepnote_cell_height=369 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=15 execution_start=1647057557100 source_hash="a7991aff" tags=[]
def run(cases):
    random.seed(100)
    results = []
    results_logs = {idx+1: [] for idx in range(len(cases))}
    for idx, case in enumerate(cases):
        toolbox = register_initial_components()
        toolbox = register_genetic_operators(toolbox)
        for i in range(10):
            t0 = time()
            best, log = simulate(toolbox, **case)
            results.append([idx+1, i, case["NIND"], case["CXPB"],
                case["MUTPB"], case["NGEN"], best[0].fitness.values[0], best[0], round(time()-t0, 4)]
            )
            results_logs[idx+1].append(log)
            print(f"Case {idx+1}: {(i+1)*10}%")

    return pd.DataFrame(results, columns=["Test ID", "Try", "Population", "CXPB", "MUTPB", "NGEN", "Best Fitness", "Best", "Time"]), results_logs

/ + cell_id="a206d231-03e6-49f0-a8d6-81f80ec698a1" deepnote_cell_height=189 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=5 execution_start=1647057872621 source_hash="38474efa" tags=[]
cases = (
    {"CXPB":0.8, "MUTPB":0.2, "NGEN":50, "NIND":100},
    {"CXPB":0.4, "MUTPB":0.6, "NGEN":50, "NIND":100},
    {"CXPB":0.2, "MUTPB":0.2, "NGEN":50, "NIND":100},
    {"CXPB":0.3, "MUTPB":0.7, "NGEN":50, "NIND":100},
    {"CXPB":0.6, "MUTPB":0.4, "NGEN":50, "NIND":100},
)

/ + cell_id="97deb54e-d17b-4624-96ef-abb319eea63c" deepnote_cell_height=293.875 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=17796 execution_start=1647057873959 source_hash="85ad5d6b" tags=[]
cases_result, logs = run(cases)

/ + cell_id="ea5cfd89-5fb9-4e0c-9da6-adb5adabfd40" deepnote_cell_height=630 deepnote_cell_type="code" deepnote_table_invalid=false deepnote_table_loading=false deepnote_table_state={"filters": [], "pageIndex": 0, "pageSize": 10, "sortBy": [{"id": "Best Fitness", "type": "desc"}]} deepnote_to_be_reexecuted=false execution_millis=49 execution_start=1647057896947 source_hash="33d2a840" tags=[]
cases_result[cases_result["Best Fitness"] > 0]

/ + cell_id="ae670724-05b2-4cd3-8208-62bf1dbbf07f" deepnote_cell_height=595 deepnote_cell_type="code" deepnote_output_heights=[498] deepnote_to_be_reexecuted=false execution_millis=277 execution_start=1647057859953 source_hash="fd0f0255" tags=[]
plot_evolution(logs[1][1])

/ + cell_id="eeb4c823-529e-4bc7-b5fe-9f1e1921895f" deepnote_cell_height=533 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=228 execution_start=1647057915945 source_hash="35bb54df" tags=[]
PRODUCTS.iloc[[655, 693, 593, 207, 297, 427, 337, 27], :]

/ + cell_id="846f0b16-e5f3-4bde-a5b7-315008674043" deepnote_cell_height=81 deepnote_cell_type="code" deepnote_to_be_reexecuted=false execution_millis=12 execution_start=1647057693503 source_hash="b623e53d" tags=[]


/ + [markdown] created_in_deepnote_cell=true deepnote_cell_type="markdown" tags=[]
/ <a style='text-decoration:none;line-height:16px;display:flex;color:#5B5B62;padding:10px;justify-content:end;' href='https://deepnote.com?utm_source=created-in-deepnote-cell&projectId=07e29549-6cbf-4e88-b69c-0fc48f2d6023' target="_blank">
/ <img alt='Created in deepnote.com' style='display:inline;max-height:16px;margin:0px;margin-right:7.5px;' src='data:image/svg+xml;base64,<KEY> > </img>
/ Created in <span style='font-weight:600;margin-left:4px;'>Deepnote</span></a>

StarcoderdataJupyterScriptsDedupFiltered