diff --git a/Pyrimidine(article).md b/Pyrimidine(article).md index 0eaff9b..173ea83 100644 --- a/Pyrimidine(article).md +++ b/Pyrimidine(article).md @@ -102,7 +102,7 @@ class MyPopulation(SGAPopulation): default_size = 20 pop = MyPopulation.random(size=n) # Size: length of the chromosome -pop.evolve(n_iter=100) +pop.evolve(max_iter=100) ``` Finally, the optimal individual can be found using `pop.best_individual` as the solution. Setting `verbose=True` prints the iteration process. The equivalent expression is as follows: @@ -121,7 +121,7 @@ To assess the algorithm's performance, it is common to plot fitness curves or ot ```python stat = {'Mean Fitness': 'mean_fitness', 'Best Fitness': 'best_fitness'} -data = pop.history(stat=stat, n_iter=100) +data = pop.history(stat=stat, max_iter=100) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) diff --git a/docs/build/html/Customization.html b/docs/build/html/Customization.html index b59aef0..6bfa27c 100644 --- a/docs/build/html/Customization.html +++ b/docs/build/html/Customization.html @@ -228,7 +228,7 @@

Evolutionary Strategyind = MyIndividual.random() stat = {'Fitness':'_fitness'} -data = ind.evolve(stat=stat, n_iter=100, history=True) +data = ind.evolve(stat=stat, max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/docs/build/html/Examples.html b/docs/build/html/Examples.html index 14add0c..e526058 100644 --- a/docs/build/html/Examples.html +++ b/docs/build/html/Examples.html @@ -98,7 +98,7 @@

Codes } # Do statistical task and print the results through the evoluation -data = pop.evolve(stat=stat, n_iter=100, history=True, verbose=True) +data = pop.evolve(stat=stat, max_iter=100, history=True, verbose=True) # Print the solution(the best individual in the population) print(pop.best_individual) # or print(pop.solution) @@ -169,7 +169,7 @@

Another Problem 'Best Fitness':'max_fitness'} by default; need not set `stat` explicitly. """ - data = pop.evolve(n_iter=100, history=True) + data = pop.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt fig = plt.figure() @@ -272,10 +272,10 @@

Comparison of Algorithms_Population = StandardPopulation[_Individual] pop = MyPopulation.random(n_individuals=20, sizes=[8]*ndim+[8]) cpy = pop.copy(type_=_Population) -d = cpy.evolve(stat=stat, n_iter=100, history=True) +d = cpy.evolve(stat=stat, max_iter=100, history=True) ax.plot(d.index, d['Mean Fitness'], d.index, d['Best Fitness'], '.-') -d = pop.history(n_iter=100, stat=stat, history=True) +d = pop.history(max_iter=100, stat=stat, history=True) ax.plot(d.index, d['Mean Fitness'], d.index, d['Best Fitness'], '.-') ax.legend(('Traditional mean','Traditional best', 'New mean', 'New best')) plt.show() @@ -337,7 +337,7 @@

Example 3 — Evolution Strategyind = MyPopulation.random() -data = ind.evolve(n_iter=100, history=True) +data = ind.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt @@ -426,8 +426,8 @@

Visualization and comparisonmypop = MyPopulation.random() yourpop = YourPopulation([YourIndividual(i.decode()) for i in mypop]) -mydata = mypop.evolve(n_iter=100, stat=stat, history=True) -yourdata = yourpop.evolve(n_iter=100, stat=stat, history=True) +mydata = mypop.evolve(max_iter=100, stat=stat, history=True) +yourdata = yourpop.evolve(max_iter=100, stat=stat, history=True) import matplotlib.pyplot as plt fig = plt.figure() @@ -475,7 +475,7 @@

Example 5 — MultiPopulationmp = _MultiPopulation.random() -data = mp.evolve(n_iter=100, history=True) +data = mp.evolve(max_iter=100, history=True)

Equivalently

@@ -499,7 +499,7 @@

Example 5 — MultiPopulation# _MultiPopulation = MultiPopulation[HOFPopulation[BinaryChromosome // n_bags] // 10].set_fitness(_evaluate) // 2 mp = _MultiPopulation.random() -data = mp.evolve(n_iter=100, history=True) +data = mp.evolve(max_iter=100, history=True)

Plot the fitness curves as usual.

@@ -562,7 +562,7 @@

Hybrid-populationsp = _HybridPopulation.random() -data = sp.evolve(n_iter=100, history=True) +data = sp.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/docs/build/html/Helpers.html b/docs/build/html/Helpers.html index 4f2cb8e..44cf755 100644 --- a/docs/build/html/Helpers.html +++ b/docs/build/html/Helpers.html @@ -145,8 +145,8 @@

Memorymypop = MyPopulation.random() yourpop = mypop.clone(type_=YourPopulation) -mydata = mypop.evolve(n_iter=200, stat=stat, history=True) -yourdata = yourpop.evolve(n_iter=200, stat=stat, history=True) +mydata = mypop.evolve(max_iter=200, stat=stat, history=True) +yourdata = yourpop.evolve(max_iter=200, stat=stat, history=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/docs/build/html/pyrimidine.html b/docs/build/html/pyrimidine.html index 116442b..d3bf056 100644 --- a/docs/build/html/pyrimidine.html +++ b/docs/build/html/pyrimidine.html @@ -306,7 +306,7 @@

Submodules
-params = {'frequency': 0.5, 'loudness': 0, 'n_iter': 100, 'pulse_rate': 0, 'scale': 0.1}
+params = {'frequency': 0.5, 'loudness': 0, 'max_iter': 100, 'pulse_rate': 0, 'scale': 0.1}
@@ -367,7 +367,7 @@

Submodules
-params = {'alpha': 0.95, 'gamma': 0.5, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'pulse_rate': 0.9, 'scaling': 0.2, 'tourn_size': 5}
+params = {'alpha': 0.95, 'gamma': 0.5, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'pulse_rate': 0.9, 'scaling': 0.2, 'tourn_size': 5}

@@ -518,7 +518,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -583,7 +583,7 @@

Submodules
-params = {'migrate_prob': 0.75, 'n_iter': 100}
+params = {'migrate_prob': 0.75, 'max_iter': 100}

@@ -641,7 +641,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -763,7 +763,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -887,7 +887,7 @@

Submodules
-params = {'migrate_prob': 0.75, 'n_iter': 100}
+params = {'migrate_prob': 0.75, 'max_iter': 100}

@@ -1022,7 +1022,7 @@

Submodules
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -1117,7 +1117,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1154,7 +1154,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1196,7 +1196,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1218,7 +1218,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1245,7 +1245,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1271,7 +1271,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1320,7 +1320,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1359,7 +1359,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1391,7 +1391,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1521,7 +1521,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1591,7 +1591,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1617,7 +1617,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1677,7 +1677,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1720,7 +1720,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1741,7 +1741,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1778,7 +1778,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1799,7 +1799,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1865,7 +1865,7 @@

Submodules
-params = {'cross_prob': 0.75, 'factor': 0.05, 'n_iter': 100}
+params = {'cross_prob': 0.75, 'factor': 0.05, 'max_iter': 100}
@@ -1930,7 +1930,7 @@

Submodules
-params = {'cross_prob': 0.75, 'factor': 0.5, 'n_iter': 100}
+params = {'cross_prob': 0.75, 'factor': 0.5, 'max_iter': 100}

@@ -2190,7 +2190,7 @@

pyrimidine.aco module
-params = {'alpha': 1, 'beta': 5, 'n_iter': 100, 'n_steps': 1, 'sedimentation': 100, 'volatilization': 0.75}
+params = {'alpha': 1, 'beta': 5, 'max_iter': 100, 'n_steps': 1, 'sedimentation': 100, 'volatilization': 0.75}

@@ -2296,7 +2296,7 @@

pyrimidine.aco module
-params = {'c': 0.1, 'epsilon': 0.0001, 'n_iter': 100}
+params = {'c': 0.1, 'epsilon': 0.0001, 'max_iter': 100}

@@ -2401,7 +2401,7 @@

pyrimidine.aco module
-params = {'lambda_': 20, 'mate_prob': 0.75, 'mu': 10, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'lambda_': 20, 'mate_prob': 0.75, 'mu': 10, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -2714,7 +2714,7 @@

pyrimidine.aco module
-params = {'accelerate': 0, 'n_iter': 100}
+params = {'accelerate': 0, 'max_iter': 100}

@@ -2781,7 +2781,7 @@

pyrimidine.aco module
-params = {'age': 0, 'life_span': 100, 'n_iter': 100}
+params = {'age': 0, 'life_span': 100, 'max_iter': 100}

@@ -2832,7 +2832,7 @@

pyrimidine.aco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -2902,7 +2902,7 @@

pyrimidine.aco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -2977,7 +2977,7 @@

pyrimidine.aco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -3042,7 +3042,7 @@

pyrimidine.aco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -3130,7 +3130,7 @@

pyrimidine.aco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -3433,7 +3433,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'migrate_prob': 0.75, 'n_elders': 0.5, 'n_iter': 100}
+params = {'mate_prob': 0.75, 'migrate_prob': 0.75, 'n_elders': 0.5, 'max_iter': 100}

@@ -3503,7 +3503,7 @@

pyrimidine.multipopulation module
-params = {'migrate_prob': 0.75, 'n_iter': 100}
+params = {'migrate_prob': 0.75, 'max_iter': 100}

@@ -3559,7 +3559,7 @@

pyrimidine.multipopulation module
-params = {'migrate_prob': 0.75, 'n_iter': 100}
+params = {'migrate_prob': 0.75, 'max_iter': 100}

@@ -3717,7 +3717,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -3780,7 +3780,7 @@

pyrimidine.multipopulation module
-params = {'dual_prob': 0.2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.3, 'n_iter': 100, 'tourn_size': 5}
+params = {'dual_prob': 0.2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.3, 'max_iter': 100, 'tourn_size': 5}

@@ -3837,7 +3837,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -3911,7 +3911,7 @@

pyrimidine.multipopulation module
-params = {'hof_size': 2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'hof_size': 2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -3988,7 +3988,7 @@

pyrimidine.multipopulation module
-params = {'hof_size': 2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'hof_size': 2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -4049,7 +4049,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'n_iter': 100, 'n_local_iter': 2, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'max_iter': 100, 'n_local_iter': 2, 'tourn_size': 5}

@@ -4107,7 +4107,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'mutate_prob_lb': 0.1, 'mutate_prob_ub': 0.5, 'n_elders': 0.5, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'mutate_prob_lb': 0.1, 'mutate_prob_ub': 0.5, 'n_elders': 0.5, 'max_iter': 100, 'tourn_size': 5}

@@ -4166,7 +4166,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'max_iter': 100, 'tourn_size': 5}

@@ -4318,7 +4318,7 @@

pyrimidine.multipopulation module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -4397,7 +4397,7 @@

pyrimidine.multipopulation module
-params = {'acceleration_coefficient': 3, 'hof_size': 0.2, 'inertia': 0.75, 'learning_factor': 2, 'max_velocity': None, 'n_iter': 100}
+params = {'acceleration_coefficient': 3, 'hof_size': 0.2, 'inertia': 0.75, 'learning_factor': 2, 'max_velocity': None, 'max_iter': 100}

@@ -4461,7 +4461,7 @@

pyrimidine.multipopulation module
-params = {'acceleration_coefficient': 3, 'inertia': 0.5, 'learning_factor': 2, 'n_iter': 100}
+params = {'acceleration_coefficient': 3, 'inertia': 0.5, 'learning_factor': 2, 'max_iter': 100}

@@ -4565,7 +4565,7 @@

pyrimidine.multipopulation module
-params = {'acceleration_coefficient': 3, 'hof_size': 0.2, 'inertia': 0.75, 'learning_factor': 2, 'max_velocity': None, 'n_iter': 100}
+params = {'acceleration_coefficient': 3, 'hof_size': 0.2, 'inertia': 0.75, 'learning_factor': 2, 'max_velocity': None, 'max_iter': 100}

@@ -4646,7 +4646,7 @@

pyrimidine.multipopulation module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -4692,7 +4692,7 @@

pyrimidine.multipopulation module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -4770,7 +4770,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'max_iter': 100, 'tourn_size': 5}

@@ -4867,7 +4867,7 @@

pyrimidine.multipopulation module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

diff --git a/docs/build/html/pyrimidine.local_search.html b/docs/build/html/pyrimidine.local_search.html index 4741b57..6299bdd 100644 --- a/docs/build/html/pyrimidine.local_search.html +++ b/docs/build/html/pyrimidine.local_search.html @@ -129,7 +129,7 @@

Submodules
-params = {'ext_c': 0.99, 'initT': 100, 'int_c': 0.99, 'n_epochs': 200, 'n_iter': 100, 'termT': 0.0001}
+params = {'ext_c': 0.99, 'initT': 100, 'int_c': 0.99, 'n_epochs': 200, 'max_iter': 100, 'termT': 0.0001}

@@ -231,7 +231,7 @@

Submodules
-params = {'actions': [], 'n_iter': 100, 'tabu_list': [], 'tabu_size': 10, 'value': 0}
+params = {'actions': [], 'max_iter': 100, 'tabu_list': [], 'tabu_size': 10, 'value': 0}

@@ -310,7 +310,7 @@

Submodules
-params = {'actions': [], 'n_iter': 100, 'tabu_list': [], 'tabu_size': 10, 'value': 0}
+params = {'actions': [], 'max_iter': 100, 'tabu_list': [], 'tabu_size': 10, 'value': 0}

diff --git a/docs/build/source/Customization.html b/docs/build/source/Customization.html index c3d7280..2c6aa28 100644 --- a/docs/build/source/Customization.html +++ b/docs/build/source/Customization.html @@ -235,7 +235,7 @@

Simulated Annealing Algorithmind = MyIndividual.random() stat = {'Fitness':'_fitness'} -data = ind.evolve(stat=stat, n_iter=100, history=True) +data = ind.evolve(stat=stat, max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/docs/build/source/Examples.html b/docs/build/source/Examples.html index cc12659..6e723d4 100644 --- a/docs/build/source/Examples.html +++ b/docs/build/source/Examples.html @@ -106,7 +106,7 @@

Codes } # Do statistical task and print the results through the evoluation -data = pop.evolve(stat=stat, n_iter=100, history=True, verbose=True) +data = pop.evolve(stat=stat, max_iter=100, history=True, verbose=True) # Print the solution(the best individual in the population) print(pop.best_individual) # or print(pop.solution) @@ -177,7 +177,7 @@

Another Problem 'Best Fitness':'max_fitness'} by default; need not set `stat` explicitly. """ - data = pop.evolve(n_iter=100, history=True) + data = pop.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt fig = plt.figure() @@ -280,10 +280,10 @@

Comparison of Algorithms_Population = StandardPopulation[_Individual] pop = MyPopulation.random(n_individuals=20, sizes=[8]*ndim+[8]) cpy = pop.copy(type_=_Population) -d = cpy.evolve(stat=stat, n_iter=100, history=True) +d = cpy.evolve(stat=stat, max_iter=100, history=True) ax.plot(d.index, d['Mean Fitness'], d.index, d['Best Fitness'], '.-') -d = pop.history(n_iter=100, stat=stat, history=True) +d = pop.history(max_iter=100, stat=stat, history=True) ax.plot(d.index, d['Mean Fitness'], d.index, d['Best Fitness'], '.-') ax.legend(('Traditional mean','Traditional best', 'New mean', 'New best')) plt.show() @@ -345,7 +345,7 @@

Example 3 — Evolution Strategyind = MyPopulation.random() -data = ind.evolve(n_iter=100, history=True) +data = ind.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt @@ -434,8 +434,8 @@

Visualization and comparisonmypop = MyPopulation.random() yourpop = YourPopulation([YourIndividual(i.decode()) for i in mypop]) -mydata = mypop.evolve(n_iter=100, stat=stat, history=True) -yourdata = yourpop.evolve(n_iter=100, stat=stat, history=True) +mydata = mypop.evolve(max_iter=100, stat=stat, history=True) +yourdata = yourpop.evolve(max_iter=100, stat=stat, history=True) import matplotlib.pyplot as plt fig = plt.figure() @@ -483,7 +483,7 @@

Example 5 — MultiPopulationmp = _MultiPopulation.random() -data = mp.evolve(n_iter=100, history=True) +data = mp.evolve(max_iter=100, history=True)

Equivalently

@@ -507,7 +507,7 @@

Example 5 — MultiPopulation# _MultiPopulation = MultiPopulation[HOFPopulation[BinaryChromosome // n_bags] // 10].set_fitness(_evaluate) // 2 mp = _MultiPopulation.random() -data = mp.evolve(n_iter=100, history=True) +data = mp.evolve(max_iter=100, history=True)

Plot the fitness curves as usual.

@@ -570,7 +570,7 @@

Hybrid-populationsp = _HybridPopulation.random() -data = sp.evolve(n_iter=100, history=True) +data = sp.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/docs/build/source/Helpers.html b/docs/build/source/Helpers.html index d4f73fc..c02dc36 100644 --- a/docs/build/source/Helpers.html +++ b/docs/build/source/Helpers.html @@ -154,8 +154,8 @@

Memorymypop = MyPopulation.random() yourpop = mypop.clone(type_=YourPopulation) -mydata = mypop.evolve(n_iter=200, stat=stat, history=True) -yourdata = yourpop.evolve(n_iter=200, stat=stat, history=True) +mydata = mypop.evolve(max_iter=200, stat=stat, history=True) +yourdata = yourpop.evolve(max_iter=200, stat=stat, history=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/docs/build/source/pyrimidine.html b/docs/build/source/pyrimidine.html index 94cd4e2..cad2988 100644 --- a/docs/build/source/pyrimidine.html +++ b/docs/build/source/pyrimidine.html @@ -307,7 +307,7 @@

Submodules
-params = {'frequency': 0.5, 'loudness': 0, 'n_iter': 100, 'pulse_rate': 0, 'scale': 0.1}
+params = {'frequency': 0.5, 'loudness': 0, 'max_iter': 100, 'pulse_rate': 0, 'scale': 0.1}

@@ -368,7 +368,7 @@

Submodules
-params = {'alpha': 0.95, 'gamma': 0.5, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'pulse_rate': 0.9, 'scaling': 0.2, 'tourn_size': 5}
+params = {'alpha': 0.95, 'gamma': 0.5, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'pulse_rate': 0.9, 'scaling': 0.2, 'tourn_size': 5}

@@ -519,7 +519,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -584,7 +584,7 @@

Submodules
-params = {'migrate_prob': 0.75, 'n_iter': 100}
+params = {'migrate_prob': 0.75, 'max_iter': 100}

@@ -642,7 +642,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -764,7 +764,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -888,7 +888,7 @@

Submodules
-params = {'migrate_prob': 0.75, 'n_iter': 100}
+params = {'migrate_prob': 0.75, 'max_iter': 100}

@@ -1023,7 +1023,7 @@

Submodules
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -1115,7 +1115,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1152,7 +1152,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1194,7 +1194,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1216,7 +1216,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1243,7 +1243,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1269,7 +1269,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1318,7 +1318,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1357,7 +1357,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1389,7 +1389,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1519,7 +1519,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1589,7 +1589,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1615,7 +1615,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1675,7 +1675,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1718,7 +1718,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1739,7 +1739,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1776,7 +1776,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}
@@ -1797,7 +1797,7 @@

Submodules
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -1863,7 +1863,7 @@

Submodules
-params = {'cross_prob': 0.75, 'factor': 0.05, 'n_iter': 100}
+params = {'cross_prob': 0.75, 'factor': 0.05, 'max_iter': 100}
@@ -1928,7 +1928,7 @@

Submodules
-params = {'cross_prob': 0.75, 'factor': 0.5, 'n_iter': 100}
+params = {'cross_prob': 0.75, 'factor': 0.5, 'max_iter': 100}

@@ -2144,7 +2144,7 @@

pyrimidine.deco module
-params = {'c': 0.1, 'epsilon': 0.0001, 'n_iter': 100}
+params = {'c': 0.1, 'epsilon': 0.0001, 'max_iter': 100}

@@ -2247,7 +2247,7 @@

pyrimidine.deco module
-params = {'lambda_': 20, 'mate_prob': 0.75, 'mu': 10, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'lambda_': 20, 'mate_prob': 0.75, 'mu': 10, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -2555,7 +2555,7 @@

pyrimidine.deco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -2620,7 +2620,7 @@

pyrimidine.deco module
-params = {'age': 0, 'life_span': 100, 'n_iter': 100}
+params = {'age': 0, 'life_span': 100, 'max_iter': 100}

@@ -2671,7 +2671,7 @@

pyrimidine.deco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -2741,7 +2741,7 @@

pyrimidine.deco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -2816,7 +2816,7 @@

pyrimidine.deco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -2881,7 +2881,7 @@

pyrimidine.deco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -2969,7 +2969,7 @@

pyrimidine.deco module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -3269,7 +3269,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'migrate_prob': 0.75, 'n_elders': 0.5, 'n_iter': 100}
+params = {'mate_prob': 0.75, 'migrate_prob': 0.75, 'n_elders': 0.5, 'max_iter': 100}

@@ -3339,7 +3339,7 @@

pyrimidine.multipopulation module
-params = {'migrate_prob': 0.75, 'n_iter': 100}
+params = {'migrate_prob': 0.75, 'max_iter': 100}

@@ -3395,7 +3395,7 @@

pyrimidine.multipopulation module
-params = {'migrate_prob': 0.75, 'n_iter': 100}
+params = {'migrate_prob': 0.75, 'max_iter': 100}

@@ -3527,7 +3527,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -3590,7 +3590,7 @@

pyrimidine.multipopulation module
-params = {'dual_prob': 0.2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.3, 'n_iter': 100, 'tourn_size': 5}
+params = {'dual_prob': 0.2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.3, 'max_iter': 100, 'tourn_size': 5}

@@ -3647,7 +3647,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -3721,7 +3721,7 @@

pyrimidine.multipopulation module
-params = {'hof_size': 2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'hof_size': 2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -3798,7 +3798,7 @@

pyrimidine.multipopulation module
-params = {'hof_size': 2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_iter': 100, 'tourn_size': 5}
+params = {'hof_size': 2, 'mate_prob': 0.75, 'mutate_prob': 0.2, 'max_iter': 100, 'tourn_size': 5}

@@ -3859,7 +3859,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'n_iter': 100, 'n_local_iter': 2, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'max_iter': 100, 'n_local_iter': 2, 'tourn_size': 5}

@@ -3917,7 +3917,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'mutate_prob_lb': 0.1, 'mutate_prob_ub': 0.5, 'n_elders': 0.5, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'mutate_prob_lb': 0.1, 'mutate_prob_ub': 0.5, 'n_elders': 0.5, 'max_iter': 100, 'tourn_size': 5}

@@ -3976,7 +3976,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'max_iter': 100, 'tourn_size': 5}

@@ -4128,7 +4128,7 @@

pyrimidine.multipopulation module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -4207,7 +4207,7 @@

pyrimidine.multipopulation module
-params = {'acceleration_coefficient': 3, 'hof_size': 0.2, 'inertia': 0.75, 'learning_factor': 2, 'max_velocity': None, 'n_iter': 100}
+params = {'acceleration_coefficient': 3, 'hof_size': 0.2, 'inertia': 0.75, 'learning_factor': 2, 'max_velocity': None, 'max_iter': 100}

@@ -4271,7 +4271,7 @@

pyrimidine.multipopulation module
-params = {'acceleration_coefficient': 3, 'inertia': 0.5, 'learning_factor': 2, 'n_iter': 100}
+params = {'acceleration_coefficient': 3, 'inertia': 0.5, 'learning_factor': 2, 'max_iter': 100}

@@ -4375,7 +4375,7 @@

pyrimidine.multipopulation module
-params = {'acceleration_coefficient': 3, 'hof_size': 0.2, 'inertia': 0.75, 'learning_factor': 2, 'max_velocity': None, 'n_iter': 100}
+params = {'acceleration_coefficient': 3, 'hof_size': 0.2, 'inertia': 0.75, 'learning_factor': 2, 'max_velocity': None, 'max_iter': 100}

@@ -4456,7 +4456,7 @@

pyrimidine.multipopulation module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -4502,7 +4502,7 @@

pyrimidine.multipopulation module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

@@ -4580,7 +4580,7 @@

pyrimidine.multipopulation module
-params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'n_iter': 100, 'tourn_size': 5}
+params = {'mate_prob': 0.75, 'mutate_prob': 0.2, 'n_elders': 0.5, 'max_iter': 100, 'tourn_size': 5}

@@ -4677,7 +4677,7 @@

pyrimidine.multipopulation module
-params = {'n_iter': 100}
+params = {'max_iter': 100}

diff --git a/docs/build/source/pyrimidine.local_search.html b/docs/build/source/pyrimidine.local_search.html index 7fbbb55..7434e91 100644 --- a/docs/build/source/pyrimidine.local_search.html +++ b/docs/build/source/pyrimidine.local_search.html @@ -129,7 +129,7 @@

Submodules
-params = {'ext_c': 0.99, 'initT': 100, 'int_c': 0.99, 'n_epochs': 200, 'n_iter': 100, 'termT': 0.0001}
+params = {'ext_c': 0.99, 'initT': 100, 'int_c': 0.99, 'n_epochs': 200, 'max_iter': 100, 'termT': 0.0001}

@@ -227,7 +227,7 @@

Submodules
-params = {'actions': [], 'n_iter': 100, 'tabu_list': [], 'tabu_size': 10, 'value': 0}
+params = {'actions': [], 'max_iter': 100, 'tabu_list': [], 'tabu_size': 10, 'value': 0}

@@ -306,7 +306,7 @@

Submodules
-params = {'actions': [], 'n_iter': 100, 'tabu_list': [], 'tabu_size': 10, 'value': 0}
+params = {'actions': [], 'max_iter': 100, 'tabu_list': [], 'tabu_size': 10, 'value': 0}

diff --git a/docs/source/Customization.md b/docs/source/Customization.md index c0f3f2f..128a5a5 100644 --- a/docs/source/Customization.md +++ b/docs/source/Customization.md @@ -200,7 +200,7 @@ class MyIndividual(SimulatedAnnealing, MonoIndividual): ind = MyIndividual.random() stat = {'Fitness':'_fitness'} -data = ind.evolve(stat=stat, n_iter=100, history=True) +data = ind.evolve(stat=stat, max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/docs/source/Examples.md b/docs/source/Examples.md index 81bc58e..eb39be2 100644 --- a/docs/source/Examples.md +++ b/docs/source/Examples.md @@ -57,7 +57,7 @@ stat = { } # Do statistical task and print the results through the evoluation -data = pop.evolve(stat=stat, n_iter=100, history=True, verbose=True) +data = pop.evolve(stat=stat, max_iter=100, history=True, verbose=True) # Print the solution(the best individual in the population) print(pop.best_individual) # or print(pop.solution) @@ -131,7 +131,7 @@ if __name__ == '__main__': 'Best Fitness':'max_fitness'} by default; need not set `stat` explicitly. """ - data = pop.evolve(n_iter=100, history=True) + data = pop.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt fig = plt.figure() @@ -240,10 +240,10 @@ ax = fig.add_subplot(111) _Population = StandardPopulation[_Individual] pop = MyPopulation.random(n_individuals=20, sizes=[8]*ndim+[8]) cpy = pop.copy(type_=_Population) -d = cpy.evolve(stat=stat, n_iter=100, history=True) +d = cpy.evolve(stat=stat, max_iter=100, history=True) ax.plot(d.index, d['Mean Fitness'], d.index, d['Best Fitness'], '.-') -d = pop.history(n_iter=100, stat=stat, history=True) +d = pop.history(max_iter=100, stat=stat, history=True) ax.plot(d.index, d['Mean Fitness'], d.index, d['Best Fitness'], '.-') ax.legend(('Traditional mean','Traditional best', 'New mean', 'New best')) plt.show() @@ -306,7 +306,7 @@ MyPopulation = EvolutionStrategy[FloatChromosome // n].set_fitness(f) ind = MyPopulation.random() -data = ind.evolve(n_iter=100, history=True) +data = ind.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt @@ -395,8 +395,8 @@ stat={'Mean Fitness': 'mean_fitness', 'Best Fitness': 'max_fitness'} mypop = MyPopulation.random() yourpop = YourPopulation([YourIndividual(i.decode()) for i in mypop]) -mydata = mypop.evolve(n_iter=100, stat=stat, history=True) -yourdata = yourpop.evolve(n_iter=100, stat=stat, history=True) +mydata = mypop.evolve(max_iter=100, stat=stat, history=True) +yourdata = yourpop.evolve(max_iter=100, stat=stat, history=True) import matplotlib.pyplot as plt fig = plt.figure() @@ -445,7 +445,7 @@ class _MultiPopulation(MultiPopulation): mp = _MultiPopulation.random() -data = mp.evolve(n_iter=100, history=True) +data = mp.evolve(max_iter=100, history=True) ``` Equivalently @@ -471,7 +471,7 @@ _MultiPopulation = MultiPopulation[_Population] // 2 # _MultiPopulation = MultiPopulation[HOFPopulation[BinaryChromosome // n_bags] // 10].set_fitness(_evaluate) // 2 mp = _MultiPopulation.random() -data = mp.evolve(n_iter=100, history=True) +data = mp.evolve(max_iter=100, history=True) ``` Plot the fitness curves as usual. @@ -539,7 +539,7 @@ class _HybridPopulation(HybridPopulation[_Population, _Population, _Individual, sp = _HybridPopulation.random() -data = sp.evolve(n_iter=100, history=True) +data = sp.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/docs/source/Helpers.md b/docs/source/Helpers.md index 04947ee..ef8bd11 100644 --- a/docs/source/Helpers.md +++ b/docs/source/Helpers.md @@ -112,8 +112,8 @@ stat = {'Mean Fitness': 'mean_fitness', 'Best Fitness': 'best_fitness'} mypop = MyPopulation.random() yourpop = mypop.clone(type_=YourPopulation) -mydata = mypop.evolve(n_iter=200, stat=stat, history=True) -yourdata = yourpop.evolve(n_iter=200, stat=stat, history=True) +mydata = mypop.evolve(max_iter=200, stat=stat, history=True) +yourdata = yourpop.evolve(max_iter=200, stat=stat, history=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/docs/source/Release History.md b/docs/source/Release History.md index 1a2d557..35c2fdb 100644 --- a/docs/source/Release History.md +++ b/docs/source/Release History.md @@ -5,6 +5,7 @@ - Add `aco.py` to implement the ant colony optimization (test the observer pattern) - define `get_worst_elements` method for `PopulationMixin` class - correct some code in examples and `IterativeMixin` class. +- The argument `n_iter` is changed to `max_iter` ## v1.5 diff --git a/examples/comparison-ba.py b/examples/comparison-ba.py index 9df1582..60dc742 100755 --- a/examples/comparison-ba.py +++ b/examples/comparison-ba.py @@ -36,11 +36,11 @@ class MyIndividual(_Individual, MixedIndividual): pop1 = MyPopulation.random(size=(30, 30)) pop2 = pop1.copy(type_=YourPopulation) -pop1.ezolve(n_iter=50) +pop1.ezolve(max_iter=50) ind1 = pop1.best_individual y1 = evaluate.fit(*ind1.decode()) -pop2.ezolve(n_iter=50) +pop2.ezolve(max_iter=50) ind2 = pop2.best_individual y2 = evaluate.fit(*ind2.decode()) diff --git a/examples/comparison-de.py b/examples/comparison-de.py index 0067bb5..b99c01b 100755 --- a/examples/comparison-de.py +++ b/examples/comparison-de.py @@ -29,8 +29,8 @@ class _Population1(DifferentialEvolution, BasePopulation): pop2 = pop1.copy(type_=_Population2) # population 2 with the same initial values to population 1 # stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'max_fitness'} -data1 = pop1.evolve(n_iter=100, history=True) -data2 = pop2.evolve(n_iter=100, history=True) +data1 = pop1.evolve(max_iter=100, history=True) +data2 = pop2.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/examples/comparison-hof.py b/examples/comparison-hof.py index 0c3de52..1d9dee3 100755 --- a/examples/comparison-hof.py +++ b/examples/comparison-hof.py @@ -32,8 +32,8 @@ def transition(self, *args, **kwargs): # pop2 = pop1.copy(type_=_Population2) stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'max_fitness'} -data1 = pop1.evolve(stat=stat, n_iter=50, history=True) -# data2 = pop2.evolve(stat=stat, n_iter=100, history=True) +data1 = pop1.evolve(stat=stat, max_iter=50, history=True) +# data2 = pop2.evolve(stat=stat, max_iter=100, history=True) # import matplotlib.pyplot as plt diff --git a/examples/comparison-modified.py b/examples/comparison-modified.py index a7285c0..9dd868a 100755 --- a/examples/comparison-modified.py +++ b/examples/comparison-modified.py @@ -37,9 +37,9 @@ class YourPopulation(HOFPopulation): pop2 = pop.copy(type_=YourPopulation) stat={'Mean Fitness':'fitness', 'Best Fitness':'best_fitness', 'Standard Deviation of Fitnesses': 'std_fitness'} -data = pop.evolve(stat=stat, n_iter=300, history=True) +data = pop.evolve(stat=stat, max_iter=300, history=True) stat={'Mean Fitness2':'fitness', 'Best Fitness2':'best_fitness', 'Standard Deviation of Fitnesses2': 'std_fitness'} -data2 = pop2.evolve(stat=stat, n_iter=300, history=True) +data2 = pop2.evolve(stat=stat, max_iter=300, history=True) import matplotlib.pyplot as plt diff --git a/examples/comparison-proba.py b/examples/comparison-proba.py index f75d878..61c9403 100755 --- a/examples/comparison-proba.py +++ b/examples/comparison-proba.py @@ -59,8 +59,8 @@ class YourPopulation(_Mixin, HOFPopulation): mypop = MyPopulation.random() for i in mypop: i.measure() yourpop = MyPopulation([YourIndividual(i.measure_result) for i in mypop]) -mydata = mypop.evolve(n_iter=50, history=True) -yourdata = yourpop.evolve(n_iter=50, history=True) +mydata = mypop.evolve(max_iter=50, history=True) +yourdata = yourpop.evolve(max_iter=50, history=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/comparison-sma.py b/examples/comparison-sma.py index 0c148ca..333901d 100755 --- a/examples/comparison-sma.py +++ b/examples/comparison-sma.py @@ -37,11 +37,11 @@ class MyIndividual(_Individual): pop1 = MyPopulation.random(size=30) pop2 = pop1.copy(type_=YourPopulation) -pop1.ezolve(n_iter=50) +pop1.ezolve(max_iter=50) ind1 = pop1.best_individual y1 = evaluate.fit(*ind1.decode()) -pop2.ezolve(n_iter=50) +pop2.ezolve(max_iter=50) ind2 = pop2.best_individual y2 = evaluate.fit(*ind2.decode()) diff --git a/examples/comparison-trait.py b/examples/comparison-trait.py index 36ab068..f319a5c 100755 --- a/examples/comparison-trait.py +++ b/examples/comparison-trait.py @@ -55,7 +55,7 @@ class ExampleIndividual2(ExampleIndividual, SelfAdaptiveIndividual): pop.mate_prob = pop.mutate_prob = 1 - data = pop.evolve(n_iter=300, history=True, stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness', + data = pop.evolve(max_iter=300, history=True, stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness', 'mean threshold': lambda pop: np.mean([ind.threshold for ind in pop.individuals]), 'mean mate_prob': lambda pop: np.mean([ind.mate_prob for ind in pop.individuals]), 'mean mutate_prob': lambda pop: np.mean([ind.mutate_prob for ind in pop.individuals]), @@ -73,16 +73,16 @@ class ExampleIndividual2(ExampleIndividual, SelfAdaptiveIndividual): ind2.mate_prob = ind.mate_prob ind2.mutate_prob = ind.mutate_prob - data2 = pop2.evolve(n_iter=300, history=True, stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness'}) + data2 = pop2.evolve(max_iter=300, history=True, stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness'}) pop1.mate_prob = 0.8 pop1.mutate_prob = 0.4 - data1 = pop1.evolve(n_iter=300, history=True, stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness'}) + data1 = pop1.evolve(max_iter=300, history=True, stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness'}) # pop2.mate_prob = data.loc[300, 'best mate_prob'] # pop2.mutate_prob = data.loc[300, 'best mutate_prob'] - # data2 = pop2.evolve(n_iter=300, history=True, stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness'}) + # data2 = pop2.evolve(max_iter=300, history=True, stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness'}) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/comparison0.py b/examples/comparison0.py index 5960659..63b30c9 100644 --- a/examples/comparison0.py +++ b/examples/comparison0.py @@ -31,8 +31,8 @@ class _Population2(HOFPopulation): pop2 = pop1.copy(type_=_Population2) stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness'} - data1 = pop1.evolve(stat=stat, n_iter=100, history=True) - data2 = pop2.evolve(stat=stat, n_iter=100, history=True) + data1 = pop1.evolve(stat=stat, max_iter=100, history=True) + data2 = pop2.evolve(stat=stat, max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/examples/comparison1.py b/examples/comparison1.py index ab2ab3e..70e6f00 100755 --- a/examples/comparison1.py +++ b/examples/comparison1.py @@ -86,20 +86,20 @@ def mate(self, mate_prob=None): stat={'Male Fitness':'male_fitness', 'Female Fitness':'female_fitness', 'Best Fitness': 'best_fitness', 'Mean Fitness': 'mean_fitness'} -n_iter = 500 -data2, t2 = sp.perf(stat=stat, n_iter=n_iter, n_repeats=1) +max_iter = 500 +data2, t2 = sp.perf(stat=stat, max_iter=max_iter, n_repeats=1) stat={'Mean Fitness':'mean_fitness', 'Best Fitness': 'best_fitness'} -data3, t3 = pop.perf(stat=stat, n_iter=n_iter, n_repeats=1) +data3, t3 = pop.perf(stat=stat, max_iter=max_iter, n_repeats=1) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) -ax.plot(data2.index * t2 / n_iter, data2['Best Fitness'], 'r', - data2.index * t2 / n_iter, data2['Mean Fitness'], 'r--', - data3.index * t3 / n_iter, data3['Best Fitness'], 'b', - data3.index * t3 / n_iter, data3['Mean Fitness'], 'b--') +ax.plot(data2.index * t2 / max_iter, data2['Best Fitness'], 'r', + data2.index * t2 / max_iter, data2['Mean Fitness'], 'r--', + data3.index * t3 / max_iter, data3['Best Fitness'], 'b', + data3.index * t3 / max_iter, data3['Mean Fitness'], 'b--') ax.legend(('My Fitness', 'My Mean Fitness', 'Traditional Fitness', 'Traditional Mean Fitness')) ax.set_xlabel('Time') ax.set_ylabel('Fitness') diff --git a/examples/comparison2.py b/examples/comparison2.py index 317a649..070f19c 100755 --- a/examples/comparison2.py +++ b/examples/comparison2.py @@ -34,7 +34,7 @@ class MyPopulation(AgePopulation): # pop.evolve(verbose=True) -data = pop.evolve(n_iter=200, stat=stat, history=True) +data = pop.evolve(max_iter=200, stat=stat, history=True) import matplotlib.pyplot as plt fig = plt.figure() @@ -42,7 +42,7 @@ class MyPopulation(AgePopulation): data[['Mean Fitness', 'Best Fitness']].plot(ax=ax) pop = MyPopulation(cpy.individuals) -data = pop.evolve(n_iter=200, stat=stat, history=True) +data = pop.evolve(max_iter=200, stat=stat, history=True) data[['Mean Fitness', 'Best Fitness']].plot(ax=ax) ax.legend(('Fitness', 'Best Fitness', 'My Fitness', 'My Best Fitness')) diff --git a/examples/comparison3.py b/examples/comparison3.py index e537486..810dae6 100755 --- a/examples/comparison3.py +++ b/examples/comparison3.py @@ -32,7 +32,7 @@ class YourPopulation(HOFPopulation): pop = YourPopulation.random() -data = pop.evolve(n_iter=100, history=True) +data = pop.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt fig = plt.figure() @@ -41,7 +41,7 @@ class YourPopulation(HOFPopulation): pop = pop.copy(type_=MyPopulation) -data = pop.evolve(n_iter=100, history=True) +data = pop.evolve(max_iter=100, history=True) data[['Mean Fitness', 'Best Fitness']].plot(ax=ax) ax.legend(('My Fitness', 'My Best Fitness', 'Your Fitness', 'Your Best Fitness')) ax.set_xlabel('Generations') diff --git a/examples/comparison4.py b/examples/comparison4.py index bf6ee2c..b5f6f97 100755 --- a/examples/comparison4.py +++ b/examples/comparison4.py @@ -29,10 +29,10 @@ class MyPopulation(StandardPopulation): stat={'Best Fitness(PSO)': 'max_fitness'} -data = pop.evolve(stat=stat, n_iter=100, history=True) +data = pop.evolve(stat=stat, max_iter=100, history=True) stat={'Best Fitness(GA)': 'max_fitness'} -data2 = pop2.evolve(stat=stat, n_iter=100, history=True) +data2 = pop2.evolve(stat=stat, max_iter=100, history=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/comparison5.py b/examples/comparison5.py index 234861d..1b9812d 100755 --- a/examples/comparison5.py +++ b/examples/comparison5.py @@ -39,11 +39,11 @@ def _fitness(self): pop = MyPopulation.random(size=(10, 10, 10)) pop2 = pop.copy(type_=YourPopulation) -pop.ezolve(n_iter=300) +pop.ezolve(max_iter=300) ind1 = pop.best_individual y1 = evaluate.fit(*ind1.chromosomes) -pop2.ezolve(n_iter=300) +pop2.ezolve(max_iter=300) ind2 = pop2.best_individual y2 = evaluate.fit(*ind2.chromosomes) diff --git a/examples/example-aco.py b/examples/example-aco.py index 80d2e3d..1b896b1 100755 --- a/examples/example-aco.py +++ b/examples/example-aco.py @@ -18,7 +18,7 @@ class AntPopulation(BaseAntColony): ac = AntPopulation.from_distances(n_ants=10, distances=distances) -ac.ezolve(n_iter=30) +ac.ezolve(max_iter=30) print('colony:') for ant in ac: diff --git a/examples/example-ep.py b/examples/example-ep.py index eb1eb4a..0ed029d 100644 --- a/examples/example-ep.py +++ b/examples/example-ep.py @@ -35,7 +35,7 @@ class _Population(EvolutionProgramming, BasePopulation): pop = _Population.random() -data = pop.evolve(n_iter=100, period=2, history=True, verbose=True) +data = pop.evolve(max_iter=100, period=2, history=True, verbose=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/example-ep2.py b/examples/example-ep2.py index 22a99d2..170d0e3 100644 --- a/examples/example-ep2.py +++ b/examples/example-ep2.py @@ -29,7 +29,7 @@ class _Population(EvolutionProgramming, BasePopulation): pop = _Population.random() stat={'Mean Fitness':'mean_fitness', 'Max Fitness': 'max_fitness', 'Size': len} -data = pop.evolve(stat=stat, n_iter=100, period=5, history=True, verbose=True) +data = pop.evolve(stat=stat, max_iter=100, period=5, history=True, verbose=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/example-es.py b/examples/example-es.py index 6204f15..c16f750 100755 --- a/examples/example-es.py +++ b/examples/example-es.py @@ -14,7 +14,7 @@ ind = MyPopulation.random() -data = ind.evolve(n_iter=100, history=True) +data = ind.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/examples/example-gsa.py b/examples/example-gsa.py index 7e7788c..8864689 100644 --- a/examples/example-gsa.py +++ b/examples/example-gsa.py @@ -22,7 +22,7 @@ class MyGravitySearch(GravitySearch, BasePopulation): stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness'} -data = pop.evolve(stat=stat, n_iter=100, history=True) +data = pop.evolve(stat=stat, max_iter=100, history=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/example-hybridpopulation.py b/examples/example-hybridpopulation.py index 2957e89..b2c28f8 100644 --- a/examples/example-hybridpopulation.py +++ b/examples/example-hybridpopulation.py @@ -25,7 +25,7 @@ def max_fitness(self): sp = _HybridPopulation.random() -data = sp.evolve(n_iter=100, history=True) +data = sp.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/examples/example-local1.py b/examples/example-local1.py index 57ccce7..6b9cecb 100755 --- a/examples/example-local1.py +++ b/examples/example-local1.py @@ -38,7 +38,7 @@ def get_neighbour(self): sa = SAIndividual.random(size=n) -sa_data = sa.evolve(stat={'Fitness':'fitness', 'Phantom Fitness':lambda ind: ind.phantom.fitness}, n_iter=200, history=True) +sa_data = sa.evolve(stat={'Fitness':'fitness', 'Phantom Fitness':lambda ind: ind.phantom.fitness}, max_iter=200, history=True) import matplotlib.pyplot as plt diff --git a/examples/example-local2.py b/examples/example-local2.py index 4dab99f..5741a66 100755 --- a/examples/example-local2.py +++ b/examples/example-local2.py @@ -43,7 +43,7 @@ def move(self, action): ts = TSIndividual.random(size=8) -ts_data = ts.history(n_iter=100) +ts_data = ts.history(max_iter=100) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/example-local3.py b/examples/example-local3.py index 554d904..7b81d4c 100755 --- a/examples/example-local3.py +++ b/examples/example-local3.py @@ -30,7 +30,7 @@ def get_neighbour(self): i = MyIndividual.random(size=20) -data = i.evolve(n_iter=100, history=True) +data = i.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) diff --git a/examples/example-local4.py b/examples/example-local4.py index c60d4e7..df0d289 100755 --- a/examples/example-local4.py +++ b/examples/example-local4.py @@ -44,7 +44,7 @@ def get_neighbour(self): points = _evaluate.points def animate(i): - sa.evolve(n_iter=5, verbose=False) + sa.evolve(max_iter=5, verbose=False) ax.plot(*sa.chromosome.to_points(), 'k-o') ax.plot(*sa.phantom.chromosome.to_points(), 'b--o') ax.legend((f'Best Solution({sa.fitness:.4})', f'Generation {i*5}')) diff --git a/examples/example-local5.py b/examples/example-local5.py index bae1bee..8884c45 100755 --- a/examples/example-local5.py +++ b/examples/example-local5.py @@ -44,7 +44,7 @@ def get_neighbour(self): points = _evaluate.points def animate(i): - sa.evolve(n_iter=5, verbose=False) + sa.evolve(max_iter=5, verbose=False) ax.plot(*sa.chromosome.to_points(), 'k-o') ax.plot(*sa.phantom.chromosome.to_points(), 'b--o') ax.legend((f'Best Solution({sa.fitness:.4})', f'Generation {i*5}')) diff --git a/examples/example-multipopulation.py b/examples/example-multipopulation.py index f1bf8b6..436ddb0 100644 --- a/examples/example-multipopulation.py +++ b/examples/example-multipopulation.py @@ -29,7 +29,7 @@ class _MultiPopulation(MultiPopulation): sp = _MultiPopulation.random() -data = sp.evolve(n_iter=100, history=True) +data = sp.evolve(max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/examples/example-pso copy.py b/examples/example-pso copy.py index 3a8ad59..a9e9955 100644 --- a/examples/example-pso copy.py +++ b/examples/example-pso copy.py @@ -25,7 +25,7 @@ class MyParticleSwarm(ParticleSwarm): stat={'Mean Fitness': 'mean_fitness', 'Best Fitness': 'max_fitness'} -data = pop.evolve(stat=stat, n_iter=10, history=True, verbose=True) +data = pop.evolve(stat=stat, max_iter=10, history=True, verbose=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/example-pso-path.py b/examples/example-pso-path.py index 9d04d2e..2d17373 100755 --- a/examples/example-pso-path.py +++ b/examples/example-pso-path.py @@ -58,7 +58,7 @@ class _ParticleSwarm(ParticleSwarm, HOFPopulation): def animate(i): - pop.ezolve(n_iter=2) + pop.ezolve(max_iter=2) x = pop.best_individual.decode() ax.plot(points[x, 0], points[x, 1], 'k-o') ax.legend((f'Generation {i*2}({pop.best_fitness:.4})',)) diff --git a/examples/example-pso.py b/examples/example-pso.py index 3a8ad59..a9e9955 100644 --- a/examples/example-pso.py +++ b/examples/example-pso.py @@ -25,7 +25,7 @@ class MyParticleSwarm(ParticleSwarm): stat={'Mean Fitness': 'mean_fitness', 'Best Fitness': 'max_fitness'} -data = pop.evolve(stat=stat, n_iter=10, history=True, verbose=True) +data = pop.evolve(stat=stat, max_iter=10, history=True, verbose=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/example-sa.py b/examples/example-sa.py index 036e52f..6ffe6dc 100755 --- a/examples/example-sa.py +++ b/examples/example-sa.py @@ -30,7 +30,7 @@ def get_neighbour(self): ind = MyIndividual.random() stat = {'Fitness':'_fitness'} -data = ind.evolve(stat=stat, n_iter=100, history=True) +data = ind.evolve(stat=stat, max_iter=100, history=True) import matplotlib.pyplot as plt diff --git a/examples/example-studga.py b/examples/example-studga.py index bd9ba8c..ec7abd3 100755 --- a/examples/example-studga.py +++ b/examples/example-studga.py @@ -31,9 +31,9 @@ class YourPopulation(HOFPopulation): pop2 = pop.clone(type_=YourPopulation) stat={'Mean Fitness':'fitness', 'Best Fitness':'best_fitness', 'Standard Deviation of Fitnesses': 'std_fitness'} -data = pop.evolve(stat=stat, n_iter=200, history=True) +data = pop.evolve(stat=stat, max_iter=200, history=True) stat={'Mean Fitness2':'fitness', 'Best Fitness2':'best_fitness', 'Standard Deviation of Fitnesses2': 'std_fitness'} -data2 = pop2.evolve(stat=stat, n_iter=200, history=True) +data2 = pop2.evolve(stat=stat, max_iter=200, history=True) import matplotlib.pyplot as plt diff --git a/examples/example.py b/examples/example.py index 1d1ec83..accef3c 100755 --- a/examples/example.py +++ b/examples/example.py @@ -50,7 +50,7 @@ class MyPopulation(StandardPopulation): } # Do statistical task and print the results through the evoluation - data = pop.evolve(stat=stat, n_iter=100, history=True) + data = pop.evolve(stat=stat, max_iter=100, history=True) # Visualize the data import matplotlib.pyplot as plt diff --git a/examples/example0.py b/examples/example0.py index 19375a0..96b901e 100755 --- a/examples/example0.py +++ b/examples/example0.py @@ -19,7 +19,7 @@ def _fitness(o): # MyPopulation.map = concurrent.futures.ProcessPoolExecutor().map stat={'Mean Fitness':'mean_fitness', 'Best Fitness': 'max_fitness'} -data = pop.evolve(stat=stat, n_iter=100, history=True) +data = pop.evolve(stat=stat, max_iter=100, history=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/example1.py b/examples/example1.py index c7c7975..e53d541 100755 --- a/examples/example1.py +++ b/examples/example1.py @@ -42,7 +42,7 @@ def _fitness(self): pop = MyPopulation.random() stat = {'Mean Fitness':'mean_fitness', 'Best Fitness':'max_fitness'} -data = pop.evolve(stat=stat, n_iter=50, history=True, verbose=True) +data = pop.evolve(stat=stat, max_iter=50, history=True, verbose=True) if __name__ == '__main__': diff --git a/examples/example11.py b/examples/example11.py index a1b1781..9119411 100755 --- a/examples/example11.py +++ b/examples/example11.py @@ -28,7 +28,7 @@ class YourPopulation(StandardPopulation): element_class = YourIndividual pop = YourPopulation.random(n_individuals=50, n_chromosomes=2, size=32) - pop.evolve(n_iter=100, verbose=True) + pop.evolve(max_iter=100, verbose=True) def example2(): @@ -51,6 +51,6 @@ class YourPopulation(StandardPopulation): element_class = YourIndividual pop = YourPopulation.random(n_individuals=50, n_chromosomes=3, size=16) - pop.evolve(n_iter=100, verbose=True) + pop.evolve(max_iter=100, verbose=True) example2() diff --git a/examples/example12.py b/examples/example12.py index c2dbdfd..d17907c 100755 --- a/examples/example12.py +++ b/examples/example12.py @@ -40,7 +40,7 @@ def _fitness(self): pop = StandardPopulation.random(n_individuals=30, sizes=(N, N, N, p, p, p, 3)) stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'max_fitness', 'STD Fitness': 'std_fitness'} - data = pop.evolve(stat=stat, n_iter=100, history=True) + data = pop.evolve(stat=stat, max_iter=100, history=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/example14.py b/examples/example14.py index de37095..a2269f3 100755 --- a/examples/example14.py +++ b/examples/example14.py @@ -64,7 +64,7 @@ def mate(self): ax = fig.add_subplot(111) def animate(i): - pop.evolve(n_iter=2, verbose=False) + pop.evolve(max_iter=2, verbose=False) params = pop.best_individual.chromosomes yy = evaluate.fit(*params) ax.set_xlim((-5,5)) diff --git a/examples/example15.py b/examples/example15.py index 472748d..6754c2f 100755 --- a/examples/example15.py +++ b/examples/example15.py @@ -48,7 +48,7 @@ def _fitness(self): pop = MyPopulation.random() -pop.ezolve(n_iter=250) +pop.ezolve(max_iter=250) params = pop.solution im = evaluate.toimage(*params) im.show() diff --git a/examples/example16.py b/examples/example16.py index f427142..80bd645 100644 --- a/examples/example16.py +++ b/examples/example16.py @@ -71,7 +71,7 @@ class MyPopulation(_Population): stat={'Male Fitness':'male_fitness', 'Female Fitness':'female_fitness', 'Best Fitness': 'best_fitness', 'Mean Expect': 'expect', 'Best Expect': 'best_expect'} -data = sp.evolve(stat=stat, n_iter=100, history=True) +data = sp.evolve(stat=stat, max_iter=100, history=True) import matplotlib.pyplot as plt fig = plt.figure() diff --git a/examples/example2.py b/examples/example2.py index a0fa890..eda9732 100755 --- a/examples/example2.py +++ b/examples/example2.py @@ -76,9 +76,9 @@ def transit(self, *args, **kwargs): ax = fig.add_subplot(111) pop = MyPopulation.random(n_individuals=40, size=[8]*ndim+[8]) cpy = pop.copy(HOFPopulation[ExampleIndividual]) - d = cpy.evolve(n_iter=200, stat=stat, history=True, verbose=True) + d = cpy.evolve(max_iter=200, stat=stat, history=True, verbose=True) ax.plot(d.index, d['Mean Fitness'], d.index, d['Best Fitness'], '.-') - d = pop.evolve(n_iter=200, stat=stat, history=True) + d = pop.evolve(max_iter=200, stat=stat, history=True) ax.plot(d.index, d['Mean Fitness'], d.index, d['Best Fitness'], '.-') ax.legend(('Traditional mean', f'Traditional best({cpy.best_fitness})', 'New mean', f'New best({pop.best_fitness})')) ax.set_title('Comparison of two GAs') diff --git a/examples/example3.py b/examples/example3.py index 843830a..4d60acd 100755 --- a/examples/example3.py +++ b/examples/example3.py @@ -72,8 +72,8 @@ class MyIndividual(_Individual): pop = MyPopulation.random() # pop.append(i) pop2 = pop.copy(type_=YourPopulation) -data = pop.evolve(stat={'Error': lambda pop: - pop.max_fitness}, n_iter=300, history=True, period=5) -yourdata = pop2.evolve(stat={'Error': lambda pop: - pop.max_fitness}, n_iter=300, history=True, period=5) +data = pop.evolve(stat={'Error': lambda pop: - pop.max_fitness}, max_iter=300, history=True, period=5) +yourdata = pop2.evolve(stat={'Error': lambda pop: - pop.max_fitness}, max_iter=300, history=True, period=5) import matplotlib.pyplot as plt diff --git a/examples/example4.py b/examples/example4.py index 20aa490..6e6e13d 100755 --- a/examples/example4.py +++ b/examples/example4.py @@ -54,7 +54,7 @@ def get_neighbour(self): ga = StandardPopulation.random(n_individuals=20, size=10) ga.mate_prob = 0.9 - data= ga.evolve(n_iter=10, stat=stat, history=True, verbose=True) + data= ga.evolve(max_iter=10, stat=stat, history=True, verbose=True) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) @@ -65,7 +65,7 @@ def get_neighbour(self): lga = LocalSearchPopulation.random(n_individuals=20, n_chromosomes=10, size=10) lga.mate_prob = 0.9 - d= lga.evolve(n_iter=10, stat=stat, history=True) + d= lga.evolve(max_iter=10, stat=stat, history=True) d[['Mean Fitness', 'Max Fitness']].plot(ax=ax, style='.-') ax.legend(('Traditional','Traditional best', 'SA', 'SA best')) plt.show() diff --git a/examples/example5.py b/examples/example5.py index 8b44e8d..71ed242 100755 --- a/examples/example5.py +++ b/examples/example5.py @@ -27,7 +27,7 @@ def _fitness(self): pop = MyPopulation.random(n_individuals=100) stat = {'Best Fitness': 'best_fitness', 'Mean Fitness': 'mean_fitness'} -data = pop.evolve(n_iter=200, stat=stat, history=True) +data = pop.evolve(max_iter=200, stat=stat, history=True) import matplotlib.pyplot as plt diff --git a/examples/example6.py b/examples/example6.py index bc8824a..5040a83 100755 --- a/examples/example6.py +++ b/examples/example6.py @@ -64,13 +64,13 @@ class MyPopulation(HOFPopulation): cpy = pop.clone(type_=StandardPopulation[ExampleIndividual]) pop.mate_prob = 1 pop.mutate_prob = 1 - d = pop.evolve(n_iter=500, stat=stat, history=True, period=10) + d = pop.evolve(max_iter=500, stat=stat, history=True, period=10) d[['Mean Fitness', 'Best Fitness']].plot(ax=ax, style='.-') d['Standard Deviation'].plot(ax=ax2, style='--') cpy.mate_prob = 0.9 - d = cpy.evolve(n_iter=500, stat=stat, history=True, period=10) + d = cpy.evolve(max_iter=500, stat=stat, history=True, period=10) d[['Mean Fitness', 'Best Fitness']].plot(ax=ax) d['Standard Deviation'].plot(ax=ax2, style='--') diff --git a/examples/example7.py b/examples/example7.py index bac671c..ece5376 100755 --- a/examples/example7.py +++ b/examples/example7.py @@ -41,7 +41,7 @@ def __str__(self): HOFPopulation.element_class = MyIndividual pop = HOFPopulation.random(n_individuals=10, size=15) - data = pop.evolve(n_iter=100, stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness'}, history=True) + data = pop.evolve(max_iter=100, stat={'Mean Fitness':'mean_fitness', 'Best Fitness':'best_fitness'}, history=True) import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) diff --git a/examples/example8.py b/examples/example8.py index eee0a64..39f4d3f 100755 --- a/examples/example8.py +++ b/examples/example8.py @@ -31,7 +31,7 @@ def decode(self): points = _evaluate.points def animate(i, step=5, start=0): - pop.ezolve(n_iter=step) + pop.ezolve(max_iter=step) x = pop.solution ax.plot(points[x, 0], points[x, 1], 'r-o') ax.legend((f'Generation {start+i*step}({-pop.best_fitness:.4})',)) diff --git a/examples/movie.py b/examples/movie.py index 914048d..a8c2619 100755 --- a/examples/movie.py +++ b/examples/movie.py @@ -1,810 +1,810 @@ -#!/usr/bin/env python - -from random import randint, random -import time -import copy - -import numpy as np -from scipy import stats -import matplotlib.pyplot as plt - - -# data -movies = {248576: (130, 3.3682410181274, 0), 344258: (110, 4.5819413321144, 1), 247875: (135, 24.520869061059, 0), 342183: (105, 6.3525688839221, 1), 1190376: (115, 2.3976810308718, 0), 342858: (120, 18.548330769309, 0), 346383: (110, 13.337895007968, 1), 344880: (105, 8.7481385225418, 0), 246065: (110, 8.0910852616215, 0), 1200675: (90, 3.4135008624687, 0), 1199126: (90, 4.2430678789594, 0), 344440: (90, 2.3966803710367, 0)} -movien = len(movies) -ids=[248576, 344258, 247875, 342183, 346383, 1190376, 342858, 346383, 344880, 246065, 1200675, 1199126, 344440] -hotp = np.array([movies[ids[k]][1] for k in range(movien)]) -S = np.sum(hotp) -hotp /= np.sum(hotp) -halls = {'37756': (154, 1489111200, 1489158000, 1, 6), '37757': (147, 1489111200, 1489158000, 1, 6), '37758': (146, 1489111200, 1489158000, 1, 6), '37755': (235, 1489111200, 1489158000, 1, 6), '37759': (126, 1489111200, 1489158000, 1, 6), '37762': (146, 1489111200, 1489158000, 1, 6), '37754': (410, 1489111200, 1489158000, 1, 6), '37761': (186, 1489111200, 1489158000, 1, 6)} - -halln = len(halls) -gtime = 1489147200 -gapub = 10 - -def stamp2str(timeStamp): - timeArray = time.localtime(timeStamp) - return time.strftime("%H:%M", timeArray) - -# def mymin(x): -# m = np.min(x) -# return m + np.mean(x-m)/(m+1) - -def mymin(x): - x = np.sort(np.unique(x)) - return np.sum(a / 30**k for k, a in enumerate(x)) - -class Movie(object): - '''Movie has 4 (principal) propteries - id_: id - length: length - hot: hot - type_: type - ''' - - __slots__ = ('id_', 'length', 'hot', 'type_', '__start', '__end') - - def __init__(self, id_, length, hot, type_): - self.id_ = id_ - self.length = length * 60 - self.hot = hot / 100 - self.type_ = type_ - self.__start = 0 - self.__end = length * 60 - - def __str__(self): - if self.isgolden(): - return 'movie %d(%.4s)*: %s - %s'%(self.id_, self.hot, stamp2str(self.start), stamp2str(self.end)) - else: - return 'movie %d(%.4s): %s - %s'%(self.id_, self.hot, stamp2str(self.start), stamp2str(self.end)) - - @property - def start(self): - return self.__start - - @property - def end(self): - return self.__end - - @start.setter - def start(self, time): - self.__start = time - self.__end = time + self.length - - @end.setter - def end(self, time): - self.__end = time - self.__start = time - self.length - - def isgolden(self): - return self.__end - 75 * 60 <= gtime <= self.__start + 75 * 60 - - def copy(self): - return copy.copy(self) - - -class Hall: - '''Hall has 6 (principal) propteries - - id_: id - seat: seat - start: start - last: last - entrance: entrance - type_: type - ''' - - def __init__(self, id_, seatn, start, last, entrance=1, type_=6): - self.id_ = id_ - self.seatn = seatn - self.start = start - self.last = last - self.entrance = entrance - self.type_ = type_ - self.movies = [] - self.admission = None - self.manager = None - self.min_interval = 300 - - @staticmethod - def from_db(data): - return Hall(id_=data[0], seatn=data[2], type_=data[3]) - - def __getitem__(self, key): - for m in self.movies: - if m.id_ == key: - return m - - def __str__(self): - return 'hall_%s'%self.id_ - - def __repr__(self): - return 'hall %s (%d)'%(self.id_, self.seatn) - - def random(self): - AM = self.admission - if AM is None: - p = np.array([m.hot for m in self.manager.movies]) - M = stats.rv_discrete(name='movie', values=(np.arange(movien), p / np.sum(p))) - else: - p = np.array([self.manager.movies[k].hot for k in AM]) - M = stats.rv_discrete(name='movie', values=(AM, p / np.sum(p))) - return M.rvs(size=1)[0] - - def dumps(self): - print('hall %s (%d):'%(self.id_, self.seatn)) - for m in self.movies: - if m.start <= self.last: - print(m, end=', ') - - def insert(self, i, movie, t=0): - self.movies.insert(i, movie) - if i == 0: - movie.start = h.start + t - self.movies[i+1].start += movie.length + t - else: - movie.start = self.movies[i-1].start + self.min_interval + t - self.movies[i+1].start += movie.length + self.min_interval + t - if self.movies[i+2].start - self.movies[i+1].end < self.min_interval: - self.movies[i+1].start = self.movies[i].end + self.min_interval - else: - return - for k in range(i+1, len(self.movies)-1): - if self.movies[k+1].start - self.movies[k].end < self.min_interval: - self.movies[k+1].start = self.movies[k].end + self.min_interval - else: - return - - def append(self, movie, t=0): - if self.movies: - movie.start = self.movies[-1].end + t + self.min_interval - else: - movie.start = self.start + t - self.movies.append(movie) - - def count(self): - # count movies in a hall - dict_ = {} - for m in self.movies: - if m.id_ in dict_: - dict_[m.id_] += 1 - else: - dict_.update({m.id_:1}) - return dict_ - - def dist(self, other): - k = 0 - d2 = d1 = 2100 - movies1 = [m for m in self.movies if m.start <= self.last] - movies2 = [m for m in other.movies if m.start <= other.last] - for m in movies1: - for l, mm in enumerate(movies2[k:]): - d = mm.start - m.start - if d <= -2100: - k = l + 1 - continue - else: - if d <= 2100: - if m.id_ == mm.id_: - d1 = min(abs(d), d1) - else: - d2 = min(abs(d), d2) - k = l + 1 - else: - k = l - break - return d1, d2 - - -class Criterion: - '''Criterion has 3 (principal) propteries - value: value - name: name - weight: weight [5] - level: level [None] - ''' - - def __init__(self, value, name='', weight=5, level=None): - self.value = value - self.name = name - self.weight = weight - self.level = level - - def __repr__(self): - return '%s: %.4f * %d'%(self.name, self.value, weight) - - -class Manager: - '''Manager has 1 (principal) proptery - halls: halls - ''' - - def __init__(self, halls, movies=None, sorted=True): - self.halls = halls - for h in halls: - h.manager = self - self.movies = movies - if sorted: - self.halls.sort(key=lambda h:h.seatn, reverse=True) - if movies: - self.movies.sort(key=lambda h:h.hot, reverse=True) - N = sum(h.type_ for h in self.halls) + halln / 2 - for m in self.movies: - p = np.array([m.hot for m in self.movies]) - self.estimate = [int(k) for k in np.round(N * (p / np.sum(p)))] - # count seat taking - - s = np.sum(np.sqrt(h.seatn) for h in self.halls) - for h in self.halls: - h.seat_rate = np.sqrt(h.seatn) / s - - @staticmethod - def from_data(hall_data, movie_data=None): - if movies: - return Manager([Hall(id_, *propteries) for id_, propteries in hall_data.items()], [Movie(id_, *propteries) for id_, propteries in movie_data.items()]) - else: - return Manager([Hall(id_, *propteries) for id_, propteries in hall_data.items()]) - - @staticmethod - def from_db(lst): - return Manager([Hall.from_db(*args) for args in lst]) - - def insert_into(self, j, k, t=None): - if t is None: - for time in range(gapub): - flag = True - for kk, h in enumerate(self.halls): - if kk != k: - for m in h.movies: - if time == m.start: - flag = False - if flag: - t = time - self.halls[k].insert(0, self.movies[j].copy(), t) - - def count(self): - '''count movies - dict_ : {id_: number} - ''' - - dict_ = {} - S = 0 - for h in self.halls: - S += len(h.movies) - for m in h.movies: - if m.start <= h.last: - if m.id_ in dict_: - dict_[m.id_] += 1 - else: - dict_.update({m.id_:1}) - - for id_ in dict_: - dict_[id_] /= S - return dict_ - - def schedule(self, individual): - # individual.gmovies = {} - for k, h in enumerate(self.halls): - n = h.type_ - h.movies = [self.movies[i].copy() for i in individual[k][1:2*n:2]] - times = individual[k][:2*n-1:2] - h.movies[0].start = h.start + times[0] * 300 - for l, m in enumerate(h.movies[1:], start=1): - m.start = h.movies[l-1].end + (times[l]+1) * 300 - if m.start > h.last: - h.movies = h.movies[:l] - break - - # if m.isgolden(): - # individual.gmovies.update({k:l}) - - def initSchedule2(self, hook=list): - # minlen = min(m.length for m in self.movies) - individual = hook(list([] for _ in range(halln))) - # individual.gmovies = {} - lst = self.estimate.copy() - i = 0 - ts = np.random.permutation(len(self.halls)) - for k, h in enumerate(self.halls): - # golden period - h.movies = [self.movies[i].copy()] - h.movies[0].start = gtime - 75 * 60 + ts[k] * 300 - individual[k] = [i] - lst[i] -= 1 - if lst[i] == 0: - i += 1 - for k, h in enumerate(self.halls): - # common period - n = h.type_ - times = np.random.randint(0, gapub, size=n) - for l in range(1, n): - end = h.movies[0].start - (times[l]+1) * 300 - start = end - self.movies[i].length - if h.start <= start and end <= h.movies[0].start + 300: - h.movies.insert(0, self.movies[i].copy()) - h.movies[0].start = start - t = times[l] - while lst[i] <= 0: - i += 1 - individual[k] = [i, t] + individual[k] - lst[i] -= 1 - elif start < h.start: - gap = (h.movies[0].start - h.start)//300 - if gap <= gapub: - individual[k] = [gap] + individual[k] - else: - for j, m in enumerate(self.movies): - if gap * 300 - 300 * gapub <= m.length + 300 <= gap * 300 and lst[j] > 0: - h.movies.insert(0, m.copy()) - h.movies[0].end = h.movies[1].start - 300 - t0 = (h.movies[0].start - h.start)//300 - individual[k] = [t0, i, 1] + individual[k] - lst[j] -= 1 - break - else: - while lst[i] <= 0: - i += 1 - lst[i] -= 1 - t0 = randint(0, gapub-1) - individual[k] = [t0, i, 1] + individual[k] - h.movies[0].start = self.movies[i].length + 300 * (t0 +1) - h.movies.insert(0, self.movies[i].copy()) - h.movies[0].start = t0 * 300 - for l in range(1, len(h.movies)-1): - m, mm = self.movies[l], self.movies[l+1] - if m.end <= mm.start - 300: - break - else: - mm.start = m.end + 300 - individual[k][l*2+2] = 1 - break - - # if h.movies[-1].isgolden(): - # individual.gmovies.update({k:l}) - # break - - t = times[-1] - start = h.movies[-1].end + t * 300 - if start <= h.last: - while lst[i] <= 0: - i += 1 - h.movies.insert(0, self.movies[i].copy()) - h.movies[-1].start = start - individual[k] = individual[k] + [t, i] - lst[i] -= 1 - d = h.type_ - len(h.movies) - if d > 0: - for _ in range(d): - if h.movies[-1].end + 300 <= h.last: - h.append(self.movies[i].copy()) - individual[k] = individual[k] + [1, i] - elif d < 0: - individual[k] = individual[k][:2*d] - h.movies = h.movies[:d] - return individual - - def initSchedule1(self, hook=list): - # minlen = min(m.length for m in self.movies) - individual = hook(list([] for _ in range(halln))) - # individual.gmovies = {} - lst = self.estimate.copy() - i = 0 - ts = np.random.permutation(len(self.halls)) - for k, h in enumerate(self.halls): - # Arrange movies in prime time - h.movies = [self.movies[i].copy()] - h.movies[0].start = gtime - 75 * 60 + ts[k] * 300 - individual[k] = [i] - lst[i] -= 1 - if lst[i] == 0: - i += 1 - # Arrange movies in common time - n = h.type_ - times = np.random.randint(0, gapub, size=n) - for l in range(1, n): - end = h.movies[0].start - (times[l]+1) * 300 - start = end - self.movies[i].length - if h.start <= start and end <= h.movies[0].start + 300: - h.movies.insert(0, self.movies[i].copy()) - h.movies[0].start = start - t = times[l] - while lst[i] <= 0: - i += 1 - individual[k] = [i, t] + individual[k] - lst[i] -= 1 - elif start < h.start: - gap = (h.movies[0].start - h.start)//300 - if gap <= gapub: - individual[k] = [gap] + individual[k] - else: - for j, m in enumerate(self.movies): - if gap * 300 - 300 * gapub <= m.length + 300 <= gap * 300 and lst[j] > 0: - h.movies.insert(0, m.copy()) - h.movies[0].end = h.movies[1].start - 300 - t0 = (h.movies[0].start - h.start)//300 - individual[k] = [t0, i, 1] + individual[k] - lst[j] -= 1 - break - else: - while lst[i] <= 0: - i += 1 - lst[i] -= 1 - t0 = randint(0, gapub-1) - individual[k] = [t0, i, 1] + individual[k] - h.movies[0].start = self.movies[i].length + 300 * (t0 +1) - h.movies.insert(0, self.movies[i].copy()) - h.movies[0].start = t0 * 300 - for l in range(1, len(h.movies)-1): - m, mm = self.movies[l], self.movies[l+1] - if m.end <= mm.start - 300: - break - else: - mm.start = m.end + 300 - individual[k][l*2+2] = 1 - break - - # if h.movies[-1].isgolden(): - # individual.gmovies.update({k:l}) - # break - - t = times[-1] - start = h.movies[-1].end + t * 300 - if start <= h.last: - while lst[i] <= 0: - i += 1 - h.movies.insert(0, self.movies[i].copy()) - h.movies[-1].start = start - individual[k] = individual[k] + [t, i] - lst[i] -= 1 - d = h.type_ - len(h.movies) - if d > 0: - for _ in range(d): - if h.movies[-1].end + 300 <= h.last: - h.append(self.movies[i].copy()) - individual[k] = individual[k] + [1, i] - elif d < 0: - individual[k] = individual[k][:2*d] - h.movies = h.movies[:d] - return individual - - def initSchedule(self, hook=list): - if random() < .5: - return self.initSchedule1(hook) - else: - return self.initSchedule2(hook) - - def fitness(self): - return self.time_interval(), self.check_rate(), self.total_hot(), self.check_time() - - def check(self): - d1, d2 = self.check_interval() - print(''' -Minimum time interval: %.4f+%.4f; -Similarity between popularity and show times: %.4f; -Total popularity (prime time): %.4f(%.4f); -The number of full-screen movie halls: %d'''%(d1, d2, self.check_rate(), self.total_hot(), self.ghot(), self.check_time())) - - def print_fitness(self): - print('fitness: %.4f, %.4f, %.4f, %d'%(self.time_interval(), self.check_rate(), self.total_hot(), self.check_time())) - - def hot(self): - # total popularity - return sum(sum(m.hot for m in h.movies if m.start<=h.last) * h.seatn for h in self.halls) - - def ghot(self): - # prime time - hot = 0 - for h in self.halls: - for m in h.movies: - if m.isgolden(): - hot += m.hot * h.seatn - break - return hot - - def total_hot(self): - # Weighted popularity - return sum(sum(m.hot for m in h.movies if m.start<=h.last) * h.seatn for h in self.halls) + 3 * self.ghot() - - def check_time(self): - # check time-out - N = 0 - for h in self.halls: - if h.movies[-1].start <= h.last: - N +=1 - return N - - def check_rate(self): - """Popularity ~ Times ratio ~ Screening rate ~ Number ratio ~ Box office rate -The degree of similarity between the system recommended screening rate and the actual screening rate - """ - dict_ = self.count() - d = 0 - for id_, rate in dict_.items(): - d += abs(movies[id_][1]/S - rate) - return 1 / (d + 0.001) - - def check_interval(self): - # opening interval - d1s = [] - d2s = [] - for k, h in enumerate(self.halls[:-1]): - for hh in self.halls[k+1:]: - d1, d2 = h.dist(hh) - d1s.append(d1) - d2s.append(d2) - return min(d1s) / 60, min(d2s) / 60 - - def time_interval(self): - # opening interval - deltas = [] - for k, h in enumerate(self.halls[:-1]): - for hh in self.halls[k+1:]: - d1, d2 = h.dist(hh) - deltas.append((d1*0.5 + d2*0.5)) - delta = mymin(deltas) - - return delta / 60 - - def criterion1(self): - # Rationality of arranging movie screening halls(安排影片放映厅的合理性) - c = self.count() - alpha = 0 - for m in self.movies: - for k, h in enumerate(self.halls): - hc = h.count() - if m.id_ in hc and c[m.id_] < hc[m.id_] * 2: - alpha += abs(m.hot - h.seat_rate) - break - return alpha - - def criterion2(self): - # The degree of similarity between the system recommended screening rate and the actual screening rate(系统推荐排片率与实际排片率接近程度) - return self.check_rate() - - def criterion3(self): - # the number of movies shown during the prime time(黄金时间段放映电影数) - hot = 0 - for h in self.halls: - for m in h.movies[::-1]: - if m.isgolden(): - hot += 1 - break - return hot - - def criterion4(self): - # the most popular movie screened in the optimal hall during the prime time(最火的影片排入最优厅黄金时间段) - for m in self.halls[0].movies: - if m.id_ == self.movies[0].id_ and m.isgolden(): - return 1 - return 0 - - # def golden(self): - # c = {} - # for h in self.halls: - # for m in h: - # if m.isgolden(): - # if m.id_ in c: - # c[m.id_].append(m) - # else: - # c[m.id_] = [m] - # return c - - def criterion5(self): - return 1 - - def criterion6(self): - # Rationality of the interval between the opening of all movies in prime time (所有电影黄金时段开映间隔合理性) - times = np.sort([m.start for h in self.halls for m in h.movies if m.isgolden()]) - times = np.diff(times) - return 1 - - def criterion7(self): - # (所有电影非黄金时段开映间隔合理性) - times = np.sort([m.start for h in self.halls for m in h.movies if not m.isgolden()]) - times = np.diff(times) - return 1 - - def criterion8(self): - # (避免同时开场) - return 1 - - def criterion9(self): - # (高票房日子场间隔尽量短) - times = np.sort([m.start for h in self.halls for m in h.movies]) - return 1 - - def criterion10(self, latest='22'): - # (低热度动画片开映时间合理性) - n = 0 - for h in self.halls: - for m in hall: - if '动画' in m.type and m.hot < 1/halln and m.end > latest: - n += 1 - return n - - def criterion11(self, earliest='22'): - # (低热度动画片开映时间合理性) - n = 0 - for h in self.halls: - for m in hall: - if '恐怖' in m.type and m.hot < 0.5/halln and m.start < earliest: - n += 1 - return n - - def hasbighall(self): - return self.halls[0].seatn > self.halls[1].seatn * 1.5 - - def criterion12(self): - # Hall sharing status(大厅共用情况) - m, mm = self.movies[:2] - if self.hasbighall() and abs(m.hot - mm.hot) < 0.05: - gm = [m for m in self.halls[0].movies() if m.isgolden] - if set(m.id_ for m in gm) == {m.id_, mm.id_}: - return 1 - else: - return 0 - - - def criterion13(self): - # The richness of screening(影片排映丰富度) - if halln >= 6 and sum(m.hot for m in self.movies[:5])> .05: - return len(self.count()) - - - def criterion14(self, minhot=0.1): - # not popular movie (小片不在黄金时段) - n = 0 - for h in self.halls: - for m in h: - if m.isgolden() and m.hot < minhot: - n += 1 - return n - - def print_criterion(self): - for k in range(1, 13): - if k != 10 and k!=11: - print('criterion%d:'%k, getattr(self, 'criterion%d'%k)()) - - def dumps(self): - for h in self.halls: - h.dumps() - print() - - def stat(self): - dict_ = self.count() - for id_, rate in dict_.items(): - print(movies[id_][1]/100, rate) - - def plot(self, axes=None): - from matplotlib.ticker import FuncFormatter, MaxNLocator - if axes is None: - fig = plt.figure() - axes = fig.add_subplot(111) - axes.invert_yaxis() - - def format_fn(tick_val, tick_pos): - return stamp2str(tick_val) - axes.xaxis.set_major_formatter(FuncFormatter(format_fn)) - axes.xaxis.set_major_locator(MaxNLocator(integer=True)) - def format_fn(tick_val, tick_pos): - k = int(tick_val) - if k < len(self.halls): - h = self.halls[k] - return '%s(%d)'%(h.id_, h.seatn) - else: - return '' - axes.yaxis.set_major_formatter(FuncFormatter(format_fn)) - axes.yaxis.set_major_locator(MaxNLocator(integer=True)) - - H = len(self.halls) - for k, h in enumerate(self.halls): - for m in h.movies: - if m.hot > 0.2: - color = 'r' - elif m.hot > 0.15: - color = 'y' - elif m.hot > 0.1: - color = 'g' - elif m.hot > 0.05: - color = 'c' - else: - color = 'b' - axes.text(m.start, k, '%d'%m.id_) - axes.plot((m.start, m.end), (k, k), color=color, linestyle='-') - axes.plot((h.start, h.start), (k-1/2, k+1/2), color='k') - axes.plot((h.last, h.last), (k-1/2, k+1/2), color='k') - axes.plot((gtime-75*60, gtime-75*60), (0, H), color='y', linestyle='--') - axes.plot((gtime+75*60, gtime+75*60), (0, H), color='y', linestyle='--') - axes.set_xlabel('time') - axes.set_ylabel('hall') - axes.set_title('movie schedule') - plt.show() - - -manager = Manager.from_data(halls, movies) - - -from deap import tools - -def mutRandom(individual, indpb1, indpb2): - ts = np.random.permutation(gapub) - for k, hall in enumerate(individual): - hall[0] = ts[k] - for k, hall in enumerate(individual): - if random() < indpb1: - for i in range(1, len(hall), 2): - if random() < indpb2: - if random() < 0.7: - if hall[i] == 0: - hall[i] += 1 - else: - hall[i] -= 1 - else: - if hall[i] == movien: - hall[i] -= 1 - else: - hall[i] += 1 - - else: - for i in range(2, len(hall)-1, 2): - if random() < indpb2: - hall[i] = np.random.choice([t for t in range(gapub) if t != hall[i]]) - h = randint(0, halln-2) - if random() < 0.3: - individual[h], individual[h+1] = individual[h+1], individual[h] - else: - individual[h], individual[h+1] = tools.cxTwoPoint(individual[h+1], individual[h]) - return individual - - -from pyrimidine import BaseIndividual, HOFPopulation -from pyrimidine.deco import side_effect, fitness_cache - - -class Chromosome(list): - - def copy(self, type_=None): - return copy.deepcopy(self) - - def cross(self, other): - k = randint(1, len(self)-1) - return self.__class__(np.concatenate((self[:k], other[k:]), axis=0)) - - -@fitness_cache -class Individual(BaseIndividual): - - element_class = Chromosome - - @side_effect - def mutate(self): - self[:] = mutRandom(self, indpb1=0.15, indpb2=0.8) - - def cross(self, other): - s1 = set(h[0] for h in self) - s2 = set(h[0] for h in other) - if random() > 1/(len(s1.symmetric_difference(s2))+1): - return super().cross(other) - else: - return self.copy() - - def _fitness(self): - manager.schedule(self) - return np.dot((50, 20, 2, 1), manager.fitness()) - - -Population = HOFPopulation[Individual] - -if __name__ == '__main__': - - pop = Population([manager.initSchedule() for _ in range(50)]) - pop.evolve() - ind = pop.best_individual - - manager.schedule(ind) - manager.print_fitness() - - manager.check() - manager.dumps() - manager.plot() - manager.print_criterion() +#!/usr/bin/env python + +from random import randint, random +import time +import copy + +import numpy as np +from scipy import stats +import matplotlib.pyplot as plt + + +# data +movies = {248576: (130, 3.3682410181274, 0), 344258: (110, 4.5819413321144, 1), 247875: (135, 24.520869061059, 0), 342183: (105, 6.3525688839221, 1), 1190376: (115, 2.3976810308718, 0), 342858: (120, 18.548330769309, 0), 346383: (110, 13.337895007968, 1), 344880: (105, 8.7481385225418, 0), 246065: (110, 8.0910852616215, 0), 1200675: (90, 3.4135008624687, 0), 1199126: (90, 4.2430678789594, 0), 344440: (90, 2.3966803710367, 0)} +movien = len(movies) +ids=[248576, 344258, 247875, 342183, 346383, 1190376, 342858, 346383, 344880, 246065, 1200675, 1199126, 344440] +hotp = np.array([movies[ids[k]][1] for k in range(movien)]) +S = np.sum(hotp) +hotp /= np.sum(hotp) +halls = {'37756': (154, 1489111200, 1489158000, 1, 6), '37757': (147, 1489111200, 1489158000, 1, 6), '37758': (146, 1489111200, 1489158000, 1, 6), '37755': (235, 1489111200, 1489158000, 1, 6), '37759': (126, 1489111200, 1489158000, 1, 6), '37762': (146, 1489111200, 1489158000, 1, 6), '37754': (410, 1489111200, 1489158000, 1, 6), '37761': (186, 1489111200, 1489158000, 1, 6)} + +halln = len(halls) +gtime = 1489147200 +gapub = 10 + +def stamp2str(timeStamp): + timeArray = time.localtime(timeStamp) + return time.strftime("%H:%M", timeArray) + +# def mymin(x): +# m = np.min(x) +# return m + np.mean(x-m)/(m+1) + +def mymin(x): + x = np.sort(np.unique(x)) + return np.sum(a / 30**k for k, a in enumerate(x)) + +class Movie(object): + '''Movie has 4 (principal) propteries + id_: id + length: length + hot: hot + type_: type + ''' + + __slots__ = ('id_', 'length', 'hot', 'type_', '__start', '__end') + + def __init__(self, id_, length, hot, type_): + self.id_ = id_ + self.length = length * 60 + self.hot = hot / 100 + self.type_ = type_ + self.__start = 0 + self.__end = length * 60 + + def __str__(self): + if self.isgolden(): + return 'movie %d(%.4s)*: %s - %s'%(self.id_, self.hot, stamp2str(self.start), stamp2str(self.end)) + else: + return 'movie %d(%.4s): %s - %s'%(self.id_, self.hot, stamp2str(self.start), stamp2str(self.end)) + + @property + def start(self): + return self.__start + + @property + def end(self): + return self.__end + + @start.setter + def start(self, time): + self.__start = time + self.__end = time + self.length + + @end.setter + def end(self, time): + self.__end = time + self.__start = time - self.length + + def isgolden(self): + return self.__end - 75 * 60 <= gtime <= self.__start + 75 * 60 + + def copy(self): + return copy.copy(self) + + +class Hall: + '''Hall has 6 (principal) propteries + + id_: id + seat: seat + start: start + last: last + entrance: entrance + type_: type + ''' + + def __init__(self, id_, seatn, start, last, entrance=1, type_=6): + self.id_ = id_ + self.seatn = seatn + self.start = start + self.last = last + self.entrance = entrance + self.type_ = type_ + self.movies = [] + self.admission = None + self.manager = None + self.min_interval = 300 + + @staticmethod + def from_db(data): + return Hall(id_=data[0], seatn=data[2], type_=data[3]) + + def __getitem__(self, key): + for m in self.movies: + if m.id_ == key: + return m + + def __str__(self): + return 'hall_%s'%self.id_ + + def __repr__(self): + return 'hall %s (%d)'%(self.id_, self.seatn) + + def random(self): + AM = self.admission + if AM is None: + p = np.array([m.hot for m in self.manager.movies]) + M = stats.rv_discrete(name='movie', values=(np.arange(movien), p / np.sum(p))) + else: + p = np.array([self.manager.movies[k].hot for k in AM]) + M = stats.rv_discrete(name='movie', values=(AM, p / np.sum(p))) + return M.rvs(size=1)[0] + + def dumps(self): + print('hall %s (%d):'%(self.id_, self.seatn)) + for m in self.movies: + if m.start <= self.last: + print(m, end=', ') + + def insert(self, i, movie, t=0): + self.movies.insert(i, movie) + if i == 0: + movie.start = h.start + t + self.movies[i+1].start += movie.length + t + else: + movie.start = self.movies[i-1].start + self.min_interval + t + self.movies[i+1].start += movie.length + self.min_interval + t + if self.movies[i+2].start - self.movies[i+1].end < self.min_interval: + self.movies[i+1].start = self.movies[i].end + self.min_interval + else: + return + for k in range(i+1, len(self.movies)-1): + if self.movies[k+1].start - self.movies[k].end < self.min_interval: + self.movies[k+1].start = self.movies[k].end + self.min_interval + else: + return + + def append(self, movie, t=0): + if self.movies: + movie.start = self.movies[-1].end + t + self.min_interval + else: + movie.start = self.start + t + self.movies.append(movie) + + def count(self): + # count movies in a hall + dict_ = {} + for m in self.movies: + if m.id_ in dict_: + dict_[m.id_] += 1 + else: + dict_.update({m.id_:1}) + return dict_ + + def dist(self, other): + k = 0 + d2 = d1 = 2100 + movies1 = [m for m in self.movies if m.start <= self.last] + movies2 = [m for m in other.movies if m.start <= other.last] + for m in movies1: + for l, mm in enumerate(movies2[k:]): + d = mm.start - m.start + if d <= -2100: + k = l + 1 + continue + else: + if d <= 2100: + if m.id_ == mm.id_: + d1 = min(abs(d), d1) + else: + d2 = min(abs(d), d2) + k = l + 1 + else: + k = l + break + return d1, d2 + + +class Criterion: + '''Criterion has 3 (principal) propteries + value: value + name: name + weight: weight [5] + level: level [None] + ''' + + def __init__(self, value, name='', weight=5, level=None): + self.value = value + self.name = name + self.weight = weight + self.level = level + + def __repr__(self): + return '%s: %.4f * %d'%(self.name, self.value, weight) + + +class Manager: + '''Manager has 1 (principal) proptery + halls: halls + ''' + + def __init__(self, halls, movies=None, sorted=True): + self.halls = halls + for h in halls: + h.manager = self + self.movies = movies + if sorted: + self.halls.sort(key=lambda h:h.seatn, reverse=True) + if movies: + self.movies.sort(key=lambda h:h.hot, reverse=True) + N = sum(h.type_ for h in self.halls) + halln / 2 + for m in self.movies: + p = np.array([m.hot for m in self.movies]) + self.estimate = [int(k) for k in np.round(N * (p / np.sum(p)))] + # count seat taking + + s = np.sum(np.sqrt(h.seatn) for h in self.halls) + for h in self.halls: + h.seat_rate = np.sqrt(h.seatn) / s + + @staticmethod + def from_data(hall_data, movie_data=None): + if movies: + return Manager([Hall(id_, *propteries) for id_, propteries in hall_data.items()], [Movie(id_, *propteries) for id_, propteries in movie_data.items()]) + else: + return Manager([Hall(id_, *propteries) for id_, propteries in hall_data.items()]) + + @staticmethod + def from_db(lst): + return Manager([Hall.from_db(*args) for args in lst]) + + def insert_into(self, j, k, t=None): + if t is None: + for time in range(gapub): + flag = True + for kk, h in enumerate(self.halls): + if kk != k: + for m in h.movies: + if time == m.start: + flag = False + if flag: + t = time + self.halls[k].insert(0, self.movies[j].copy(), t) + + def count(self): + '''count movies + dict_ : {id_: number} + ''' + + dict_ = {} + S = 0 + for h in self.halls: + S += len(h.movies) + for m in h.movies: + if m.start <= h.last: + if m.id_ in dict_: + dict_[m.id_] += 1 + else: + dict_.update({m.id_:1}) + + for id_ in dict_: + dict_[id_] /= S + return dict_ + + def schedule(self, individual): + # individual.gmovies = {} + for k, h in enumerate(self.halls): + n = h.type_ + h.movies = [self.movies[i].copy() for i in individual[k][1:2*n:2]] + times = individual[k][:2*n-1:2] + h.movies[0].start = h.start + times[0] * 300 + for l, m in enumerate(h.movies[1:], start=1): + m.start = h.movies[l-1].end + (times[l]+1) * 300 + if m.start > h.last: + h.movies = h.movies[:l] + break + + # if m.isgolden(): + # individual.gmovies.update({k:l}) + + def initSchedule2(self, hook=list): + # minlen = min(m.length for m in self.movies) + individual = hook(list([] for _ in range(halln))) + # individual.gmovies = {} + lst = self.estimate.copy() + i = 0 + ts = np.random.permutation(len(self.halls)) + for k, h in enumerate(self.halls): + # golden period + h.movies = [self.movies[i].copy()] + h.movies[0].start = gtime - 75 * 60 + ts[k] * 300 + individual[k] = [i] + lst[i] -= 1 + if lst[i] == 0: + i += 1 + for k, h in enumerate(self.halls): + # common period + n = h.type_ + times = np.random.randint(0, gapub, size=n) + for l in range(1, n): + end = h.movies[0].start - (times[l]+1) * 300 + start = end - self.movies[i].length + if h.start <= start and end <= h.movies[0].start + 300: + h.movies.insert(0, self.movies[i].copy()) + h.movies[0].start = start + t = times[l] + while lst[i] <= 0: + i += 1 + individual[k] = [i, t] + individual[k] + lst[i] -= 1 + elif start < h.start: + gap = (h.movies[0].start - h.start)//300 + if gap <= gapub: + individual[k] = [gap] + individual[k] + else: + for j, m in enumerate(self.movies): + if gap * 300 - 300 * gapub <= m.length + 300 <= gap * 300 and lst[j] > 0: + h.movies.insert(0, m.copy()) + h.movies[0].end = h.movies[1].start - 300 + t0 = (h.movies[0].start - h.start)//300 + individual[k] = [t0, i, 1] + individual[k] + lst[j] -= 1 + break + else: + while lst[i] <= 0: + i += 1 + lst[i] -= 1 + t0 = randint(0, gapub-1) + individual[k] = [t0, i, 1] + individual[k] + h.movies[0].start = self.movies[i].length + 300 * (t0 +1) + h.movies.insert(0, self.movies[i].copy()) + h.movies[0].start = t0 * 300 + for l in range(1, len(h.movies)-1): + m, mm = self.movies[l], self.movies[l+1] + if m.end <= mm.start - 300: + break + else: + mm.start = m.end + 300 + individual[k][l*2+2] = 1 + break + + # if h.movies[-1].isgolden(): + # individual.gmovies.update({k:l}) + # break + + t = times[-1] + start = h.movies[-1].end + t * 300 + if start <= h.last: + while lst[i] <= 0: + i += 1 + h.movies.insert(0, self.movies[i].copy()) + h.movies[-1].start = start + individual[k] = individual[k] + [t, i] + lst[i] -= 1 + d = h.type_ - len(h.movies) + if d > 0: + for _ in range(d): + if h.movies[-1].end + 300 <= h.last: + h.append(self.movies[i].copy()) + individual[k] = individual[k] + [1, i] + elif d < 0: + individual[k] = individual[k][:2*d] + h.movies = h.movies[:d] + return individual + + def initSchedule1(self, hook=list): + # minlen = min(m.length for m in self.movies) + individual = hook(list([] for _ in range(halln))) + # individual.gmovies = {} + lst = self.estimate.copy() + i = 0 + ts = np.random.permutation(len(self.halls)) + for k, h in enumerate(self.halls): + # Arrange movies in prime time + h.movies = [self.movies[i].copy()] + h.movies[0].start = gtime - 75 * 60 + ts[k] * 300 + individual[k] = [i] + lst[i] -= 1 + if lst[i] == 0: + i += 1 + # Arrange movies in common time + n = h.type_ + times = np.random.randint(0, gapub, size=n) + for l in range(1, n): + end = h.movies[0].start - (times[l]+1) * 300 + start = end - self.movies[i].length + if h.start <= start and end <= h.movies[0].start + 300: + h.movies.insert(0, self.movies[i].copy()) + h.movies[0].start = start + t = times[l] + while lst[i] <= 0: + i += 1 + individual[k] = [i, t] + individual[k] + lst[i] -= 1 + elif start < h.start: + gap = (h.movies[0].start - h.start)//300 + if gap <= gapub: + individual[k] = [gap] + individual[k] + else: + for j, m in enumerate(self.movies): + if gap * 300 - 300 * gapub <= m.length + 300 <= gap * 300 and lst[j] > 0: + h.movies.insert(0, m.copy()) + h.movies[0].end = h.movies[1].start - 300 + t0 = (h.movies[0].start - h.start)//300 + individual[k] = [t0, i, 1] + individual[k] + lst[j] -= 1 + break + else: + while lst[i] <= 0: + i += 1 + lst[i] -= 1 + t0 = randint(0, gapub-1) + individual[k] = [t0, i, 1] + individual[k] + h.movies[0].start = self.movies[i].length + 300 * (t0 +1) + h.movies.insert(0, self.movies[i].copy()) + h.movies[0].start = t0 * 300 + for l in range(1, len(h.movies)-1): + m, mm = self.movies[l], self.movies[l+1] + if m.end <= mm.start - 300: + break + else: + mm.start = m.end + 300 + individual[k][l*2+2] = 1 + break + + # if h.movies[-1].isgolden(): + # individual.gmovies.update({k:l}) + # break + + t = times[-1] + start = h.movies[-1].end + t * 300 + if start <= h.last: + while lst[i] <= 0: + i += 1 + h.movies.insert(0, self.movies[i].copy()) + h.movies[-1].start = start + individual[k] = individual[k] + [t, i] + lst[i] -= 1 + d = h.type_ - len(h.movies) + if d > 0: + for _ in range(d): + if h.movies[-1].end + 300 <= h.last: + h.append(self.movies[i].copy()) + individual[k] = individual[k] + [1, i] + elif d < 0: + individual[k] = individual[k][:2*d] + h.movies = h.movies[:d] + return individual + + def initSchedule(self, hook=list): + if random() < .5: + return self.initSchedule1(hook) + else: + return self.initSchedule2(hook) + + def fitness(self): + return self.time_interval(), self.check_rate(), self.total_hot(), self.check_time() + + def check(self): + d1, d2 = self.check_interval() + print(''' +Minimum time interval: %.4f+%.4f; +Similarity between popularity and show times: %.4f; +Total popularity (prime time): %.4f(%.4f); +The number of full-screen movie halls: %d'''%(d1, d2, self.check_rate(), self.total_hot(), self.ghot(), self.check_time())) + + def print_fitness(self): + print('fitness: %.4f, %.4f, %.4f, %d'%(self.time_interval(), self.check_rate(), self.total_hot(), self.check_time())) + + def hot(self): + # total popularity + return sum(sum(m.hot for m in h.movies if m.start<=h.last) * h.seatn for h in self.halls) + + def ghot(self): + # prime time + hot = 0 + for h in self.halls: + for m in h.movies: + if m.isgolden(): + hot += m.hot * h.seatn + break + return hot + + def total_hot(self): + # Weighted popularity + return sum(sum(m.hot for m in h.movies if m.start<=h.last) * h.seatn for h in self.halls) + 3 * self.ghot() + + def check_time(self): + # check time-out + N = 0 + for h in self.halls: + if h.movies[-1].start <= h.last: + N +=1 + return N + + def check_rate(self): + """Popularity ~ Times ratio ~ Screening rate ~ Number ratio ~ Box office rate +The degree of similarity between the system recommended screening rate and the actual screening rate + """ + dict_ = self.count() + d = 0 + for id_, rate in dict_.items(): + d += abs(movies[id_][1]/S - rate) + return 1 / (d + 0.001) + + def check_interval(self): + # opening interval + d1s = [] + d2s = [] + for k, h in enumerate(self.halls[:-1]): + for hh in self.halls[k+1:]: + d1, d2 = h.dist(hh) + d1s.append(d1) + d2s.append(d2) + return min(d1s) / 60, min(d2s) / 60 + + def time_interval(self): + # opening interval + deltas = [] + for k, h in enumerate(self.halls[:-1]): + for hh in self.halls[k+1:]: + d1, d2 = h.dist(hh) + deltas.append((d1*0.5 + d2*0.5)) + delta = mymin(deltas) + + return delta / 60 + + def criterion1(self): + # Rationality of arranging movie screening halls(安排影片放映厅的合理性) + c = self.count() + alpha = 0 + for m in self.movies: + for k, h in enumerate(self.halls): + hc = h.count() + if m.id_ in hc and c[m.id_] < hc[m.id_] * 2: + alpha += abs(m.hot - h.seat_rate) + break + return alpha + + def criterion2(self): + # The degree of similarity between the system recommended screening rate and the actual screening rate(系统推荐排片率与实际排片率接近程度) + return self.check_rate() + + def criterion3(self): + # the number of movies shown during the prime time(黄金时间段放映电影数) + hot = 0 + for h in self.halls: + for m in h.movies[::-1]: + if m.isgolden(): + hot += 1 + break + return hot + + def criterion4(self): + # the most popular movie screened in the optimal hall during the prime time(最火的影片排入最优厅黄金时间段) + for m in self.halls[0].movies: + if m.id_ == self.movies[0].id_ and m.isgolden(): + return 1 + return 0 + + # def golden(self): + # c = {} + # for h in self.halls: + # for m in h: + # if m.isgolden(): + # if m.id_ in c: + # c[m.id_].append(m) + # else: + # c[m.id_] = [m] + # return c + + def criterion5(self): + return 1 + + def criterion6(self): + # Rationality of the interval between the opening of all movies in prime time (所有电影黄金时段开映间隔合理性) + times = np.sort([m.start for h in self.halls for m in h.movies if m.isgolden()]) + times = np.diff(times) + return 1 + + def criterion7(self): + # (所有电影非黄金时段开映间隔合理性) + times = np.sort([m.start for h in self.halls for m in h.movies if not m.isgolden()]) + times = np.diff(times) + return 1 + + def criterion8(self): + # (避免同时开场) + return 1 + + def criterion9(self): + # (高票房日子场间隔尽量短) + times = np.sort([m.start for h in self.halls for m in h.movies]) + return 1 + + def criterion10(self, latest='22'): + # (低热度动画片开映时间合理性) + n = 0 + for h in self.halls: + for m in hall: + if '动画' in m.type and m.hot < 1/halln and m.end > latest: + n += 1 + return n + + def criterion11(self, earliest='22'): + # (低热度动画片开映时间合理性) + n = 0 + for h in self.halls: + for m in hall: + if '恐怖' in m.type and m.hot < 0.5/halln and m.start < earliest: + n += 1 + return n + + def hasbighall(self): + return self.halls[0].seatn > self.halls[1].seatn * 1.5 + + def criterion12(self): + # Hall sharing status(大厅共用情况) + m, mm = self.movies[:2] + if self.hasbighall() and abs(m.hot - mm.hot) < 0.05: + gm = [m for m in self.halls[0].movies() if m.isgolden] + if set(m.id_ for m in gm) == {m.id_, mm.id_}: + return 1 + else: + return 0 + + + def criterion13(self): + # The richness of screening(影片排映丰富度) + if halln >= 6 and sum(m.hot for m in self.movies[:5])> .05: + return len(self.count()) + + + def criterion14(self, minhot=0.1): + # not popular movie (小片不在黄金时段) + n = 0 + for h in self.halls: + for m in h: + if m.isgolden() and m.hot < minhot: + n += 1 + return n + + def print_criterion(self): + for k in range(1, 13): + if k != 10 and k!=11: + print('criterion%d:'%k, getattr(self, 'criterion%d'%k)()) + + def dumps(self): + for h in self.halls: + h.dumps() + print() + + def stat(self): + dict_ = self.count() + for id_, rate in dict_.items(): + print(movies[id_][1]/100, rate) + + def plot(self, axes=None): + from matplotlib.ticker import FuncFormatter, MaxNLocator + if axes is None: + fig = plt.figure() + axes = fig.add_subplot(111) + axes.invert_yaxis() + + def format_fn(tick_val, tick_pos): + return stamp2str(tick_val) + axes.xaxis.set_major_formatter(FuncFormatter(format_fn)) + axes.xaxis.set_major_locator(MaxNLocator(integer=True)) + def format_fn(tick_val, tick_pos): + k = int(tick_val) + if k < len(self.halls): + h = self.halls[k] + return '%s(%d)'%(h.id_, h.seatn) + else: + return '' + axes.yaxis.set_major_formatter(FuncFormatter(format_fn)) + axes.yaxis.set_major_locator(MaxNLocator(integer=True)) + + H = len(self.halls) + for k, h in enumerate(self.halls): + for m in h.movies: + if m.hot > 0.2: + color = 'r' + elif m.hot > 0.15: + color = 'y' + elif m.hot > 0.1: + color = 'g' + elif m.hot > 0.05: + color = 'c' + else: + color = 'b' + axes.text(m.start, k, '%d'%m.id_) + axes.plot((m.start, m.end), (k, k), color=color, linestyle='-') + axes.plot((h.start, h.start), (k-1/2, k+1/2), color='k') + axes.plot((h.last, h.last), (k-1/2, k+1/2), color='k') + axes.plot((gtime-75*60, gtime-75*60), (0, H), color='y', linestyle='--') + axes.plot((gtime+75*60, gtime+75*60), (0, H), color='y', linestyle='--') + axes.set_xlabel('time') + axes.set_ylabel('hall') + axes.set_title('movie schedule') + plt.show() + + +manager = Manager.from_data(halls, movies) + + +from deap import tools + +def mutRandom(individual, indpb1, indpb2): + ts = np.random.permutation(gapub) + for k, hall in enumerate(individual): + hall[0] = ts[k] + for k, hall in enumerate(individual): + if random() < indpb1: + for i in range(1, len(hall), 2): + if random() < indpb2: + if random() < 0.7: + if hall[i] == 0: + hall[i] += 1 + else: + hall[i] -= 1 + else: + if hall[i] == movien: + hall[i] -= 1 + else: + hall[i] += 1 + + else: + for i in range(2, len(hall)-1, 2): + if random() < indpb2: + hall[i] = np.random.choice([t for t in range(gapub) if t != hall[i]]) + h = randint(0, halln-2) + if random() < 0.3: + individual[h], individual[h+1] = individual[h+1], individual[h] + else: + individual[h], individual[h+1] = tools.cxTwoPoint(individual[h+1], individual[h]) + return individual + + +from pyrimidine import BaseIndividual, HOFPopulation +from pyrimidine.deco import side_effect, fitness_cache + + +class Chromosome(list): + + def copy(self, type_=None): + return copy.deepcopy(self) + + def cross(self, other): + k = randint(1, len(self)-1) + return self.__class__(np.concatenate((self[:k], other[k:]), axis=0)) + + +@fitness_cache +class Individual(BaseIndividual): + + element_class = Chromosome + + @side_effect + def mutate(self): + self[:] = mutRandom(self, indpb1=0.15, indpb2=0.8) + + def cross(self, other): + s1 = set(h[0] for h in self) + s2 = set(h[0] for h in other) + if random() > 1/(len(s1.symmetric_difference(s2))+1): + return super().cross(other) + else: + return self.copy() + + def _fitness(self): + manager.schedule(self) + return np.dot((50, 20, 2, 1), manager.fitness()) + + +Population = HOFPopulation[Individual] + +if __name__ == '__main__': + + pop = Population([manager.initSchedule() for _ in range(50)]) + pop.evolve() + ind = pop.best_individual + + manager.schedule(ind) + manager.print_fitness() + + manager.check() + manager.dumps() + manager.plot() + manager.print_criterion() diff --git a/logo-ai.png b/logo-ai.png index 18657e0..5c0f590 100644 Binary files a/logo-ai.png and b/logo-ai.png differ diff --git a/paper/paper.md b/paper/paper.md index 6ff3af1..b6e336a 100644 --- a/paper/paper.md +++ b/paper/paper.md @@ -201,7 +201,7 @@ UserPopulation = StandardPopulation[BinaryChromosome // n].set_fitness(_evaluate Then we execute the evolutionary program as follows. ```python pop = UserPopulation.random() -pop.evolve(n_iter=100) +pop.evolve(max_iter=100) ``` Finally, the optimal individual can be obtained with `pop.best_individual`, or `pop.solution` to decode the individual to the solution of the problem. @@ -219,7 +219,7 @@ stat = {'Mean Fitness': 'mean_fitness', } # obtain the statistical results through the evolution. -data = pop.evolve(stat=stat, n_iter=100, history=True) +data = pop.evolve(stat=stat, max_iter=100, history=True) ``` `data` is an `pandas.DataFrame` object, with the columns "Mean Fitness", "Best Fitness" and "Standard Deviation of Fitnesses". Now utilize the `plot` method of the object (or the Python library `matplotlib`) to show the iteration history \autoref{history}. diff --git a/pyrimidine/__init__.py b/pyrimidine/__init__.py index e17b633..1e97a3d 100755 --- a/pyrimidine/__init__.py +++ b/pyrimidine/__init__.py @@ -58,7 +58,7 @@ class MyPopulation(HOFPopulation): stat={'Mean Fitness': 'fitness', 'Best Fitness': 'max_fitness', 'Standard Deviation of Fitnesses': 'std_fitness'} -data = pop.evolve(stat=stat, n_iter=200, history=True) +data = pop.evolve(stat=stat, max_iter=200, history=True) import matplotlib.pyplot as plt diff --git a/pyrimidine/aco.py b/pyrimidine/aco.py index d7e18d8..143e377 100644 --- a/pyrimidine/aco.py +++ b/pyrimidine/aco.py @@ -84,7 +84,7 @@ class BaseAntColony(PopulationMixin, metaclass=MetaContainer): element_class = BaseAnt params = {'sedimentation':100, 'volatilization':0.75, 'alpha':1, 'beta':5, 'n_steps':1, - 'reset_rate': 0.3, 'local_n_iter': 3, 'move_rate':0.5} + 'reset_rate': 0.3, 'local_max_iter': 3, 'move_rate':0.5} alias = {"ants": "elements", "worst_ant": "worst_element", "get_worst_ants": "get_worst_elements"} @@ -109,7 +109,7 @@ def from_distances(cls, n_ants=10, distances=None): def transition(self, *args, **kwargs): - for _ in range(self.local_n_iter) + for _ in range(self.local_max_iter) self.move(n_steps=self.n_steps) self.update_pheromone() if not any(ant.move_flag for ant in self): diff --git a/pyrimidine/base.py b/pyrimidine/base.py index e083841..fb22fc4 100755 --- a/pyrimidine/base.py +++ b/pyrimidine/base.py @@ -398,14 +398,14 @@ def mate_with(self, other, mate_prob=None): return offspring @side_effect - def local_search(self, n_iter=2, *args, **kwargs): + def local_search(self, max_iter=2, *args, **kwargs): """Call local searching method By default, it calls the `ezolve` methods of individuals, iteratively """ for individual in self: - individual.ezolve(n_iter=n_iter or self.n_iter, init=False) + individual.ezolve(max_iter=max_iter or self.max_iter, init=False) def get_rank(self, individual): """Get rank of one individual diff --git a/pyrimidine/gsa.py b/pyrimidine/gsa.py index 0e9b832..6eeed23 100644 --- a/pyrimidine/gsa.py +++ b/pyrimidine/gsa.py @@ -115,7 +115,7 @@ def transition(self, k): """ self.compute_accelerate() self.move() - self.gravity_coefficient = exp(-self.attenuation_coefficient*k / self.n_iter) + self.gravity_coefficient = exp(-self.attenuation_coefficient*k / self.max_iter) def move(self): for particle in self: diff --git a/pyrimidine/learn/__init__.py b/pyrimidine/learn/__init__.py index a885443..db9c08c 100755 --- a/pyrimidine/learn/__init__.py +++ b/pyrimidine/learn/__init__.py @@ -33,7 +33,7 @@ def fit(self, X, Y=None, pop=None, warm_start=False): return self def _fit(self): - self.pop.ezolve(n_iter=self.max_iter) + self.pop.ezolve(max_iter=self.max_iter) model_ = self.pop.solution for k in self.estimated_params: setattr(self, k, getattr(model_, k)) diff --git a/pyrimidine/mixin.py b/pyrimidine/mixin.py index 4c2bf07..bc02ae0 100755 --- a/pyrimidine/mixin.py +++ b/pyrimidine/mixin.py @@ -37,7 +37,7 @@ class IterativeMixin: # Mixin class for iterative algrithms - params = {'n_iter': 100} + params = {'max_iter': 100} # @property # def _row(self): @@ -62,19 +62,19 @@ def local_search(self, *args, **kwargs): """ raise NotImplementedError('If you apply a local search algorithm, you must define the `local_search` method.') - def ezolve(self, n_iter=None, init=True): + def ezolve(self, max_iter=None, init=True): # Extreamly eazy evolution method for lazybones - n_iter = n_iter or self.n_iter + max_iter = max_iter or self.max_iter if init: self.init() - for k in range(1, n_iter+1): + for k in range(1, max_iter+1): self.transition(k) - def evolve(self, initialize:bool=True, n_iter:int=100, period:int=1, verbose:bool=False, history=False, stat=None, attrs=('solution',), control=None): + def evolve(self, initialize:bool=True, max_iter:int=100, period:int=1, verbose:bool=False, history=False, stat=None, attrs=('solution',), control=None): """Get the history of the whole evolution Keyword Arguments: - n_iter {number} -- number of iterations (default: {None}) + max_iter {number} -- number of iterations (default: {None}) period {integer} -- the peroid of stat verbose {bool} -- to print the iteration process stat {dict} -- a dict(key: function mapping from the object to a number) of statistics @@ -88,7 +88,7 @@ def evolve(self, initialize:bool=True, n_iter:int=100, period:int=1, verbose:boo assert control is None or callable(control) - n_iter = n_iter or self.n_iter + max_iter = max_iter or self.max_iter if isinstance(stat, dict): stat = Statistics(stat) @@ -105,30 +105,35 @@ def evolve(self, initialize:bool=True, n_iter:int=100, period:int=1, verbose:boo history_flag = True else: raise TypeError('The argument `history` should be an instance of `pandas.DataFrame` or `bool`.') - # n_iter = n_iter or self.n_iter + if verbose: + def _row(t, attrs, res, sep=" & "): + return f'{sep.join(map(str, concat((("[%d]"%t,), (getattr(self, attr) for attr in attrs), res.values()))))}' from toolz.itertoolz import concat if not history_flag: res = stat(self) - print(f""" + print(f""" ** History ** {" & ".join(concat((("iteration",), attrs, res.keys())))} -------------------------------------------------------------- -{" & ".join(map(str, concat((("[0]",), (getattr(self, attr) for attr in attrs), res.values()))))}""") +-------------------------------------------------------------""") + print(_row(0, attrs, res)) - for t in range(1, n_iter+1): + for t in range(1, max_iter+1): self.transition(t) + if history_flag and (period == 1 or t % period ==0): res = stat(self) history = pd.concat([history, pd.Series(res.values(), index=res.keys()).to_frame().T], ignore_index=True) + if verbose and (period == 1 or t % period ==0): - print(f'{" & ".join(map(str, concat((("[%d]"%t,), (getattr(self, attr) for attr in attrs), res.values()))))}') + print(_row(t, attrs, res)) if control: if control(self): - # if it satisfies the control condition + # if it satisfies the control condition (such as convergence criterion) break + return history def perf(self, n_repeats=10, timing=True, *args, **kwargs): @@ -351,7 +356,7 @@ def observe(self, name='_system'): @property def op(self): - class _C + class _C: def __getitem__(obj, s): def _f(*args, **kwargs): return getattr(self._system, s)(self, *args, **kwargs) diff --git a/pyrimidine/population.py b/pyrimidine/population.py index ed62cfd..647430f 100755 --- a/pyrimidine/population.py +++ b/pyrimidine/population.py @@ -186,7 +186,7 @@ class LocalSearchPopulation(StandardPopulation): # def init(self): # for i in self: - # i.n_iter = self.n_local_iter + # i.max_iter = self.n_local_iter def transition(self, *args, **kwargs): """Transitation of the states of population @@ -194,7 +194,7 @@ def transition(self, *args, **kwargs): Calling `local_search` method """ super().transition(*args, **kwargs) - self.local_search(n_iter=self.n_local_iter) + self.local_search(max_iter=self.n_local_iter) class ModifiedPopulation(StandardPopulation): diff --git a/pyrimidine/sma.py b/pyrimidine/sma.py index 7d7c4f0..c3f42b6 100755 --- a/pyrimidine/sma.py +++ b/pyrimidine/sma.py @@ -36,7 +36,7 @@ class SlimeMould(HOFPopulation): element_class = SlimyMaterial params = { - "n_iter": 100 + "max_iter": 100 } def get_ranks(self): @@ -48,7 +48,7 @@ def get_ranks(self): def approach_food(self, t): N = len(self) # calculate vc and a - vc = 1 - t/self.n_iter + vc = 1 - t/self.max_iter a = np.arctanh(vc) # all fitness, max/min fitness all_fitness = self.get_all_fitness() diff --git a/tests/test_de.py b/tests/test_de.py index 4f54e22..5036047 100644 --- a/tests/test_de.py +++ b/tests/test_de.py @@ -42,8 +42,8 @@ def test_evolve(self, example2): self.population1 = P1.random() self.population2 = P2.random() stat = {'Mean Fitness':'mean_fitness', 'Best Fitness':'max_fitness'} - data1 = self.population1.evolve(stat=stat, n_iter=3, history=True) - data2 = self.population2.evolve(stat=stat, n_iter=3, history=True) + data1 = self.population1.evolve(stat=stat, max_iter=3, history=True) + data2 = self.population2.evolve(stat=stat, max_iter=3, history=True) assert ('Mean Fitness' in data1.columns and 'Best Fitness' in data1.columns and 'Mean Fitness' in data2.columns and 'Best Fitness' in data2.columns) assert len(data1) == len(data2) == 4 diff --git a/tests/test_ga.py b/tests/test_ga.py index 2f82fc3..b444906 100644 --- a/tests/test_ga.py +++ b/tests/test_ga.py @@ -14,21 +14,21 @@ def test_merge(self, example): def test_evolve(self, example): ExamplePopulation, _ = example population = ExamplePopulation.random() - population.evolve(n_iter=2) + population.evolve(max_iter=2) assert True def test_stat(self, example): ExamplePopulation, _ = example population = ExamplePopulation.random() stat = {'Mean Fitness': 'mean_fitness', 'Best Fitness': 'max_fitness'} - data = population.evolve(stat=stat, n_iter=3, history=True) + data = population.evolve(stat=stat, max_iter=3, history=True) assert ('Mean Fitness' in data.columns) and ('Best Fitness' in data.columns) assert len(data) == 4 def test_stat_default(self, example): ExamplePopulation, _ = example population = ExamplePopulation.random() - data = population.evolve(n_iter=3, history=True) + data = population.evolve(max_iter=3, history=True) assert ('Mean Fitness' in data.columns) and ('Best Fitness' in data.columns) assert len(data) == 4 @@ -38,7 +38,7 @@ def test_hof(self, example): population = NewPopulation.random() stat = {'Best Fitness': 'max_fitness'} - data = population.evolve(stat=stat, n_iter=5, history=True) + data = population.evolve(stat=stat, max_iter=5, history=True) def increasing(x): return all(xi <= xj for xi, xj in zip(x[:-1], x[1:])) diff --git a/tests/test_sa.py b/tests/test_sa.py index 778a94c..d6818a9 100644 --- a/tests/test_sa.py +++ b/tests/test_sa.py @@ -35,6 +35,6 @@ class TestSA: def test_evolve(self, example): I = example self.individual = I.random() - data = self.individual.evolve(n_iter=3, history=True) + data = self.individual.evolve(max_iter=3, history=True) assert len(data) == 4