<jupyter_start><jupyter_text>Find maximal value of a single-parameter function<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
import random
%matplotlib inline
def obj_func(x):
    return - x ** 4 + 2 * x + 3
def update_best(val, x_max_his, x):
    # update val
    val = obj_func(x)
    
    # global max
    maxindex  = np.argmax(val)
    max_x = x[maxindex]
    
    # local max
    for i in range(len(val)):
        if(obj_func(x_max_his[i]) < val[i]):
            x_max_his[i] = x[i]
            
    return max_x, x_max_his, val<jupyter_output><empty_output><jupyter_text>initialization<jupyter_code>num_par = 100
max_x = 50
min_x = -50
x = np.random.uniform(min_x, max_x, size=(num_par))
v = np.zeros(num_par)
x_max_his = np.zeros((num_par))
val = obj_func(x)
w = 0.8
c1 = 2
c2 = 2
max_x, x_max_his, val = update_best(val, x_max_his, x)<jupyter_output><empty_output><jupyter_text>main<jupyter_code>if __name__ == '__main__':
    fittest = []
    for j in range(100):
        for i in range(len(val)):
            v[i] = w * v[i] + c1 * random.random() * (x_max_his[i] - x[i]) + c2 * random.random() * (max_x - x[i])
            x[i] += v[i]
        max_x, x_max_his, val = update_best(val, x_max_his, x)
        # print(x, v)
        # print(np.mean(x))
        fittest.append(obj_func(max_x))
plt.plot(fittest)
plt.plot(x)
np.max(val)
plt.plot(val)
result = [obj_func(x/10) for x in np.arange(-50,50,0.1)]
plt.plot(result)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14769647696476965, 'fraction_numerical': 0.01964769647696477, 'mean_word_length': 3.281159420289855, 'pattern_counts': {'":': 0, '<': 14, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '9633', 'license': 'MIT', 'n_tokens_mistral': 649, 'n_tokens_neox': 625, 'n_words': 126, 'path': 'PSO-function maximum.ipynb', 'repo_name': 'AndyRay1998/Bio-inspired-AI', 'size': '1476'}