⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 psodemo.java

📁 A program to demonstrate the optimization process of particle swarm optimization. A two-dimensional
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
  public void saveImage (File file)  {                             /* --- save image to a file */    FileOutputStream stream;    /* stream to write to */    if (file == null) {         /* if no file name is given */      if (this.chooser == null) this.chooser = this.createChooser();      this.chooser.setDialogType(JFileChooser.SAVE_DIALOG);      int r = this.chooser.showDialog(this, null);      if (r != JFileChooser.APPROVE_OPTION) return;      file = this.chooser.getSelectedFile();    }                           /* let the user choose a file name */    try {                       /* save the decision tree image */      ImageIO.write(this.panel.makeImage(), "png",                  new FileOutputStream(file)); }    catch (java.io.IOException ioe) {      String msg = "file " +file.getName() +":\n" +ioe.getMessage();      stat.setText(msg); System.err.println(msg);      JOptionPane.showMessageDialog(this, msg, "alert",        JOptionPane.ERROR_MESSAGE);    }                           /* set the status text */  }  /* saveImage() */  /*------------------------------------------------------------------*/  private JDialog createFnSel ()  {                             /* --- create "Select..." dialog */    final JDialog      dlg  = new JDialog(this, "Select Function...");    GridBagLayout      g    = new GridBagLayout();    GridBagConstraints lc   = new GridBagConstraints();    GridBagConstraints rc   = new GridBagConstraints();    JPanel             grid = new JPanel(g);    JPanel             bbar;    JLabel             lbl;    JTextArea          help;    JButton            btn;    grid.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));    lc.fill      =              /* fill fields in both directions */    rc.fill      = GridBagConstraints.BOTH;    rc.weightx   = 1.0;         /* resize only the input fields, */    lc.weightx   = 0.0;         /* but not the labels */    lc.weighty   = 0.0;         /* resize lines equally */    rc.weighty   = 0.0;         /* in vertical direction */    lc.ipadx     = 10;          /* gap between labels and inputs */    lc.ipady     = 10;          /* make all lines of the same height */    rc.gridwidth = GridBagConstraints.REMAINDER;    lbl = new JLabel("Function to optimize:");    g.setConstraints(lbl, lc);    grid.add(lbl);    final JComboBox selfn = new JComboBox(new String[] {      "parabola", "circles 1", "circles 2", "eggbox 1", "eggbox 2" });    selfn.setSelectedIndex(0);    g.setConstraints(selfn, rc);  grid.add(selfn);    bbar = new JPanel(new GridLayout(1, 2, 5, 5));    bbar.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 3));    btn = new JButton("Ok"); bbar.add(btn);    btn.addActionListener(new AbstractAction () {      public void actionPerformed (ActionEvent e) {        dlg.setVisible(false);        PSODemo.this.panel.setFn(selfn.getSelectedIndex());        PSODemo.this.stat.setText("function set.");      } } );    btn = new JButton("Apply"); bbar.add(btn);    btn.addActionListener(new AbstractAction () {      public void actionPerformed (ActionEvent e) {        PSODemo.this.panel.setFn(selfn.getSelectedIndex());        PSODemo.this.stat.setText("objective function set.");      } } );    btn = new JButton("Cancel"); bbar.add(btn);    btn.addActionListener(new AbstractAction () {      public void actionPerformed (ActionEvent e) {        dlg.setVisible(false);    } } );    dlg.getContentPane().add(grid, BorderLayout.CENTER);    dlg.getContentPane().add(bbar, BorderLayout.SOUTH);    dlg.setLocationRelativeTo(this);    dlg.setLocation(664, 0);    dlg.pack();    return dlg;  }  /* createFnSel() */  /*------------------------------------------------------------------*/  private JDialog createSwarm ()  {                             /* --- create swarm dialog */    final JDialog      dlg  = new JDialog(this,                                          "Create Particle Swarm...");    GridBagLayout      g    = new GridBagLayout();    GridBagConstraints lc   = new GridBagConstraints();    GridBagConstraints rc   = new GridBagConstraints();    JPanel             grid = new JPanel(g);    JPanel             bbar;    JLabel             lbl;    JTextArea          help;    JButton            btn;    grid.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));    lc.fill      =              /* fill fields in both directions */    rc.fill      = GridBagConstraints.BOTH;    rc.weightx   = 1.0;         /* resize only the input fields, */    lc.weightx   = 0.0;         /* but not the labels */    lc.weighty   = 0.0;         /* resize lines equally */    rc.weighty   = 0.0;         /* in vertical direction */    lc.ipadx     = 10;          /* gap between labels and inputs */    lc.ipady     = 10;          /* make all lines of the same height */    rc.gridwidth = GridBagConstraints.REMAINDER;    lbl = new JLabel("Number of particles:");    g.setConstraints(lbl, lc);     grid.add(lbl);    final JSpinner parcnt = new JSpinner(          new SpinnerNumberModel(30, 1, 999999, 1));    g.setConstraints(parcnt, rc);  grid.add(parcnt);    lbl = new JLabel("Tail length (history):");    g.setConstraints(lbl, lc);     grid.add(lbl);    final JSpinner tailen = new JSpinner(          new SpinnerNumberModel(2, 0, 100, 1));    g.setConstraints(tailen, rc);  grid.add(tailen);    lbl = new JLabel("Seed for random numbers:");    g.setConstraints(lbl, lc);     grid.add(lbl);    final JSpinner seed = new JSpinner(          new SpinnerNumberModel(0, 0, 999999, 1));    g.setConstraints(seed, rc);    grid.add(seed);    help = new JTextArea(       "If the seed for the pseudo-random number generator\n"      +"is set to zero, the system time will be used instead.");    help.setFont(small);    help.setBackground(this.getBackground());    g.setConstraints(help, rc); grid.add(help);    lbl = new JLabel("Acceleration factor:");    g.setConstraints(lbl, lc);     grid.add(lbl);    final JTextField accel = new JTextField("1");    accel.setFont(font);    g.setConstraints(accel, rc);   grid.add(accel);    lbl = new JLabel("Initial deceleration factor:");    g.setConstraints(lbl, lc);     grid.add(lbl);    final JTextField decel = new JTextField("1");    decel.setFont(font);    g.setConstraints(decel, rc);   grid.add(decel);    lbl = new JLabel("Deceleration factor decay:");    g.setConstraints(lbl, lc);     grid.add(lbl);    final JTextField decay = new JTextField("0.03");    decay.setFont(font);    g.setConstraints(decay, rc);   grid.add(decay);    bbar = new JPanel(new GridLayout(1, 2, 5, 5));    bbar.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 3));    btn = new JButton("Ok"); bbar.add(btn);    btn.addActionListener(new AbstractAction () {      public void actionPerformed (ActionEvent e) {        dlg.setVisible(false);        int s = ((Integer)seed.getValue()).intValue();        PSODemo.this.panel.createSwarm(          ((Integer)parcnt.getValue()).intValue(),          ((Integer)tailen.getValue()).intValue(),          Double.parseDouble(accel.getText()),          Double.parseDouble(decel.getText()),          Double.parseDouble(decay.getText()),          (s != 0) ? new Random(s) : new Random());        PSODemo.this.stat.setText("swarm created");      } } );    btn = new JButton("Apply"); bbar.add(btn);    btn.addActionListener(new AbstractAction () {      public void actionPerformed (ActionEvent e) {        int s = ((Integer)seed.getValue()).intValue();        PSODemo.this.panel.createSwarm(          ((Integer)parcnt.getValue()).intValue(),          ((Integer)tailen.getValue()).intValue(),          Double.parseDouble(accel.getText()),          Double.parseDouble(decel.getText()),          Double.parseDouble(decay.getText()),          (s != 0) ? new Random(s) : new Random());        PSODemo.this.stat.setText("swarm created");      } } );    btn = new JButton("Close"); bbar.add(btn);    btn.addActionListener(new AbstractAction () {      public void actionPerformed (ActionEvent e) {        dlg.setVisible(false); } } );    dlg.getContentPane().add(grid, BorderLayout.CENTER);    dlg.getContentPane().add(bbar, BorderLayout.SOUTH);    dlg.setLocationRelativeTo(this);    dlg.setLocation(664, 94);    dlg.pack();    return dlg;  }  /* createSwarm() */  /*------------------------------------------------------------------*/  private String msg ()  {                             /* --- create status message */    if (this.fmt == null) this.fmt = new DecimalFormat("0.000000");    return "step: "     +this.panel.getStep()          +", best: f(" +this.fmt.format(this.panel.getBestX())          +","          +this.fmt.format(this.panel.getBestY())          +") = "       +this.fmt.format(this.panel.getBest());  }  /* msg() */  /*------------------------------------------------------------------*/  private void updateSwarm (int epochs, int delay)  {                             /* --- move the swarm */    if (this.cnt >= 0) {        /* check for running update */      this.timer.stop(); this.cnt = -1; return; }    if (!this.panel.hasSwarm()) return;    if (delay <= 0) {           /* if to update at the end */      while (--epochs >= 0)     /* while more epochs to compute, */        this.panel.updateSwarm();              /* move the swarm */      this.panel.repaint();     /* redraw the window contents */      this.stat.setText(this.msg());      return;                   /* show a status message, */    }                           /* then abort the function */    this.cnt   = epochs;        /* note the epochs */    this.timer = new Timer(delay, new ActionListener () {      public void actionPerformed (ActionEvent e) {        if (--PSODemo.this.cnt < 0) {          PSODemo.this.timer.stop(); return; }        PSODemo.this.panel.updateSwarm();     /* move the swarm and */        PSODemo.this.panel.repaint(); /* redraw the window contents */        PSODemo.this.stat.setText(PSODemo.this.msg());      } } );                    /* update the status text */    this.timer.start();         /* start the status update timer */  }  /* updateSwarm() */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -