<jupyter_start><jupyter_text>PyCMA<jupyter_code>%matplotlib inline

import cma
import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
sns.set_context("talk")
plt.rcParams['figure.figsize'] = 20,10
init_lower_bound = -10.
init_higher_bound = 10.

NUM_RUNS = 1000
DIMS = (2, 3, 4, 5, 6)
F_TARGET = 1e-30

fitness = cma.ff.sphere
fitness_name = "Sphere"

fitness = cma.ff.rastrigin
fitness_name = "Rastrigin"

fitness = cma.ff.rosen
fitness_name = "Rosenbrock"
solutions_list = []
run_id = 0
num_dim = None
dim_index_list = []

def callback_function(es):
    global gen_id
    global eval_id
    global num_dim
    
    gen_id += 1
    
    indiv_dict = {
        "gen": gen_id,
        "run": run_id,
        "num_dim": num_dim,
        #"best_x": es.best.x,
        "best_f": es.best.f,
        "best_evals": es.best.evals,
        "sigma": es.sigma,
    }
    
    solutions_list.append(indiv_dict)

for ndim in DIMS:
    for run in range(1, NUM_RUNS):
        run_id = run
        num_dim = ndim
        gen_id = 0
        
        print("{}D run {}".format(ndim, run))

        x0 = np.random.uniform(low=init_lower_bound, high=init_higher_bound, size=num_dim)    # initial solution
        sigma0 = np.random.uniform(0., 1.)                                                    # initial standard deviation

        x_optimal, es = cma.fmin2(fitness, x0, sigma0,
                                  callback=callback_function,
                                  options={'verbose': -9, 'ftarget': F_TARGET, 'maxfevals': 8000})    # See last example of http://cma.gforge.inria.fr/apidocs-pycma/cma.evolution_strategy.html#fmin

df = pd.DataFrame(solutions_list)
ALPHA = 0.2

ax = sns.lineplot(x="gen", y="best_f",
                  estimator=None, units="run", alpha=ALPHA,
                  data=df.loc[df.num_dim == DIMS[0]])

for dim in DIMS[1:]:
    sns.lineplot(x="gen", y="best_f",
                estimator=None, units="run", alpha=ALPHA,
                data=df.loc[df.num_dim == dim],
                ax=ax)

ax.set_yscale("log")

plt.grid()

plt.title("Best fitness ({} runs)".format(NUM_RUNS))

plt.ylabel("Best fitness")
plt.xlabel("Number of generations")

legend_lines = []
legend_str = []
for dim in DIMS:
    legend_lines.append(ax.get_lines()[(dim-1) * (NUM_RUNS-1) - 1])
    legend_str.append("{} {}D".format(fitness_name, dim))
plt.legend(legend_lines, legend_str)

plt.savefig(fitness_name.lower() + ".png");
ax = sns.lineplot(x="gen", y="best_f",
                  #estimator=None, units="run", alpha=0.5,
                  data=df.loc[df.num_dim == DIMS[0]],
                  label="{} {}D".format(fitness_name, DIMS[0]))

for dim in DIMS[1:]:
    sns.lineplot(x="gen", y="best_f",
                 #estimator=None, units="run", alpha=0.5,
                 data=df.loc[df.num_dim == dim],
                 label="{} {}D".format(fitness_name, dim))

ax.set_yscale("log")

plt.grid()

plt.title("Mean of best fitness")

plt.ylabel("Mean of best fitness")
plt.xlabel("Number of generations")

plt.savefig(fitness_name.lower() + "_avg.png");
ax = sns.lineplot(x="gen", y="best_f",
                  estimator=np.median,
                  data=df.loc[df.num_dim == DIMS[0]],
                  label="{} {}D".format(fitness_name, DIMS[0]))

for dim in DIMS[1:]:
    sns.lineplot(x="gen", y="best_f",
                 estimator=np.median,
                 data=df.loc[df.num_dim == dim],
                 label= "{} {}D".format(fitness_name, dim))

ax.set_yscale("log")

plt.grid()

plt.title("Median of best fitness")

plt.ylabel("Median of best fitness")
plt.xlabel("Number of generations")

plt.savefig(fitness_name.lower() + "_med.png");
df.to_csv(fitness_name.lower() + ".csv")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15443912812333865, 'fraction_numerical': 0.014088250930356193, 'mean_word_length': 2.5803996194100858, 'pattern_counts': {'":': 7, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '89687', 'license': 'MIT', 'n_tokens_mistral': 1452, 'n_tokens_neox': 1387, 'n_words': 255, 'path': 'nb_sci_ai/ai_optimization_cmaes_convergence_vs_number_of_dimensions.ipynb', 'repo_name': 'jdhp-docs/python-notebooks', 'size': '3762'}