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

📄 networkview.java

📁 著名的神经网络工具箱
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
   */
  private boolean updatePositions(){
    if( delta.x == 0 && delta.y == 0 ) return false;
    int dx = delta.x / settings.grid_size,
        dy = delta.y / settings.grid_size;
    network.moveUnits( network.getSelectedUnits(), new int[]{ dx, dy } );
    delta.x = delta.y = 0;
    return true;
  }


  /**
   * builds a rectangle around the given coordinates and paints it
   */
  private void buildRectangle(){
    int x, y, width, height;
    x = Math.min( startPoint.x, endPoint.x );
    y = Math.min( startPoint.y, endPoint.y );
    width = Math.abs( startPoint.x - endPoint.x ) + 1;
    height = Math.abs( startPoint.y - endPoint.y ) + 1;
    rectangle = new Rectangle( x, y, width, height);
    repaint( rectangle );
  }

  /**
   * checks if mouse made a significant move while dragging units
   * decides to repaint the network
   */
  private void checkStepSize( Point p ){
    int dirX = ( p.x > endPoint.x )? 1 : -1,
        dirY = ( p.y > endPoint.y )? 1 : -1,
        dx = ( p.x - endPoint.x + dirX * (settings.grid_size>>1)) / settings.grid_size,
        dy = ( p.y - endPoint.y + dirY * (settings.grid_size>>1)) / settings.grid_size;
    if( dx!= 0 || dy != 0 ){
      endPoint.x += dx * settings.grid_size;
      endPoint.y += dy * settings.grid_size;
      delta.x = endPoint.x - startPoint.x;
      delta.y = endPoint.y - startPoint.y;
      repaint();
    }
  }

  private void mouseMovedTo(Point p){
    grid_x = (p.x - 1 - settings.width + (settings.grid_size>>1)) / settings.grid_size;
    grid_y = (p.y - font_height - 1 + ((settings.grid_size - settings.height)>>1))/ settings.grid_size;
    setToolTipText( "(" + grid_x + ", " + grid_y  + ")" );
  }

  protected void close(){
    network.removeListener( this );
    fireEvent( NetworkViewEvent.VIEW_CLOSED );
  }

/*-------------------- private methods for direct edit -----------------------*/

  private void prepareLabels(){
    labels = new JTextField[ network.getNumberOfUnits() ];
    for( int i=0; i<labels.length; i++ ) {
      labels[ i ] = new JTextField( 5 );
      labels[ i ].setHorizontalAlignment(JTextField.CENTER);
      labels[ i ].setFont(settings.font);
      labels[ i ].setBorder( BorderFactory.createLineBorder(settings.text_color) );
      Dimension d = labels[ i ].getPreferredSize();
      labels[ i ].setSize( d.width, font_ascent+2 );
      labels[ i ].setVisible( true );
      add( labels[ i ] );

      labels[i].addKeyListener(
        new KeyAdapter() {
          public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == e.VK_ESCAPE) {
              deleteLabels();
              edit_top_labels = edit_bottom_labels = false;
              fireEvent(NetworkViewEvent.SETTINGS_CHANGED);
              network.fireEvent( NetworkEvent.UNIT_VALUES_EDITED );
              repaint();
            }
            else if(e.getKeyCode() == e.VK_ENTER) evaluateDirectEdit(true);
          }
        }
      );
    }
    fillLabels();
  }

  private void fillLabels(){
    if( labels == null ) return;
    String label;
    Unit unit;
    for( int i=0; i<labels.length; i++ ) {
      unit = network.getUnitNumber( i + 1 );
      switch( labels_to_edit ) {
        case NetworkViewSettings.ACT:       label = Snns.maxFixPoint(unit.getActivation(), 3); break;
        case NetworkViewSettings.INIT_ACT:  label = Snns.maxFixPoint(unit.getInitAct(), 3); break;
        case NetworkViewSettings.OUTPUT:    label = Snns.maxFixPoint(unit.getOutput(), 3); break;
        case NetworkViewSettings.BIAS:      label = Snns.maxFixPoint(unit.getBias(), 3); break;
        case NetworkViewSettings.NAME:      label = unit.getName(); break;
        case NetworkViewSettings.NUMBER:    label = String.valueOf(unit.getNumber()); break;
        case NetworkViewSettings.Z_VAL:     label = String.valueOf( unit.getPosition()[2] ); break;
//      case NetworkViewSettings.WINNER:    label = ;
        default:      label = "";
      }
      labels[ i ].setText( label );
    }
  }

  /**
   * method gives the units their new values
   */
  private void labels2units( boolean delete_edit_labels ) throws Exception{
    if( under_construction ) System.out.println("NetworkView.labels2units()");
    switch( labels_to_edit ) {
      case NetworkViewSettings.NAME:      names2units( delete_edit_labels ); return;
      case NetworkViewSettings.Z_VAL:     zPos2units( delete_edit_labels ); return;
    }
    double v = 0.0;
    Unit unit;
    for( int i=0; i<labels.length; i++ ){
      unit = network.getUnitNumber( i + 1 );
      try{ v = Double.valueOf( labels[ i ].getText() ).doubleValue(); }
      catch( Exception e ){
        throw new Exception("Value at unit " + ( i + 1 ) + " has to be a double value");
      }
      switch( labels_to_edit ){
        case NetworkViewSettings.ACT:       unit.setActivation( v ); break;
        case NetworkViewSettings.INIT_ACT:  unit.setInitAct( v ); break;
        case NetworkViewSettings.OUTPUT:    unit.setOutput( v ); break;
        case NetworkViewSettings.BIAS:      unit.setBias( v ); break;
      }
    }
  }

  private void names2units( boolean delete_edit_labels ){
    String name;
    Unit unit;
    for( int i=0; i<labels.length; i++ ){
      unit = network.getUnitNumber( i + 1 );
      unit.setName( labels[ i ].getText() );
    }
  }

  private void zPos2units( boolean delete_edit_labels ) throws Exception{
    int[] pos;
    Unit unit;
    for( int i=0; i<labels.length; i++ ){
      unit = network.getUnitNumber( i + 1 );
      pos = unit.getPosition();
      try{ pos[2] = Integer.parseInt( labels[ i ].getText() ); }
      catch( Exception e ){
        throw new Exception("Z-Position of unit " + ( i + 1 ) + " has to be an integer value");
      }
      unit.setPosition( pos );
    }
  }

  private void deleteLabels(){
    if( under_construction ) System.out.println("NetworkView.deleteLabels()");
    for( int i=0; i<labels.length; i++ )
      remove( labels[ i ] );
    labels = null;
  }

/*------------------------ interfaces ----------------------------------------*/
// implementing NetworkListener :
  /**
   * repaints the view when the network has changed
   */
  public void networkChanged( NetworkEvent evt ){
    if( under_construction ) System.out.println("NetworkView.networkChanged(): "+evt);
    int type = evt.id;

    if( type == NetworkEvent.NETWORK_NAME_CHANGED ){
      frame.setTitle( network.getName() + " <" + net_view_no + ">" );
      frame.repaint();
    }

    else if( type == NetworkEvent.NETWORK_DELETED      ||
             type == NetworkEvent.NEW_NETWORK_LOADED   ){
      frame.setTitle( network.getName() + " <" + net_view_no + ">" );
      if( isDirectEdit() ) deleteLabels();
      frame.repaint();
    }

    else if( type == NetworkEvent.UNITS_CREATED ){
      if( isDirectEdit() ){
        deleteLabels();
        prepareLabels();
      }
      Unit[] units = (Unit[])evt.arg;
      int i, x = 0, y = 0, h, v;
      int[] pos;
      for( i=0; i<units.length; i++ ){
        pos = units[i].getPosition();
        if( pos[0] > x ) x = pos[0];
        if( pos[1] > y ) y = pos[1];
      }
      JViewport viewPort = scrollPane.getViewport();
      Rectangle r = viewPort.getViewRect();
      Point p;
      x = X(x); y = Y(y);
      if( !r.contains( x, y ) ){
        h = x - r.width + (settings.grid_size>>1);
        if( h < 0 ) h = 0;
        v = y - r.height + (settings.grid_size>>1);
        if( v < 0 ) v = 0;
        view_position = new Point( h, v );
      }
      repaint();
    }

    else if( type == NetworkEvent.UNITS_DELETED ){
      if( isDirectEdit() ){
        deleteLabels();
        prepareLabels();
      }
      repaint();
    }

    else if( type == NetworkEvent.PATTERN_CHANGED ){
      if( isDirectEdit() ) fillLabels();
      repaint();
    }

    else if( evt.id == NetworkEvent.NETWORK_INITIALIZED ||
             evt.id == NetworkEvent.UNIT_VALUES_EDITED  ||
             evt.id == NetworkEvent.SELECTED_UNITS_CHANGED ||
             evt.id == NetworkEvent.LINKS_CREATED ||
             evt.id == NetworkEvent.LINKS_DELETED ||
             evt.id == NetworkEvent.NETWORK_UPDATED ||
             evt.id == NetworkEvent.UNITS_MOVED ||
             evt.id == NetworkEvent.NETWORK_TRAINED ||
             evt.id == NetworkEvent.NETWORK_PRUNED ||
             evt.id == NetworkEvent.SUBPATTERN_CHANGED) repaint();
  }

  public Dimension getMinimumSize(){
    Dimension min = super.getMinimumSize();
    if( min.width < 400 ) min.width = 400;
    if( min.height < 300 ) min.height = 300;
    return min;
  }

// implementing Scrollable :
    /**
     * Returns the preferred size of the viewport for a view component.
     * For example the preferredSize of a JList component is the size
     * required to acommodate all of the cells in its list however the
     * value of preferredScrollableViewportSize is the size required for
     * JList.getVisibleRowCount() rows.   A component without any properties
     * that would effect the viewport size should just return
     * getPreferredSize() here.
     *
     * @return The preferredSize of a JViewport whose view is this Scrollable.
     * @see JViewport#getPreferredSize
     */
    public Dimension getPreferredScrollableViewportSize(){
      return getPreferredSize();
    }


    /**
     * Components that display logical rows or columns should compute
     * the scroll increment that will completely expose one new row
     * or column, depending on the value of orientation.  Ideally,
     * components should handle a partially exposed row or column by
     * returning the distance required to completely expose the item.
     * <p>
     * Scrolling containers, like JScrollPane, will use this method
     * each time the user requests a unit scroll.
     *
     * @param visibleRect The view area visible within the viewport
     * @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
     * @param direction Less than zero to scroll up/left, greater than zero for down/right.
     * @return The "unit" increment for scrolling in the specified direction
     * @see JScrollBar#setUnitIncrement
     */
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction){
      if( orientation == SwingConstants.VERTICAL ) return settings.height;
      else return settings.width;
    }


    /**
     * Components that display logical rows or columns should compute
     * the scroll increment that will completely expose one block
     * of rows or columns, depending on the value of orientation.
     * <p>
     * Scrolling containers, like JScrollPane, will use this method
     * each time the user requests a block scroll.
     *
     * @param visibleRect The view area visible within the viewport
     * @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL.
     * @param direction Less than zero to scroll up/left, greater than zero for down/right.
     * @return The "block" increment for scrolling in the specified direction.
     * @see JScrollBar#setBlockIncrement
     */
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction){
      return settings.grid_size ;
    }


    /**
     * Return true if a viewport should always force the width of this
     * Scrollable to match the width of the viewport.  For example a noraml
     * text view that supported line wrapping would return true here, since it
     * would be undesirable for wrapped lines to disappear beyond the right
     * edge of the viewport.  Note that returning true for a Scrollable
     * whose ancestor is a JScrollPane effectively disables horizontal
     * scrolling.
     * <p>
     * Scrolling containers, like JViewport, will use this method each
     * time they are validated.
     *
     * @return True if a viewport should force the Scrollables width to match its own.
     */
    public boolean getScrollableTracksViewportWidth(){ return false;  }

    /**
     * Return true if a viewport should always force the height of this
     * Scrollable to match the height of the viewport.  For example a
     * columnar text view that flowed text in left to right columns
     * could effectively disable vertical scrolling by returning
     * true here.
     * <p>
     * Scrolling containers, like JViewport, will use this method each
     * time they are validated.
     *
     * @return True if a viewport should force the Scrollables height to match its own.
     */
    public boolean getScrollableTracksViewportHeight(){ return false; }

  // implementing Printable:
  public int print( Graphics g, PageFormat pf, int pi ){
    if( pi >= 1 ) return Printable.NO_SUCH_PAGE;
    scrollPane.setHorizontalScrollBarPolicy(
      ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER
    );
    scrollPane.setVerticalScrollBarPolicy(
      ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER
    );
    frame.getContentPane().validate();
    PagePrinter printer = new PagePrinter( frame.getContentPane(),g , pf );
    printer.fit_in_possible = false;
    int ret = printer.print();
    scrollPane.setHorizontalScrollBarPolicy(
      ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
    );
    scrollPane.setVerticalScrollBarPolicy(
      ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED
    );
    frame.getContentPane().validate();
    return ret;
  }
}


⌨️ 快捷键说明

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