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

📄 picsandstatgenerator.java

📁 JAVA版的蚂蚁算法(Ant Colony Optimization Algorithms)
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
      strBuf.append( "\n" );
      strBuf.append( "Bound on trail value\t" ).append(
                             commaFormat.format( antRoutingAlg.getBoundOnTrail() ) );
      strBuf.append( "\n" );
    }
    strBuf.append( "Number of packages\t" +
                   eventSim.getNumberOfInitialPackages() + "\n" );
    strBuf.append( "Dead\t" + eventSim.getLostPackages() + "\n" +
                   "TTL\t" + eventSim.getTTLDeaths() + "\n" );

    strBuf.append( "INPUT\t" + eventSim.getInputQueueDeaths() + "\n" +
                   "OUPUT\t" + eventSim.getOutputQueueDeaths() + "\n" );
    strBuf.append( "NPRDies\t" + eventSim.getNPRDeaths() + "\n" );
    strBuf.append( "Total time load of packages\t" +
                 commaFormat.format( eventSim.getAccumulatedPackageTime() ) + "\n" );
    strBuf.append( "Average time for package\t" );
    if ( eventSim.getCountDeadAntPackageTime() ) {
      strBuf.append( commaFormat.format( eventSim.getAccumulatedPackageTime() /
                                           eventSim.getNumberOfInitialPackages() ) );
    }
    else {
      strBuf.append( commaFormat.format( eventSim.getAccumulatedPackageTime() / (
            eventSim.getNumberOfInitialPackages() - eventSim.getLostPackages() ) ) );
    }
    strBuf.append( "\n");

    writeToFile( strBuf.toString(), prefix + "_Simulation_parameters.xls" );

    // Gather simulation stats
    String statData = dataListToString( eventSim.getSimStatistics() );
    writeToFile( statData, prefix + "_Simulation_stats.xls" );

    System.err.println( "generateStandardRoutingStats() completed succesfully.");
  }

  /**
   * Makes 11 standard images of the runs on the graph covering most most of the
   * information in the graph.
   */
  public void generateStandardACOGraphPics(){
    System.err.println( "Starting generateStandardACOGraphPics()...");
    // Make some different forms of standard graphs
    generateGraphPic( "theGraph.jpg", getGraph().getAllEdges(),
                                                    "The graph - all edges", false );

    generateGraphPic( "TotalAnts_ColorEdges.jpg",
                      "Total number of ants moved on edges",
                      true, 100, "totalAnts", true, true, false );
    generateGraphPic( "TotalAnts_NumberedEdges.jpg",
                      "Total number of ants moved on edges",
                      false, 100, "totalAnts", false, true, false );

    generateGraphPic( "TotalDepositedTrail_ColorEdgesUp.jpg",
                      "Total amount of trail deposited on edges",
                      true, 100, "totalTrailValueUp", true, true, false );
    generateGraphPic( "TotalDepositedTrail_ColorEdgesDown.jpg",
                      "Total amount of trail deposited on edges",
                      true, 100, "totalTrailValueDown", true, true, false );

    generateGraphPic( "Trail_OnEdges_ColorUp.jpg", "Amount of trail on edges",
                      true, 100, "trailValueUp", true, true, false );
    generateGraphPic( "Trail_OnEdges_ColorDown.jpg", "Amount of trail on edges",
                      true, 100, "trailValueDown", true, true, false );

    generateGraphPic( "Trail_OnEdges_NumbersUp.jpg", "Amount of trail on edges",
                      false, 100, "trailValueUp", false, true, false );
    generateGraphPic( "Trail_OnEdges_NumbersDown.jpg", "Amount of trail on edges",
                      false, 100, "trailValueDown", false, true, false );
  
    generateGraphPic( "TotalDepositedTrail_NumberedEdgesUp.jpg",
                      "Total amount of trail deposited on edges",
                      false, 100, "totalTrailValueUp", false, true, false );
    generateGraphPic( "TotalDepositedTrail_NumberedEdgesDown.jpg",
                      "Total amount of trail deposited on edges",
                      false, 100, "totalTrailValueDown", false, true, false );

    System.err.println( "Ending generateStandardGraphPics()...");
  }

  /**
   * Given a <code>List</code> of data, this method returns a <code>String</code>
   * containing all the data. List element 0 should contain a <code>String[]</code>
   * -array with header-names for the data, and the rest of the elements should be
   * <code>double[]</code>-arrays containing data-values. All arrays should be of
   * same length. The returned <code>String</code> will be formatted with tabs
   * (<code>'\t'</code>) for column-shifts and new-lines (<code>'\n'</code>)
   * for row-shift.
   *
   * @param statData the <code>List</code> containing the all the data
   *
   * @return tabulated <code>String</code> representation of data
   */
  private String dataListToString( List statData ) {
    StringBuffer res = new StringBuffer( statData.size() * 5 );

    // List element 0 contains String[]-array with header-names
    // and rest-elements are double[]-arrays with stat-vals...

    if ( statData.size() > 0 ) {
      String[] headers = ( String[] ) statData.get( 0 );
      int numberOfColumns = headers.length;

      // Append column-headers
      for ( int i = 0; i < numberOfColumns - 1; i++ ) {
        res.append( headers[ i ]).append( "\t" );
      }
      res.append( headers[ numberOfColumns - 1 ]).append( "\n" );

      // Append the rest of the rows
      double[] tmp = ( double[] ) statData.get( 1 );
      for ( int i = 1; i < statData.size(); i++ ) {
        tmp = ( double[] ) statData.get( i );
        for ( int j = 0; j < numberOfColumns - 1; j++ ) {
          res.append( commaFormat.format( tmp[ j ] ) ).append( '\t' );
        }
        res.append( commaFormat.format(
                                       tmp[ numberOfColumns - 1 ] ) ).append( '\n' );
      }
    }
    return res.toString();
  }

  /**
   * Given a <code>List</code> of data, this method returns a String containing
   * all the data. The format of the String is three columns
   * ("Raw data", "Sorted data", "Best possible length") and one row for each ant.
   *
   * @param statData the <code>List</code> containing the all the data
   * @param bestPossibleLength the length of the best possible path
   *
   * @return a String representation of all the ants in the algortihm.
   */
  private String dataListToString( List statData, double bestPossibleLength ){
    StringBuffer tmpStr = new StringBuffer( statData.size() * 5 );

    Object rawData[] = statData.toArray();
    // Sort the data, so the best run is first
    Collections.sort( statData );

    tmpStr.append( "Raw data\tSorted data\tBest possible length\n" );

    // Append the first row (special because this is the only row containing a
    // bestPossibleLength
    if ( statData.size() > 0 ) {
      tmpStr.append( rawData[ 0 ] ).append( '\t' ).append( statData.get( 0 ) )
              .append( '\t' ).append( (int) bestPossibleLength ).append( '\n' );
    }

    // Append the rest of the rows
    for ( int i = 1; i < statData.size(); i++ ) {
      tmpStr.append( rawData[ i ] ).append( '\t' ).append( statData.get( i ) )
                                                                    .append( '\n' );
    }

    return tmpStr.toString();
  }

  /**
   * This method collects statistical data for an ACOMetaheuristic-algorithm
   * in two different formats. The first file contains a summary of the data
   * while the other contains all data for a run.
   *
   * The result is written to two files: StatisticalAnalysis.doc and resultData.xls
   */
  public void generateStandardACOStats(){
    System.err.println( "Starting generateStandardACOStats()...");

    List statData = acoAlg.getCollectedRunData();

    ShortestPaths res =
           Algorithms.dijkstra( acoAlg.theGraph, acoAlg.getSourceIndex(), "weight" );
    double bestPossibleLength =
                res.getDistances()[ acoAlg.getSecondRunSourceIndex() ].getDistance();

    String dataStr = dataListToString( statData, bestPossibleLength );

    // Make a summery
    double avr = 0;
    double variance = 0;
    double standardDeviation = 0;
    double numTwiceAvrRun = 0;
    double numTwiceBestRun = 0;
    double total = 0;
    double bestRun = ( ( Double ) statData.get( 0 ) ).doubleValue();

    for ( int i = 0; i < statData.size(); i++ ) {
      total += ( ( Double ) statData.get( i ) ).doubleValue();
    }

    avr = total / statData.size();

    // Collect statistics
    for ( int i = 0; i < statData.size(); i++ ){
      numTwiceAvrRun += ( ( ( Double ) statData.get( i ) ).doubleValue() >
                                                              avr * 2 ) ? 1 : 0;
      numTwiceBestRun += ( ( ( Double ) statData.get( i ) ).doubleValue() >
                                                          bestRun * 2 ) ? 1 : 0;
      variance += Math.pow( ( ( Double ) statData.get( i ) ).doubleValue()
                                                                      - avr, 2);
    }
    variance /= statData.size();
    standardDeviation = Math.sqrt( variance );

    int numberOfAnts = statData.size();
    String analysisResult =
      "Number of ants       : " + numberOfAnts +
      "\nNumber of dead ants  : " + acoAlg.getNumberOfDead() +
      "\navr                  : " + avr +
      "\nfirstQuartile        : " + statData.get( numberOfAnts / 4     - 1 ) +
      "\nsecondQuartile       : " + statData.get( numberOfAnts / 2     - 1 ) +
      "\nthirdQuartile        : " + statData.get( numberOfAnts * 3 / 4 - 1 ) +
      "\nfourthQuartile       : " + statData.get( numberOfAnts         - 1 ) +
      "\nnumTwiceAvrRun       : " + numTwiceAvrRun +
      "\nnumTwiceBestRun      : " + numTwiceBestRun +
      "\nbestRun              : " + bestRun +
      "\nbestPossibleLength   : " + bestPossibleLength +
      "\nVariance             : " + variance +
      "\nStandard Deviation   : " + standardDeviation;

    // Write the summary to a file
    writeToFile( analysisResult, "StatisticalAnalysis.doc" );

    // Write whole statData to a file
    writeToFile( dataStr, "resultData.xls" );
    System.err.println( "Ending generateStandardStats()...");
  }

  /**
   * <code>writeToFile</code> creates a new file with the filename and content
   * given as arguments. 
   *
   * @param data a String containing the information to be output
   * @param filename the name of the ouput-file
   */
  private void writeToFile( String data, String filename ){
    try {
      java.io.File tmpFile = new java.io.File( picsAndStatDirectory + "//" +
                                                                     filename );
      tmpFile.createNewFile();
      java.io.FileWriter tmpFileWriter = new java.io.FileWriter( tmpFile );
      tmpFileWriter.write( data );
      tmpFileWriter.flush();
    }
    catch ( java.io.IOException e ){ e.printStackTrace(); }
  }
}

⌨️ 快捷键说明

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