Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit6403ad3

Browse files
committed
streamline and documentation
1 parent83a0400 commit6403ad3

File tree

6 files changed

+307
-100
lines changed

6 files changed

+307
-100
lines changed

‎README.md‎

Lines changed: 208 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,20 @@ Now featuring AntennaCAT hooks for GUI integration and user input handling.
99
*[Chicken Swarm Optimization](#chicken-swarm-optimization)
1010
*[Requirements](#requirements)
1111
*[Implementation](#implementation)
12+
*[Initialization](#initialization)
13+
*[State Machine-based Structure](#state-machine-based-structure)
1214
*[Constraint Handling](#constraint-handling)
1315
*[Boundary Types](#boundary-types)
1416
*[Multi-Object Optimization](#multi-object-optimization)
1517
*[Objective Function Handling](#objective-function-handling)
18+
*[Creating a Custom Objective Function](#creating-a-custom-objective-function)
1619
*[Internal Objective Function Example](internal-objective-function-example)
1720
*[Examples](#example-implementations)
1821
*[Basic PSO Example](#basic-pso-example)
1922
*[Detailed Messages](#detailed-messages)
2023
*[Realtime Graph](#realtime-graph)
2124
*[References](#references)
22-
*[Publications andIntegration](#publications-and-integration)
25+
*[RelatedPublications andRepositories](#related-publications-and-repositories)
2326
*[Licensing](#licensing)
2427

2528
##Chicken Swarm Optimization
@@ -41,8 +44,7 @@ In CSO, there is an absence of a direct random velocity component, which is an i
4144
Chicks follow their mother hens. They update their positions based on their mother's positions with some random factor to simulate the dependent behavior.
4245

4346
##Requirements
44-
45-
This project requires numpy and matplotlib.
47+
This project requires numpy, pandas, and matplotlib for the full demos. To run the optimizer without visualization, only numpy and pandas are requirements
4648

4749
Use 'pip install -r requirements.txt' to install the following dependencies:
4850

@@ -55,15 +57,139 @@ kiwisolver==1.4.5
5557
matplotlib==3.8.4
5658
numpy==1.26.4
5759
packaging==24.0
60+
pandas==2.2.3
5861
pillow==10.3.0
5962
pyparsing==3.1.2
6063
python-dateutil==2.9.0.post0
64+
pytz==2025.1
6165
six==1.16.0
66+
tzdata==2025.1
6267
zipp==3.18.1
6368

6469
```
6570

71+
Optionally, requirements can be installed manually with:
72+
73+
```python
74+
pip install matplotlib, numpy, pandas
75+
76+
```
77+
This is an example for if you've had a difficult time with the requirements.txt file. Sometimes libraries are packaged together.
78+
6679
##Implementation
80+
81+
###Initialization
82+
83+
```python
84+
# swarm variables
85+
TOL=10**-6# Convergence Tolerance
86+
MAXIT=10000# Maximum allowed iterations
87+
BOUNDARY=1# int boundary 1 = random, 2 = reflecting
88+
# 3 = absorbing, 4 = invisible
89+
90+
91+
# Objective function dependent variables
92+
LB= func_configs.LB# Lower boundaries, [[0.21, 0, 0.1]]
93+
UB= func_configs.UB# Upper boundaries, [[1, 1, 0.5]]
94+
IN_VARS= func_configs.IN_VARS# Number of input variables (x-values)
95+
OUT_VARS= func_configs.OUT_VARS# Number of output variables (y-values)
96+
TARGETS= func_configs.TARGETS# Target values for output
97+
98+
# Objective function dependent variables
99+
func_F= func_configs.OBJECTIVE_FUNC# objective function
100+
constr_F= func_configs.CONSTR_FUNC# constraint function
101+
102+
103+
# chicken swarm specific
104+
RN=10# Total number of roosters
105+
HN=20# Total number of hens
106+
MN=15# Number of mother hens in total hens
107+
CN=20# Total number of chicks
108+
G=70# Reorganize groups every G steps
109+
110+
# swarm setup
111+
best_eval=1
112+
113+
parent=None# for the PSO_TEST ONLY
114+
115+
suppress_output=True# Suppress the console output of particle swarm
116+
117+
allow_update=True# Allow objective call to update state
118+
119+
# Constant variables
120+
opt_params= {'BOUNDARY': [BOUNDARY],# int boundary 1 = random, 2 = reflecting
121+
# 3 = absorbing, 4 = invisible
122+
'RN': [RN],# Total number of roosters
123+
'HN': [HN],# Total number of hens
124+
'MN': [MN],# Number of mother hens in total hens
125+
'CN': [CN],# Total number of chicks
126+
'G': [G]}# Reorganize groups every G steps
127+
128+
opt_df= pd.DataFrame(opt_params)
129+
mySwarm= swarm(LB,UB,TARGETS,TOL,MAXIT,
130+
func_F, constr_F,
131+
opt_df,
132+
parent=parent)
133+
134+
# arguments should take the form:
135+
# swarm([[float, float, ...]], [[float, float, ...]], [[float, ...]], float, int,
136+
# func, func,
137+
# dataFrame,
138+
# class obj)
139+
#
140+
# opt_df contains class-specific tuning parameters
141+
# boundary: int. 1 = random, 2 = reflecting, 3 = absorbing, 4 = invisible
142+
# RN: int
143+
# HN: int
144+
# MN: int
145+
# CN: int
146+
# G: int
147+
#
148+
149+
```
150+
151+
###State Machine-based Structure
152+
153+
This optimizer uses a state machine structure to control the movement of the particles, call to the objective function, and the evaluation of current positions. The state machine implementation preserves the initial algorithm while making it possible to integrate other programs, classes, or functions as the objective function.
154+
155+
A controller with a`while loop` to check the completion status of the optimizer drives the process. Completion status is determined by at least 1) a set MAX number of iterations, and 2) the convergence to a given target using the L2 norm. Iterations are counted by calls to the objective function.
156+
157+
Within this`while loop` are three function calls to control the optimizer class:
158+
***complete**: the`complete function` checks the status of the optimizer and if it has met the convergence or stop conditions.
159+
***step**: the`step function` takes a boolean variable (suppress_output) as an input to control detailed printout on current particle (or agent) status. This function moves the optimizer one step forward.
160+
***call_objective**: the`call_objective function` takes a boolean variable (allow_update) to control if the objective function is able to be called. In most implementations, this value will always be true. However, there may be cases where the controller or a program running the state machine needs to assert control over this function without stopping the loop.
161+
162+
Additionally,**get_convergence_data** can be used to preview the current status of the optimizer, including the current best evaluation and the iterations.
163+
164+
The code below is an example of this process:
165+
166+
```python
167+
whilenot myOptimizer.complete():
168+
# step through optimizer processing
169+
# this will update particle or agent locations
170+
myOptimizer.step(suppress_output)
171+
# call the objective function, control
172+
# when it is allowed to update and return
173+
# control to optimizer
174+
myOptimizer.call_objective(allow_update)
175+
# check the current progress of the optimizer
176+
# iter: the number of objective function calls
177+
# eval: current 'best' evaluation of the optimizer
178+
iter,eval= myOptimizer.get_convergence_data()
179+
if (eval< best_eval)and (eval!=0):
180+
best_eval=eval
181+
182+
# optional. if the optimizer is not printing out detailed
183+
# reports, preview by checking the iteration and best evaluation
184+
185+
if suppress_output:
186+
ifiter%100==0:#print out every 100th iteration update
187+
print("Iteration")
188+
print(iter)
189+
print("Best Eval")
190+
print(best_eval)
191+
```
192+
67193
###Constraint Handling
68194
Users must create their own constraint function for their problems, if there are constraints beyond the problem bounds. This is then passed into the constructor. If the default constraint function is used, it always returns true (which means there are no constraints).
69195

@@ -75,8 +201,77 @@ Some updates have not incorporated appropriate handling for all boundary conditi
75201
###Multi-Object Optimization
76202
The no preference method of multi-objective optimization, but a Pareto Front is not calculated. Instead the best choice (smallest norm of output vectors) is listed as the output.
77203

204+
78205
###Objective Function Handling
79-
The optimizer minimizes the absolute value of the difference from the target outputs and the evaluated outputs. Future versions may include options for function minimization absent target values.
206+
The optimizer minimizes the absolute value of the difference of the target outputs and the evaluated outputs. Future versions may include options for function minimization when target values are absent.
207+
208+
####Creating a Custom Objective Function
209+
210+
Custom objective functions can be used by creating a directory with the following files:
211+
* configs_F.py
212+
* constr_F.py
213+
* func_F.py
214+
215+
`configs_F.py` contains lower bounds, upper bounds, the number of input variables, the number of output variables, the target values, and a global minimum if known. This file is used primarily for unit testing and evaluation of accuracy. If these values are not known, or are dynamic, then they can be included experimentally in the controller that runs the optimizer's state machine.
216+
217+
`constr_F.py` contains a function called`constr_F` that takes in an array,`X`, of particle positions to determine if the particle or agent is in a valid or invalid location.
218+
219+
`func_F.py` contains the objective function,`func_F`, which takes two inputs. The first input,`X`, is the array of particle or agent positions. The second input,`NO_OF_OUTS`, is the integer number of output variables, which is used to set the array size. In included objective functions, the default value is hardcoded to work with the specific objective function.
220+
221+
Below are examples of the format for these files.
222+
223+
`configs_F.py`:
224+
```python
225+
OBJECTIVE_FUNC= func_F
226+
CONSTR_FUNC= constr_F
227+
OBJECTIVE_FUNC_NAME="one_dim_x_test.func_F"#format: FUNCTION NAME.FUNCTION
228+
CONSTR_FUNC_NAME="one_dim_x_test.constr_F"#format: FUNCTION NAME.FUNCTION
229+
230+
# problem dependent variables
231+
LB= [[0]]# Lower boundaries
232+
UB= [[1]]# Upper boundaries
233+
IN_VARS=1# Number of input variables (x-values)
234+
OUT_VARS=1# Number of output variables (y-values)
235+
TARGETS= [0]# Target values for output
236+
GLOBAL_MIN= []# Global minima sample, if they exist.
237+
238+
```
239+
240+
`constr_F.py`, with no constraints:
241+
```python
242+
defconstr_F(x):
243+
F=True
244+
return F
245+
```
246+
247+
`constr_F.py`, with constraints:
248+
```python
249+
defconstr_F(X):
250+
F=True
251+
# objective function/problem constraints
252+
if (X[2]> X[0]/2)or (X[2]<0.1):
253+
F=False
254+
return F
255+
```
256+
257+
`func_F.py`:
258+
```python
259+
import numpyas np
260+
import time
261+
262+
deffunc_F(X,NO_OF_OUTS=1):
263+
F= np.zeros((NO_OF_OUTS))
264+
noErrors=True
265+
try:
266+
x= X[0]
267+
F= np.sin(5* x**3)+ np.cos(5* x)* (1- np.tanh(x**2))
268+
exceptExceptionas e:
269+
print(e)
270+
noErrors=False
271+
272+
return [F], noErrors
273+
```
274+
80275

81276
####Internal Objective Function Example
82277

@@ -94,9 +289,9 @@ Each function has four files in a directory:
94289
Other multi-objective functions can be applied to this project by following the same format (and several have been collected into a compatible library, and will be released in a separate repo)
95290

96291
<palign="center">
97-
<img src="https://github.com/LC-Linkous/chicken_swarm_python/blob/main/media/himmelblau_plots.png" alt="Himmelblau function" height="250">
292+
<img src="media/himmelblau_plots.png" alt="Himmelblau’s function" height="250">
98293
</p>
99-
<palign="center">Plotted Himmelblau Function with 3D Plot on the Left, and a 2D Contour on the Right</p>
294+
<palign="center">Plotted Himmelblau’s Function with 3D Plot on the Left, and a 2D Contour on the Right</p>
100295

101296
```math
102297
f(x, y) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2
@@ -109,10 +304,8 @@ f(x, y) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2
109304
| f(-3.779310, -3.283186) = 0| $-5 \leq x,y \leq 5$||
110305
| f(3.584428, -1.848126) = 0| $-5 \leq x,y \leq 5$||
111306

112-
113-
114307
<palign="center">
115-
<img src="https://github.com/LC-Linkous/chicken_swarm_python/blob/main/media/obj_func_pareto.png" alt="Function Feasible Decision Space and Objective Space with Pareto Front" height="200">
308+
<img src="media/obj_func_pareto.png" alt="Function Feasible Decision Space and Objective Space with Pareto Front" height="200">
116309
</p>
117310
<palign="center">Plotted Multi-Objective Function Feasible Decision Space and Objective Space with Pareto Front</p>
118311

@@ -128,9 +321,8 @@ f_{2}(\mathbf{x}) = (x_3-0.2)^4
128321
|----------|----------|----------|
129322
| 3| $0.21\leq x_1\leq 1$ <br> $0\leq x_2\leq 1$ <br> $0.1 \leq x_3\leq 0.5$| $x_3\gt \frac{x_1}{2}$ or $x_3\lt 0.1$|
130323

131-
132324
<palign="center">
133-
<img src="https://github.com/LC-Linkous/chicken_swarm_python/blob/main/media/1D_test_plots.png" alt="Function Feasible Decision Space and Objective Space with Pareto Front" height="200">
325+
<img src="media/1D_test_plots.png" alt="Function Feasible Decision Space and Objective Space with Pareto Front" height="200">
134326
</p>
135327
<palign="center">Plotted Single Input, Single-objective Function Feasible Decision Space and Objective Space with Pareto Front</p>
136328

@@ -145,33 +337,31 @@ Local minima at $(0.444453, -0.0630916)$
145337

146338
Global minima at $(0.974857, -0.954872)$
147339

148-
149340
##Example Implementations
150341

151342
###Basic Swarm Example
152-
main_test.py provides a sample use case of the optimizer.
343+
`main_test.py` provides a sample use case of the optimizer.
153344

154345
###Detailed Messages
155-
main_test_details.py provides an example using a parent class, and the self.suppress_outputand detailedWarnings flags to control error messages that are passed back to the parent class to be printed with a timestamp. This implementation sets up the hooks for integration with AntennaCAT in order to provide the user feedback of warnings and errors.
346+
`main_test_details.py` provides an example using a parent class, and the self.suppress_outputflag to control error messages that are passed back to the parent class to be printed with a timestamp. This implementation sets up the hooks for integration with AntennaCAT in order to provide the user feedback of warnings and errors.
156347

157348
###Realtime Graph
158349

159350
<palign="center">
160-
<img src="https://github.com/LC-Linkous/chicken_swarm_python/blob/main/media/chicken_swarm.gif" alt="Example Chicken Swarm Optimizer" height="200">
351+
<img src="media/chicken_swarm.gif" alt="Example Chicken Swarm Optimizer" height="200">
161352
</p>
162353

163-
main_test_graph.py provides an example using a parent class, and the self.suppress_outputand detailedWarnings flags to control error messages that are passed back to the parent class to be printed with a timestamp. Additionally, a realtime graph shows particle locations at every step.
354+
`main_test_graph.py` provides an example using a parent class, and the self.suppress_outputflag to control error messages that are passed back to the parent class to be printed with a timestamp. Additionally, a realtime graph shows particle locations at every step.
164355

165356
NOTE: if you close the graph as the code is running, the code will continue to run, but the graph will not re-open.
166357

167358
##References
168359

169360
[1] X. B. Meng, Y. Liu, X. Gao, and H. Zhang, "A new bio-inspired algorithm: Chicken swarm optimization," in Proc. Int. Conf. Swarm Intell. Cham, Switzerland, Springer, 2014, pp. 86–94.
170361

171-
##Publications andIntegration
362+
##RelatedPublications andRepositories
172363
This software works as a stand-alone implementation, and as one of the optimizers integrated into AntennaCAT.
173364

174-
Publications featuring the code in this repo will be added as they become public.
175365

176366
##Licensing
177367

‎requirements.txt‎

90 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp