Esempio n. 1
0
def SAmethod(max_iter=50):
    T, T_min, q = 100, 1e-250, 0.99
    x0 = np.array(lb) + 0.1
    start_time = datetime.now()
    sa = SA(func=finallFunction,
            lb=lb,
            ub=ub,
            x0=x0,
            L=max_iter,
            T=T,
            T_min=T_min,
            q=q,
            debug=True,
            max_iter=max_iter)  #只求解最小值
    end_time = datetime.now()
    print('Itreation numbers is {}, weight is '.format(max_iter) +
          str(weight) +
          ' using time is {}'.format((end_time - start_time).total_seconds()))
    best_x, best_y = sa.run()
    Y_history = sa.best_y_history
    tm = time.localtime(time.time())
    tm_str = '{}-{}-{} {}:{}:{} '.format(tm[0], tm[1], tm[2], tm[3], tm[4],
                                         tm[5])

    return best_x, best_y, Y_history, sa
Esempio n. 2
0
def en(code):
    pop, s1, s2, t_max, t_min, l, stay = code
    sa = SA(func=obj,
            dim=2,
            pop=pop,
            x0=[s1, s2],
            T_max=10**t_max,
            T_min=10**t_min,
            L=l,
            max_stay_counter=stay)
    best_x, best_y = sa.run()
    return best_y
Esempio n. 3
0
def SAmethod(max_iter=300, L=50, T=100, T_min=1e-5, q=0.95):
    lb = lb
    ub = ub
    x0 = np.random.random(
        size=np.array(lb).shape) * (np.array(ub) - np.array(lb)) + np.array(lb)
    sa = SA(func=calculEffFunc,
            lb=lb,
            ub=ub,
            x0=x0,
            L=L,
            T=T,
            T_min=T_min,
            quench=q,
            debug=True,
            max_iter=max_iter)  #slove lowest

    best_x, best_y = sa.run()
    Y_history = sa.best_y_history  # each temperature best solutions
    return best_x, best_y, Y_history, Y_history
Esempio n. 4
0
          c2=0.5)
pso.run()
print('\n带约束的粒子群算法\n')
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
# plt.plot(pso.gbest_y_hist)
# plt.show()
pso = PSO(func=func3, dim=3)
pso.run()
print('\n不带约束的粒子群算法\n')
print('best_x is ', pso.gbest_x, 'best_y is', pso.gbest_y)
'''
模拟退火算法
'''
sa = SA(func=func3,
        x0=[1, 1, 1],
        T_max=1,
        T_min=1e-9,
        L=300,
        max_stay_counter=150)
best_x, best_y = sa.run()
print('\n模拟退火算法用于多元函数优化\n')
print('best_x:', best_x, 'best_y', best_y)
# plt.plot(pd.DataFrame(sa.best_y_history).cummin(axis=0))
# plt.show()
sa_tsp = SA_TSP(func=getTotalDistance,
                x0=range(NUM_POINT),
                T_max=100,
                T_min=1,
                L=10 * NUM_POINT)
best_points, best_distance = sa_tsp.run()
print('\n模拟退火算法解决TSP问题(旅行商问题)\n')
print(best_points, '\nBest Distance:', best_distance)
Esempio n. 5
0
from sko.SA import SA

demo_func = lambda x: x[0]**2 + (x[1] - 0.05)**2 + x[2]**2
sa = SA(func=demo_func, x0=[1, 1, 1])
x_star, y_star = sa.run()
print(x_star, y_star)

# %% Plot the result
import matplotlib.pyplot as plt
import pandas as pd

plt.plot(pd.DataFrame(sa.f_list).cummin(axis=0))
plt.show()
Esempio n. 6
0
demo_func = lambda x: x[0]**2 + (x[1] - 0.05)**2 + x[2]**2

# %% Do SA
from sko.SA import SA

sa = SA(func=demo_func,
        x0=[1, 1, 1],
        T_max=1,
        T_min=1e-9,
        q=0.99,
        L=300,
        max_stay_counter=150)
best_x, best_y = sa.run()
print('best_x:', best_x, 'best_y', best_y)

# %% Plot the result
import matplotlib.pyplot as plt
import pandas as pd

plt.plot(pd.DataFrame(sa.best_y_history).cummin(axis=0))
plt.show()
Esempio n. 7
0
def seir_model(N, Initial_data, data, name):
    '''
    This function will return fitting and prediction number of COVID-19

    :param
        Input: N --> The total number of people that is affected by the virus
               Initial_data --> data of first day we are gonna to model, in the form of [suspected people, exposed people, infected people, recovered people]
               data --> Number of infected people data extractd from formal resource
               name --> the filename want to store the data in
        Output : data is written to txt file and stored as well.
    '''
    assert isinstance(Initial_data, list) and all(isinstance(i, int) for int in Initial_data) len(Initial_data) = 4 
    assert isinstance(data, list) and all(isinstance(i, int) for int in data)
    length = len(data)

    def demo_func(x):
        '''
        This function is for choosing parameter.
        :param
            Input: x --> parameters that we need to choose
            Output: least square error is the evaluator for parameter
        '''

        beta,beta2,alpha = x
        #Infection rate, Infection rate during Incubation, Latency conversion rate
        nums = Initial_data
        predicted_data = []
        x = np.array(x).T
        least_square_error = 0

        # latency conversion rate can not be larget than 1
        # infection rate should be larget than Infection rate during Incubation

        # parameter restriction
        if(alpha < 0):
            return float('inf')
        if(beta < beta2):
            return float('inf')
        if(beta2 < 0):
            return float('inf')

        for i in range(length):
            # use 4 functions to iterate in SEIR model
            temp = np.array([[1, -beta2 / N * nums[0], -beta / N * nums[0], 0],
                            [beta / N * nums[2], 1 - alpha, 0, 0],
                            [0, alpha, 1, 0],
                            [0, 0, 0,1 ]])
            nums = temp.dot(nums)
            predicted_data.append(nums[2])
            least_square_error += (predicted_data[i] - data[i]) ** 2

        return least_square_error 

    # calculate parameters using Simulated annealing
    sa = SA(func = demo_func, x0 = [3,0,0])
    x_star, y_star = sa.run()
    np.savetxt('qianqi_canshu.txt', [x_star], delimiter = ',')

    # pass parameters to SEIR model
    beta,beta2,alpha = x_star
    predicted_days = 200
    nums = Initial_data
    predicted_data= []
    recovered = []
    x = np.array(x).T

    least_square_error =0
    for i in range(predicted_days):
        # use 4 functions to iterate in SEIR model
        temp = np.array([[1, -beta2 / N * nums[0], -beta / N * nums[0], 0],
                            [beta / N * nums[2], 1 - alpha, 0, 0],
                            [0, alpha, 1, 0],
                            [0, 0, 0,1 ]])
        nums = temp.dot(nums)
        recovered.append(nums[3])
        predicted_data.append(nums[2])
        recovered_data.append(nums[3])

    np.savetxt(name + '_infected.txt', predicted_data, delimiter=',')
    np.savetxt(name + '_recovered.txt', recovered_data, delimiter=',')