【智能算法】FA萤火虫算法求解无约束多元函数最值(Java代码实现)

简介: 【智能算法】FA萤火虫算法求解无约束多元函数最值(Java代码实现)

@[toc]


前言

本文以求解二元函数最小值为例,如果需要求解多元函数,只需要修改以下变量即可:

  • varNum:变量维度数
  • ub和lb:变量的上下界
  • vMaxArr:每个维度的搜索速度限制

优化目标

目标:在变量区间范围最小化 Z = x^2 + y^2 - xy - 10x - 4y +60

求解结果

变量取值为:[8.00013867452009, 6.000077817430381]
最优解为:8.000000014494901

搜索过程可视化

在这里插入图片描述

Java代码

import java.util.Arrays;
import java.util.Random;

/**
 * @Author:WSKH
 * @ClassName:FA_Solve
 * @ClassType:
 * @Description:
 * @Date:2022/6/8/18:26
 * @Email:1187560563@qq.com
 * @Blog:https://blog.csdn.net/weixin_51545953?type=blog
 */
public class FA_Solve {

    // 萤火虫对象
    class Firefly {
        // 当前萤火虫的坐标(自变量数组)
        double[] curVars;
        // 当前自变量对应的目标函数值
        double curObjValue;
        // 适应度(解决最小化问题,所以适应度为目标函数值的倒数)
        double fit;

        // 全参构造
        public Firefly(double[] curVars, double curObjValue, double fit) {
            this.curVars = curVars;
            this.curObjValue = curObjValue;
            this.fit = fit;
        }
    }

    // 算法参数
    // 变量个数
    int varNum = 2;
    // 最大迭代次数
    int maxGen = 500;
    // 萤火虫群中萤火虫的个数
    int fireflyNum = 200;
    // 光吸收系数
    double gamma = 0.3;
    // 步长数组(各个维度的步长)
    double[] stepArr = new double[]{1.2, 1.2};
    // 变量的上下界
    double[] ub = new double[]{1000, 1000};
    double[] lb = new double[]{-1000, -1000};
    // 随机数对象
    Random random = new Random();
    // 萤火虫群
    Firefly[] fireflies;
    // 最佳的萤火虫
    Firefly bestFirefly;
    // 记录迭代过程
    public double[][][] positionArr;
    // 当前记录的行数
    int r;

    // 求解主函数
    public void solve() {
        // 初始化萤火虫群
        initFireflyes();
        // 开始迭代
        for (int t = 0; t < maxGen; t++) {
            for (int i = 0; i < fireflyNum; i++) {
                for (int j = 0; j < fireflyNum; j++) {
                    double light = getLight(getDistance(fireflies[i], fireflies[j]), fireflies[j].fit);
                    if (i != j && fireflies[i].fit < fireflies[j].fit) {
                        Firefly tempFirefly = copyFirefly(fireflies[i]);
                        for (int m = 0; m < varNum; m++) {
                            double move = light * (fireflies[j].curVars[m] - fireflies[i].curVars[m]) + stepArr[m] * (random.nextDouble()-0.5);
                            moveFirefly(tempFirefly, m,move);
                        }
                        updateFireFly(tempFirefly);
                        if(tempFirefly.fit > fireflies[i].fit){
                            fireflies[i] = tempFirefly;
                            if(bestFirefly.fit < tempFirefly.fit){
                                bestFirefly = copyFirefly(tempFirefly);
                            }
                        }
                    }
                }
            }
            report();
        }
        // 输出最好的结果
        System.out.println("变量取值为:" + Arrays.toString(bestFirefly.curVars));
        System.out.println("最优解为:" + bestFirefly.curObjValue);
    }

    // 记录
    void report() {
        for (int i = 0; i < fireflies.length; i++) {
            for (int j = 0; j < varNum; j++) {
                positionArr[r][i][j] = fireflies[i].curVars[j];
            }
        }
        r++;
    }

    // 获取光强
    double getLight(double r, double fit) {
        return fit * Math.exp(-gamma * Math.pow(r, 2));
    }

    // 求两个萤火虫之间的距离
    double getDistance(Firefly f1, Firefly f2) {
        double dis = 0d;
        for (int i = 0; i < varNum; i++) {
            dis += Math.pow(f1.curVars[i] - f2.curVars[i], 2);
        }
        return Math.sqrt(dis);
    }

    // 初始化萤火虫群
    private void initFireflyes() {
        positionArr = new double[maxGen][fireflyNum][varNum];
        fireflies = new Firefly[fireflyNum];
        for (int i = 0; i < fireflyNum; i++) {
            fireflies[i] = getRandomFirefly();
            if (i == 0 || bestFirefly.fit < fireflies[i].fit) {
                bestFirefly = copyFirefly(fireflies[i]);
            }
        }
    }

    // 控制萤火虫在第m个维度上移动n个距离
    public void moveFirefly(Firefly firefly, int m, double n) {
        // 移动
        firefly.curVars[m] += n;
        // 超出定义域的判断
        if (firefly.curVars[m] < lb[m]) {
            firefly.curVars[m] = lb[m];
        }
        if (firefly.curVars[m] > ub[m]) {
            firefly.curVars[m] = ub[m];
        }
    }

    // 更新萤火虫信息
    void updateFireFly(Firefly firefly) {
        double objValue = getObjValue(firefly.curVars);
        firefly.curObjValue = objValue;
        firefly.fit = 1 / objValue;
    }

    // 获取一个随机生成的萤火虫
    Firefly getRandomFirefly() {
        double[] vars = new double[varNum];
        for (int j = 0; j < vars.length; j++) {
            vars[j] = lb[j] + random.nextDouble() * (ub[j] - lb[j]);
        }
        double objValue = getObjValue(vars);
        return new Firefly(vars.clone(), objValue, 1 / objValue);
    }

    /**
     * @param vars 自变量数组
     * @return 返回目标函数值
     */
    public double getObjValue(double[] vars) {
        //目标:在变量区间范围最小化 Z = x^2 + y^2 - xy - 10x - 4y +60
        return Math.pow(vars[0], 2) + Math.pow(vars[1], 2) - vars[0] * vars[1] - 10 * vars[0] - 4 * vars[1] + 60;
    }

    // 复制萤火虫
    Firefly copyFirefly(Firefly old) {
        return new Firefly(old.curVars.clone(), old.curObjValue, old.fit);
    }

}

可视化代码

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * @Author:WSKH
 * @ClassName:PlotUtil
 * @ClassType:
 * @Description:
 * @Date:2022/6/6/18:31
 * @Email:1187560563@qq.com
 * @Blog:https://blog.csdn.net/weixin_51545953?type=blog
 */
public class PlotUtil extends Application {

    //当前的时间轴
    private Timeline nowTimeline;
    //绘图位置坐标
    private double[][][] positionArr;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {

        // 调用算法获取绘图数据
        FA_Solve solver = new FA_Solve();
        solver.solve();
        positionArr = solver.positionArr;

        // 画图
        try {
            BorderPane root = new BorderPane();
            root.setStyle("-fx-padding: 20;");
            Scene scene = new Scene(root, 1600, 900);
            double canvasWid = 800;
            double canvasHei = 800;
            //根据画布大小缩放坐标值
            this.fixPosition(canvasWid - 100, canvasHei - 100);

            //画布和画笔
            HBox canvasHbox = new HBox();
            Canvas canvas = new Canvas();
            canvas.setWidth(canvasWid);
            canvas.setHeight(canvasHei);
            canvasHbox.setPrefWidth(canvasWid);
            canvasHbox.getChildren().add(canvas);
            canvasHbox.setAlignment(Pos.CENTER);
            canvasHbox.setStyle("-fx-spacing: 20;" +
                    "-fx-background-color: #87e775;");
            root.setTop(canvasHbox);
            GraphicsContext paintBrush = canvas.getGraphicsContext2D();

            //启动
            HBox hBox2 = new HBox();
            Button beginButton = new Button("播放迭代过程");
            hBox2.getChildren().add(beginButton);
            root.setBottom(hBox2);
            hBox2.setAlignment(Pos.CENTER);
            //启动仿真以及暂停仿真
            beginButton.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
                nowTimeline.play();
            });

            //创建扫描线连接动画
            nowTimeline = new Timeline();
            createAnimation(paintBrush);

            primaryStage.setScene(scene);
            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修正cityPositionArr的坐标,让画出来的点在画布内
     *
     * @param width
     * @param height
     */
    private void fixPosition(double width, double height) {
        double minX = Double.MAX_VALUE;
        double maxX = -Double.MAX_VALUE;
        double minY = Double.MAX_VALUE;
        double maxY = -Double.MAX_VALUE;

        for (int i = 0; i < this.positionArr.length; i++) {
            for (int j = 0; j < this.positionArr[0].length; j++) {
                minX = Math.min(minX, this.positionArr[i][j][0]);
                maxX = Math.max(maxX, this.positionArr[i][j][0]);
                minY = Math.min(minY, this.positionArr[i][j][1]);
                maxY = Math.max(maxY, this.positionArr[i][j][1]);
            }
        }

        double multiple = Math.max((maxX - minX) / width, (maxY - minY) / height);

        //转化为正数数
        for (int i = 0; i < this.positionArr.length; i++) {
            for (int j = 0; j < this.positionArr[0].length; j++) {
                if (minX < 0) {
                    this.positionArr[i][j][0] = this.positionArr[i][j][0] - minX;
                }
                if (minY < 0) {
                    this.positionArr[i][j][1] = this.positionArr[i][j][1] - minY;
                }
            }
        }

        for (int i = 0; i < this.positionArr.length; i++) {
            for (int j = 0; j < this.positionArr[0].length; j++) {
                this.positionArr[i][j][0] = this.positionArr[i][j][0] / multiple;
                this.positionArr[i][j][1] = this.positionArr[i][j][1] / multiple;
            }
        }

    }

    /**
     * 用画笔在画布上画出所有的孔
     * 画第i代的所有粒子
     */
    private void drawAllCircle(GraphicsContext paintBrush, int i) {
        paintBrush.clearRect(0, 0, 2000, 2000);
        paintBrush.setFill(Color.RED);
        for (int j = 0; j < this.positionArr[i].length; j++) {
            drawCircle(paintBrush, i, j);
        }
    }

    /**
     * 用画笔在画布上画出一个孔
     * 画第i代的第j个粒子
     */
    private void drawCircle(GraphicsContext paintBrush, int i, int j) {
        double x = this.positionArr[i][j][0];
        double y = this.positionArr[i][j][1];
        double radius = 2;
        // 圆的直径
        double diameter = radius * 2;
        paintBrush.fillOval(x, y, diameter, diameter);
    }

    /**
     * 创建动画
     */
    private void createAnimation(GraphicsContext paintBrush) {
        for (int i = 0; i < this.positionArr[0].length; i++) {
            int finalI = i;
            KeyFrame keyFrame = new KeyFrame(Duration.seconds(i * 0.05), event -> drawAllCircle(paintBrush, finalI));
            nowTimeline.getKeyFrames().add(keyFrame);
        }
    }

}
相关实践学习
部署高可用架构
本场景主要介绍如何使用云服务器ECS、负载均衡SLB、云数据库RDS和数据传输服务产品来部署多可用区高可用架构。
负载均衡入门与产品使用指南
负载均衡(Server Load Balancer)是对多台云服务器进行流量分发的负载均衡服务,可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应用系统的可用性。 本课程主要介绍负载均衡的相关技术以及阿里云负载均衡产品的使用方法。
目录
相关文章
|
10天前
|
分布式计算 DataWorks Java
DataWorks操作报错合集之在使用MaxCompute的Java SDK创建函数时,出现找不到文件资源的情况,是BUG吗
DataWorks是阿里云提供的一站式大数据开发与治理平台,支持数据集成、数据开发、数据服务、数据质量管理、数据安全管理等全流程数据处理。在使用DataWorks过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
25 0
|
1天前
|
存储 安全 Java
掌握8条泛型规则,打造优雅通用的Java代码
掌握8条泛型规则,打造优雅通用的Java代码
掌握8条泛型规则,打造优雅通用的Java代码
|
1天前
|
Java 程序员 图形学
程序员教你用代码制作飞翔的小鸟--Java小游戏,正好拿去和给女神一起玩
《飞扬的小鸟》Java实现摘要:使用IntelliJ IDEA和JDK 16开发,包含小鸟类`Bird`,处理小鸟的位置、速度和碰撞检测。代码示例展示小鸟图像的加载、绘制与旋转。同时有`Music`类用于循环播放背景音乐。游戏运行时检查小鸟是否撞到地面、柱子或星星,并实现翅膀煽动效果。简单易懂,可直接复制使用。
|
2天前
|
数据库连接
java+ssm+vue代码视频学习讲解
java+ssm+vue代码视频学习讲解
5 0
|
2天前
|
SQL 缓存 算法
优化你的Java代码:性能调优技巧
优化你的Java代码:性能调优技巧
8 0
|
2天前
|
算法
【智能算法】11种混沌映射算法+2种智能算法示范【鲸鱼WOA、灰狼GWO算法】
【智能算法】11种混沌映射算法+2种智能算法示范【鲸鱼WOA、灰狼GWO算法】
|
3天前
|
Java 编译器 程序员
Java一分钟之第一行Java代码:输出"Hello, World!"
【5月更文挑战第7天】本文引导初学者编写运行第一个Java程序——打印&quot;Hello, World!&quot;,介绍基本代码结构及常见问题。包括语法错误(如缺少分号、缩进不规范)、编译运行问题(忘记编译、运行错误)和环境配置问题(JDK未安装、环境变量未设置)。建议检查语法、熟悉编译运行流程并正确安装配置JDK。通过实战演练,从编写到运行,迈出Java编程第一步。
13 0
|
3天前
|
Java
接口在增强Java代码的灵活性方面起着关键作用
Java接口增强代码灵活性,实现多态性、解耦、多继承和扩展性。通过接口,类可隐藏实现细节,实现抽象化,促进模块化和维护性。接口定义方法,允许不同类实现,减少依赖,便于测试和修改。同时,接口提供多继承解决方案,使代码更具扩展性,易于添加新功能。
22 4
|
4天前
|
搜索推荐 Java Shell
8大Java排序方法(由简入繁),有代码详解和原理指导
8大Java排序方法(由简入繁),有代码详解和原理指导
22 0
|
4天前
|
Java Apache
Java代码使用POI导出的单元格加上边框和背景色
【5月更文挑战第3天】Java代码使用POI导出的单元格加上边框和背景色
20 0