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

📄 snns.java

📁 著名的神经网络工具箱
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/*************************************************************************

This program is copyrighted. Please refer to COPYRIGHT.txt for the
copyright notice.

This file is part of JavaNNS.

JavaNNS is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

JavaNNS is distributed in the hope that it will be useful,
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with JavaNNS; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*************************************************************************/


package javanns;

import javax.swing.* ;
import javax.swing.event.*;
import java.awt.* ;
import java.awt.event.* ;
import java.beans.*;
import java.io.IOException ;
import java.util.Vector ;
import java.util.Properties;
import java.io.*;
import java.awt.print.* ;
import java.net.URL;

/*==========================================================================*
 * CLASS DECLARATION
 *==========================================================================*/

/**
 * Snns is the main class which initializes the GUI
 *
 */
class Snns extends JFrame implements ActionListener,
                                     NetworkListener,
                                     LoaderAndSaver,
                                     NetworkViewListener {

  /**
   * applet from which the JavaNNS was called. <code>null</code> if the
   *  JavaNNS is used as a stand-alone application
   */
  public static JApplet applet = null;

  /*-------------------------------------------------------------------------*
   * Settings for different distributions (Unix v/s Windows; book or no book)
   *-------------------------------------------------------------------------*/

  /**
   * Current version number of the release
   */
  public static String JavaNNS_VERSION = "1.1";

  /**
   * filenames of JavaNNS
   */
  static final String JAR_FILE_NAME = "JavaNNS.jar";

  // WICHTIG : Im jar file darf es keine weitere Datei geben, die im Namen die
  // Zeichenkette SNNS_jkr enthaelt, da ansonsten die Methode loadLibrary
  // in Network durcheinandergeraten koennte
  static final String LIBRARY_NAME = "SNNS_jkr";

  /**
   * Filename of the javanns fn-declaration file
   * usually part of the jar-file
   */
  static final String FN_DECL_FILE_NAME = "FnDeclaration.txt";

  /**
   * the JavaNNS help index file
   * JavaNNS looks for that file in the URL specified by SNN_BOOK_URL_KEY
   * of the JavaNNS properties
   */
  static final String HELP_INDEX_FILE_NAME = "JavaNNSindex.html";


  /**
   * path of the icon and images directory
   */
  static final String ICON_PATH = "images";


  static JavaNNSProperties properties;

  /*-------------------------------------------------------------------------*
   * private member variables
   *-------------------------------------------------------------------------*/

  /**
   * Use metal look-and-feel or not:
   */
  private static boolean METAL_LOOK_AND_FEEL = true;


  // Diverse menu items, for use in action listener
  private JMenuItem
    mNew, mOpen, mClose, mSave, mSaveAs, mSaveData, mPrint, mExit, // File
    mNetwork, m3DNetwork, mGraph, mAnalyzer, mProjection, mWeights, mViewSettings, mEditUnits,
      cbmiStatusPanel, mProperties,// View
    mControl, mCascade, mKohonen, mLog,// Tools
    mAddPattern, mModifyPattern, mDeletePattern, mNewPatternSet, // Pattern
    mCascadeW, mCloseW,// mArrangeIcons, // Window
    mContents, mSearch, mAbout; // Help

  // edit menu:
  private JMenuItem mUndo, mRedo, mTop, mBottom;
    // delete menu:
    private JMenu mDelete;
    private JMenuItem mDeleteLinks, mDeleteUnits;

  // Create submenu of the Tools menu:
  private JMenu mCreate;
  private JMenuItem mLayer, mConnect;

  JPopupMenu popup;
  private JMenuItem mPopEditU, mPopEditL, mPopDelU, mPopDelL;

  // used by WindowsMenuItems, so it has to be a member
  private JMenu mWindows;

  // main pane
  private JDesktopPane desktop;

  // all functions
  Functions functions;

  // unit detail
  UnitDetailPanel unitDetail;

  Insets panel_insets = new Insets(3, 4, 3, 4); // Insets for all additional panels
  IconGrabber icons;
  MasterControl master;
  StatusPanel statusPanel;
  public LogPanel pLog;
  public FileManager fileManager;
  public Network network;
  public PatternSets patternSets;
  File configHomeFile;

  private Vector net_views = new Vector();
  private int net_views_count;// more history than number of current net views
  private NetworkView last_view; // the last active network view

  /*-------------------------------------------------------------------------*
   * constructor: creates main application frame
   *-------------------------------------------------------------------------*/

  /**
   * Class constructor. Creates main application frame and loads specified
   *   network and patterns.
   *
   * @param files to load
   */
  public Snns( String[] args ) throws Exception{
    super("JavaNNS");
    icons = new IconGrabber(this);
    setIconImage(icons.getImage("network.gif"));

    properties = new JavaNNSProperties(this);

    network = new Network( this );
    network.addListener( this );
    patternSets = new PatternSets( this, 5 );

    JPanel contentPane = new JPanel( new BorderLayout() );
    statusPanel = new StatusPanel( this );
    contentPane.add( statusPanel, BorderLayout.NORTH );

    desktop = new JDesktopPane(); //a specialized layered pane
    //setContentPane(desktop);
    contentPane.add( desktop, BorderLayout.CENTER );
    setContentPane( contentPane );
    desktop.putClientProperty("JDesktopPane.dragMode", "outline");

    setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
    addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) { close();}
      }
    );

    setMenuBar();

    pLog = new LogPanel( this );
    addInternalFrame( pLog.frame, false );

    fileManager = new FileManager( this );
    fileManager.setDefaultLAS( pLog );

    // the function set :
    functions = new Functions(this);
    master = new MasterControl(this);
    addInternalFrame(master.frame, false);


    // check the arguments :
    LoaderAndSaver[] las = new LoaderAndSaver[]{ this, network, patternSets.getCover() };
    for( int i=0; i<args.length; i++ ) {
      if( args[i].equals("-view") ) openNetworkView();
      else if( args[i].equals("-controlPanel") )
        master.frame.setVisible(true);
      else if( args[i].equals("-errorGraph") ) {
        GraphPanel gp = new GraphPanel( this );
        addInternalFrame( gp.frame, true );
      }
      else if( args[i].equals("-analyzer") ){
        AnalyzerPanel ap = new AnalyzerPanel( this );
        addInternalFrame( ap.frame, true );
      }
      else if( args[i].equals("-log") )
        pLog.frame.setVisible( true );
      else if(args[i].equals("-help") || args[i].equals("-?")) {
        System.out.println(
          "\n" +
          "Java Neural Network Simulator " + JavaNNS_VERSION + "\n" +
          "Copyright (c) 1990-1995 IPVR, University of Stuttgart\n" +
          "Copyright (c) 1996-2002 WSI, University of Tuebingen\n" +
          "http://www-ra.informatik.uni-tuebingen.de/forschung/JavaNNS/\n\n" +
          "Usage:  java -jar JavaNNS.jar [-options] [files]\n\n" +
          "where options include:\n" +
          "  -view           open a network view upon starting\n" +
          "  -errorGraph     open an error graph window\n" +
          "  -controlPanel   open the control panel\n" +
          "  -analyzer       open the analyzer tool\n" +
          "  -log            show the log window\n" +
          "  -?  or  -help   show this help message\n"
        );
        System.exit(0);
      }
      else
        //try{ fileManager.load( new File( args[i] ), las ); }
        try {
          // this is a workaround for JVM not respecting the user.dir
          // when set in the applet
        fileManager.load(new File(System.getProperty("user.dir", "")
                                  + System.getProperty("file.separator", "/")
                                  + args[i]),
                         las); }
        catch( Exception e ){ showException( e, fileManager ); }

    }

    // unit details :
    unitDetail = new UnitDetailPanel( this, true );
    addInternalFrame( unitDetail.frame, false );

    PrintStream out = new PrintStream( pLog.writer );
    //System.out.println("System.out und System.err wird auf LogPanel umgeleitet");
    System.setErr( out );
    System.setOut( out );

    if( net_views.size() == 0 ) openNetworkView();
  }


  /*-------------------------------------------------------------------------*
   * public methods
   *-------------------------------------------------------------------------*/

  /**
   * Stand-alone application starting point. Calls
   *  {@link #appletMain(JApplet, String[])} with <code>applet</code>
   *  parameter set to <code>null</code>
   *
   * @param args [0]:network, [1]:pattern, [2]:configuration file to load.
   *   All args are optional.
   */
  public static void main(String[] args) { appletMain(null, args); }

  /**
   * Application starting point if called from an applet. Sets application
   *   look-and-feel and displays the application main frame.
   *
   * @param apl caller applet
   * @param args [0]:network, [1]:pattern, [2]:configuration file to load.
   *   All args are optional.
   * @return main application frame
   */
  public static Snns appletMain(JApplet apl, String[] args) {
    applet = apl;
    String laf;
    try {
      if(isMetalLookAndFeel()) laf = UIManager.getCrossPlatformLookAndFeelClassName();
      else laf = UIManager.getSystemLookAndFeelClassName();
      UIManager.setLookAndFeel(laf);
    } catch(Exception e1) { System.out.println("No Look-and-Feel!"); }
    try{
      Snns frame = new Snns( args );
      frame.setSize(Integer.parseInt(properties.getProperty(properties.SCR_WIDTH_KEY)),
                    Integer.parseInt(properties.getProperty(properties.SCR_HEIGHT_KEY))
      );
      frame.setVisible(true);
      frame.cascadeWindows();
      return frame;
    }
    catch( Exception ex ){
      JOptionPane.showMessageDialog( apl, ex, "JavaNNS couldn't start", JOptionPane.ERROR_MESSAGE );
      ex.printStackTrace();
      if( apl != null ) apl.stop();
      else System.exit(0);
      return null;
    }
  }


  /**
   * Formats a double to a maximum of <code>m</code> digits behind the point.
   * Discards any trailing zeros.
   *
   * @param x The double to be formated.
   * @param m The maximum number of digits behind the decimal point.
   * @return  String containing formated number.
   */
  public static String maxFixPoint(double x, int m) {
    if(m <= 0) return String.valueOf((int)x);
    String s;
    if(Math.abs(x) < Math.pow(10, -m)) s = "0.00000000000000000000000000000000000";
    else s = String.valueOf(x);
    int i = s.indexOf('.');
    if(i<0) return s;
    if(s.length() >= i+m+1) s = s.substring(0, i+m+1);
    while( s.endsWith("0") ) s = s.substring(0, s.length()-1);
    if(s.endsWith(".")) s = s.substring(0, s.length()-1);
    return s;
  }

  /**
   * Formats a double to <code>m</code> digits behind the point.
   * Displays trailing zeros, if any.
   *
   * @param x The double to be formated.
   * @param m Number of digits behind the decimal point.
   * @return  String containing formated number.
   */
  public static String fixPoint(double x, int m) {
    if(m <= 0) return String.valueOf((int)x);
    String s;
    if(Math.abs(x) < Math.pow(10, -m)) s = "0.00000000000000000000000000000000000";
    else s = String.valueOf(x);
    int i = s.indexOf('.');
    if(i<0) {
      s = s + ".00000000000000000000000000000000000";
      i = s.indexOf('.');
    }
    if(s.length() >= i+m+1) return s.substring(0, i+m+1);
    while( s.length() < i+m+1 ) s = s +"0";
    return s;
  }

  /**
   * adds a new frame to the desktop
   *
   * @param the internal frame
   */
  public void addInternalFrame( final JInternalFrame frame, boolean visible ){
    /*System.out.println("Snns.addInternalFrame(): "+evt.getMessage());
    int no = desktop.getComponentCount();
    System.out.println("Snns contains "+no+" components:");
    for( int i=0; i<no; i++ ) {
      java.awt.Component c = desktop.getComponent(i);
      if( c instanceof JInternalFrame ) {
        JInternalFrame f = (JInternalFrame)c;
        java.awt.Container cont = f.getContentPane();

⌨️ 快捷键说明

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