蚁群算法简介

蚁群算法是群智能算法的一种,所谓的群智能是一种由无智能或简单智能的个体通过任何形式的聚集协同而表现出智能行为,它为在没有集中控制且不提供全局模型的前提下寻找复杂的分布式问题求解方案提供了基础,比如常见的蚂蚁觅食,大雁南飞等行为。蚁群算法是模拟自然界中蚂蚁觅食的一种随机搜索算法,由Dorigo等人于1991年在第一届欧洲人工生命会议上提出[1]

蚁群算法的生物原理

通过观察发现,蚁群在觅食的时候,总能找到一条从蚁巢到食物之间的一条最短的路径。这个现象引起了生物学家的注意,根据研究,原来是蚂蚁在行进的过程中,会分泌一种化学物质——信息素,而蚂蚁在行进时,总是倾向于选择信息素浓度比较高的路线。这样,在蚁巢和食物之间假如有多条路径,初始的时候,每条路径上都会有蚂蚁爬过,但是随着时间的推迟,单位时间内最短的那条路上爬过的蚂蚁数量会比较多,释放的信息素就相对来说比较多,那么以后蚂蚁选择的时候会大部分都选择信息素比较多的路径,从而会把最短路径找出来。

蚁群算法正是模拟这种蚁群觅食的原理,构造人工蚂蚁,用来求解许多组合优化问题。

有关蚁群算法的详细信息,可参考[2]——[5]。

蚁群算法的JAVA实现

我个人认为利用JAVA编写一些计算密集型的算法不是一个好的选择。本身一些算法是要要求高效率的,但是我感觉JAVA语言的性能不够,所以编写算法最好用c,其次也可以用c++。当然,这仅是一家之言,欢迎拍砖。

此处使用JAVA的原因是为了演示算法的框架,给出一种思路,如果需要c++的参考,可以参考 http://fashionxu.blogchina.com,如果需要c的代码,可以上 http://iridia.ulb.ac.be/~mdorigo/ACO/ACO.html, 这个可以看作是ACO的官方网站了,里面的内容比较多。

算法说明

算法以求解TSP问题为例,用来演示ACO的框架。

算法设定了两个类,一个是ACO,用来处理文件信息的读入,信息素的更新,路径的计算等;另一个是ant,即蚂蚁的信息。

算法中用到的数据,可以从TSPLib 上面下载,使用的是对称TSP数据,为了简化算法的代码,下载下来的数据需要做一个简单处理,即把TSP文件中除去城市节点信息部分之外的内容都删除掉,然后在文件首插入一行,写入此文件包含的城市的数目,以att48.tsp为例,下载下来的文件内容如下:

NAME : att48
 COMMENT : 48 capitals of the US (Padberg/Rinaldi)
 TYPE : TSP
 DIMENSION : 48
 EDGE_WEIGHT_TYPE : ATT
 NODE_COORD_SECTION
 1 6734 1453
 2 2233 10
 3 5530 1424
 4 401 841
 5 3082 1644
 6 7608 4458
 7 7573 3716
 8 7265 1268
 9 6898 1885
 10 1112 2049
 11 5468 2606
 12 5989 2873
 13 4706 2674
 14 4612 2035
 15 6347 2683
 16 6107 669
 17 7611 5184
 18 7462 3590
 19 7732 4723
 20 5900 3561
 21 4483 3369
 22 6101 1110
 23 5199 2182
 24 1633 2809
 25 4307 2322
 26 675 1006
 27 7555 4819
 28 7541 3981
 29 3177 756
 30 7352 4506
 31 7545 2801
 32 3245 3305
 33 6426 3173
 34 4608 1198
 35 23 2216
 36 7248 3779
 37 7762 4595
 38 7392 2244
 39 3484 2829
 40 6271 2135
 41 4985 140
 42 1916 1569
 43 7280 4899
 44 7509 3239
 45 10 2676
 46 6807 2993
 47 5185 3258
 48 3023 1942
 EOF修改之后,内容变为如下:
 
48
 1 6734 1453
 2 2233 10
 3 5530 1424
 4 401 841
 5 3082 1644
 6 7608 4458
 7 7573 3716
 8 7265 1268
 9 6898 1885
 10 1112 2049
 11 5468 2606
 12 5989 2873
 13 4706 2674
 14 4612 2035
 15 6347 2683
 16 6107 669
 17 7611 5184
 18 7462 3590
 19 7732 4723
 20 5900 3561
 21 4483 3369
 22 6101 1110
 23 5199 2182
 24 1633 2809
 25 4307 2322
 26 675 1006
 27 7555 4819
 28 7541 3981
 29 3177 756
 30 7352 4506
 31 7545 2801
 32 3245 3305
 33 6426 3173
 34 4608 1198
 35 23 2216
 36 7248 3779
 37 7762 4595
 38 7392 2244
 39 3484 2829
 40 6271 2135
 41 4985 140
 42 1916 1569
 43 7280 4899
 44 7509 3239
 45 10 2676
 46 6807 2993
 47 5185 3258
 48 3023 1942

 

这么做仅是为了方便处理,也可以根据TSPLib给出的文件格式而自己写代码读取。

算法流程图

此处实现的算法应该是AS(Ant System),其算法流程如下:


 

 

 

 

算法代码

package tspsolver;
import java.util.Random;
/**
 *蚂蚁类
 * @author FashionXu
 */
public class ant {
    /**
     * 蚂蚁获得的路径
     */
    public int[]tour;
    //unvisitedcity 取值是0或1,
    //1表示没有访问过,0表示访问过
    int[] unvisitedcity;
    /**
     * 蚂蚁获得的路径长度
     */
    public int tourlength;
    int citys;
/**
 * 随机分配蚂蚁到某个城市中
 * 同时完成蚂蚁包含字段的初始化工作
 * @param citycount 总的城市数量
 */
    public void RandomSelectCity(int citycount){
        citys=citycount;
        unvisitedcity=new int[citycount];
        tour=new int[citycount+1];
        tourlength=0;
        for(int i=0;i<citycount;i++){
            tour[i]=-1;
            unvisitedcity[i]=1;
        }
        long r1 = System.currentTimeMillis();
        Random rnd=new Random(r1);
        int firstcity=rnd.nextInt(citycount);
        unvisitedcity[firstcity]=0;
        tour[0]=firstcity;
    }
    /**
     * 选择下一个城市
     * @param index 需要选择第index个城市了
     * @param tao   全局的信息素信息
     * @param distance  全局的距离矩阵信息
     */
    public void SelectNextCity(int index,double[][]tao,int[][]distance){
        double []p;
        p=new double[citys];
        double alpha=1.0;
        double beta=2.0;
        double sum=0;
        int currentcity=tour[index-1];
        //计算公式中的分母部分
        for(int i=0;i<citys;i++){
            if(unvisitedcity[i]==1)
                sum+=(Math.pow(tao[currentcity][i], alpha)*
                        Math.pow(1.0/distance[currentcity][i], beta));
        }
        //计算每个城市被选中的概率
        for(int i=0;i<citys;i++){
            if(unvisitedcity[i]==0)
                p[i]=0.0;
            else{
                p[i]=(Math.pow(tao[currentcity][i], alpha)*
                        Math.pow(1.0/distance[currentcity][i], beta))/sum;
            }
        }
        long r1 = System.currentTimeMillis();
        Random rnd=new Random(r1);
        double selectp=rnd.nextDouble();
        //轮盘赌选择一个城市;
        double sumselect=0;
        int selectcity=-1;
        for(int i=0;i<citys;i++){
            sumselect+=p[i];
            if(sumselect>=selectp){
                selectcity=i;
                break;
            }
        }
        if (selectcity==-1)
            System.out.println();
        tour[index]=selectcity;
        unvisitedcity[selectcity]=0;
    }
    /**
     * 计算蚂蚁获得的路径的长度
     * @param distance  全局的距离矩阵信息
     */
    public void CalTourLength(int [][]distance){
        tourlength=0;
        tour[citys]=tour[0];
        for(int i=0;i<citys;i++){
            tourlength+=distance[tour[i]][tour[i+1]];
        }    
    }
}

package tspsolver;
import java.io.*;
/**
 *蚁群优化算法,用来求解TSP问题
 * @author FashionXu
 */
public class ACO {
    //定义蚂蚁群
    ant []ants;
    int antcount;//蚂蚁的数量
    int [][]distance;//表示城市间距离
    double [][]tao;//信息素矩阵
    int citycount;//城市数量
    int[]besttour;//求解的最佳路径
    int bestlength;//求的最优解的长度
    /** 初始化函数
     *@param filename tsp数据文件
     *@param antnum 系统用到蚂蚁的数量
     *@throws 如果文件不存在则抛出异常
    */
    public void init(String filename,int antnum) throws FileNotFoundException, IOException{
        antcount=antnum;
        ants=new ant[antcount];
        //读取数据
        int[] x;
        int[] y;
        String strbuff;
        BufferedReader tspdata = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
        strbuff = tspdata.readLine();
        citycount = Integer.valueOf(strbuff);
        distance = new int[citycount][citycount];
        x = new int[citycount];
        y = new int[citycount];
        for (int citys = 0; citys < citycount; citys++) {
            strbuff = tspdata.readLine();
            String[] strcol = strbuff.split(" ");
            x[citys] = Integer.valueOf(strcol[1]);
            y[citys] = Integer.valueOf(strcol[2]);
        }
        //计算距离矩阵
        for (int city1 = 0; city1 < citycount - 1; city1++) {
            distance[city1][city1] = 0;
            for (int city2 = city1 + 1; city2 < citycount; city2++) {
                distance[city1][city2] = (int) (Math.sqrt((x[city1] - x[city2]) * (x[city1] - x[city2])
                        + (y[city1] - y[city2]) * (y[city1] - y[city2])) + 0.5);
                distance[city2][city1] = distance[city1][city2];
            }
        }
        distance[citycount - 1][citycount - 1] = 0;
        //初始化信息素矩阵
        tao=new double[citycount][citycount];
        for(int i=0;i<citycount;i++)
        {
            for(int j=0;j<citycount;j++){
                tao[i][j]=0.1;
            }
        }
        bestlength=Integer.MAX_VALUE;
        besttour=new int[citycount+1];
        //随机放置蚂蚁
        for(int i=0;i<antcount;i++){
            ants[i]=new ant();
            ants[i].RandomSelectCity(citycount);
        }
    }
    /**
     * ACO的运行过程
     * @param maxgen ACO的最多循环次数
     * 
     */
    public void run(int maxgen){
        for(int runtimes=0;runtimes<maxgen;runtimes++){
            //每一只蚂蚁移动的过程
            for(int i=0;i<antcount;i++){
                for(int j=1;j<citycount;j++){
                    ants[i].SelectNextCity(j,tao,distance);
                }
                //计算蚂蚁获得的路径长度
                ants[i].CalTourLength(distance);
                if(ants[i].tourlength<bestlength){
                    //保留最优路径
                    bestlength=ants[i].tourlength;
                    System.out.println("第"+runtimes+"代,发现新的解"+bestlength);
                    for(int j=0;j<citycount+1;j++)
                        besttour[j]=ants[i].tour[j];
                }
            }
            //更新信息素矩阵
            UpdateTao();
            //重新随机设置蚂蚁
            for(int i=0;i<antcount;i++){
                ants[i].RandomSelectCity(citycount);
            }
        }
       }
    /**
     * 更新信息素矩阵
     */
    private void UpdateTao(){
        double rou=0.5;
        //信息素挥发
        for(int i=0;i<citycount;i++)
            for(int j=0;j<citycount;j++)
                tao[i][j]=tao[i][j]*(1-rou);
        //信息素更新
        for(int i=0;i<antcount;i++){
            for(int j=0;j<citycount;j++){
                tao[ants[i].tour[j]][ants[i].tour[j+1]]+=1.0/ants[i].tourlength;
            }
        }
    }
    /**
     * 输出程序运行结果
     */
    public void ReportResult(){
        System.out.println("最优路径长度是"+bestlength);
    }
}

package tspsolver;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *主程序 调用ACO求解问题
 * @author FashionXu
 */
public class Main {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ACO aco;
        aco=new ACO();
        try {
            aco.init("e://eil51.tsp", 50);
            aco.run(2000);
            aco.ReportResult();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

一些额外说明

算法只是提供了一个框架,没有对算法做优化处理,也没有做一些错误检查之类的,因此在实际运行时难免可能会有出错的时候,请使用者注意。

参考文献

 

[1]M. Dorigo, V. Maniezzo and A. Colorni, Positive Feedback as a Search Strategy. Technical Report No. 91-016, Politecnico di Milano, Italy, 1991. Later published as Optimization by a colony of cooperating agents, IEEE Transactions on Systems, Man, and Cybernetics-Part B, 26(1):29-41,1996. TR.01-ANTS-91-016.ps.gz , IJ.10-SMC96.pdf

[2]M. Dorigo, V. Maniezzo & A. Colorni, Ant System: Optimization by a colony of cooperating agents. IEEE Transactions on Systems, Man, and Cybernetics-Part B, 26(1):29-41,1996. IJ.10-SMC96.pdf

 

o [3]Dorigo, Stutzle M. T.,张军译.蚁群优化.北京:清华大学出版社,2007
[4]http://www.aco-metaheuristic.org/
[5]http://iridia.ulb.ac.be/~mdorigo/HomePageDorigo/