lunes, 27 de mayo de 2013

Algoritmos geneticos

En este blog se han visto sobre unas practicas sobre los temas de automatización, ACO (ant colony optimization), algo de redes neuronales y como instalar un sistema multiagentes.

Pero ahora se vera una explicación sobre un tema no visto, el de algoritmos genéticos.

¿En que consiste?
El algoritmo genético consiste en obtener un resultado mediante los valores de una población o grupo y de esa población determinar quien tiene el valor mas alto. Para que esa población pueda incrementar sus valores se rendara que mejorar la población, para ello la población anterior hereda sus valores a unos nuevos individuos aunque esto signifique que la población anterior tenga que morir.

Pasos de un algoritmo genético
1.- Se crea la población de la primera generación, cada uno con un valor aleatorio.
2.- De esa población se determina quien tiene el valor mas alto.
3.- Se toma el valor mas alto y se guarda para hacer una comparación en las futuras generaciones.
4.- Se toman todos los valores, se suman y con el valor total se divide esto
valor del individuo/valor total, y el que tenga el mayor porcentaje es el que tendrá mas posibilidades de heredar sus valores.
5.- Para la nueva generación se toman todos los valores y se selecciona al azar dos individuos para heredar sus funciones, el cual consiste en separar sus valores de cadena binaria en dos y estos se juntan para hacer los hijos, este proceso se repite hasta que se tenga el mismo numero de individuos.
Ej: padre: 1110 madre:1001 → hijo1: 1101 hijo2: 1010
5.5.- En cualquier momento puede ocurrir una mutación al momento de que los dos individuos hagan un hijo, este valor puede cambiar significativamente al hijo y puede tomar el valor que el programador desee, pero se recomienda que sea pequeño ya que el objetivo es tener valores mediante la formación de hijos, no mediante la alteración de los valores.
6.- De la nueva generación se determina el valor mas alto, si es mayor que el registrado entonces se cambia el valor anterior por el nuevo.
7.- Se repiten los procesos del 3 al 6 por un determinado tiempo hasta que se obtenga un valor satisfactorio.

¿Para qué sirve un algoritmo genético?
Sirve para buscar soluciones de optimización para ahorrar tiempo, sirve para ver cual es la mejor combinación en un juego o en un problema, básicamente es utilizado en situaciones en las cuales se tiene una combinación y se quiere saber cual es la mejor opción para resolverlo.

Ademas es una técnica mejor que la fuerza bruta.

jueves, 16 de mayo de 2013

Practica #3



Introducción
Reconocimiento de caracteres por medio de redes neuronales  ¿De qué trata?
El reconocimiento de caracteres engloba un conjunto de métodos y algoritmos, los cuales permiten realizar una fase de “entrenamiento” que al final permitirán a nuestro programa reconocer de forma automática caracteres.

Objetivo
Elaborar una aplicación que al darle una imagen, reconozca los caracteres, números o letras, mediante el uso de redes neuronales.

Justificación
Elegimos este proyecto porque hoy en día la mayoría de los dispositivos móviles tienen la función del reconocimiento, sea facial, o mediante letras y números que el usuario dibuja en la pantalla. Además de que el área de redes neuronales es bastante usada en este ámbito; uno de los métodos más usados es el denominado “Backpropagation” que es una técnica de aprendizaje automático, que nos va a permitir el obtener resultados óptimos, minimizando los errores y así ir obteniendo el carácter más parecido al que el usuario dibujo.

Pseudocódigo, ¿Qué va a hacer nuestra aplicación?
 1.- El programa pregunta por la imagen que vamos a usar para reconocer.
 2.- Elegimos una imagen hecha con Paint o alguna fotografía con pocas letras o números, el programa procesa la imagen
 3.- Arroja un reconocimiento preliminar, pueden haber fallos de reconocimiento al principio
 4.- Realizamos los mismos pasos con distintas imágenes para entrar a una fase de “alimentación” al programa y nos arroje un mejor resultado.

Librerias a usar
Las librerias que se utilizaran para facilitar nuestro proceso son las siguentes
 >Opencv Esta librería nos ayudara a poder utilizar funciones las cuales nos ayudara tanto en el espacio geometrico, y en describir patrones los cuales noa ayudaran a describir los simbolos
>fann esta librería nos facilitara el uso de hacer neuronas en vez de tener que hacerlo desde 0.
Martiz
[code]package redesneuronales;
import java.text.DecimalFormat;
/**
 *Clase Matriz
 *Clase que define objetos matriz para realizar operaciones de matrices
 * de forma rápida y sencilla
 * @author Pablo Borbón
 */
public class Matriz {
//Campos
int fil=0;
int col=0;
double mat[][];


//Constructures sobrecargados

/**
 *Contructor Matriz
 * @param m Arreglo bidimensional de double
 */
public Matriz(double m[][]){
this.mat=m;
this.fil=m.length;
this.col=m[0].length;
}

/**
 *Constructor Matriz
 * @param m Arreglo unidimensional de double
 */
public Matriz(double m[]){
this.mat=new double[1][m.length];
for (int i=0;i<m.length;i++){
this.mat[0][i]=m[i];
this.fil=1;
this.col=m.length;
}
}

/****************************************************************************
 * MÉTODOS
 ****************************************************************************
 */
/**
 * Obtener número de columnas
 * @param m Matriz
 * @return int NumColumnas
 */

public static int getCol(Matriz m){
return m.col;
}

/**
 * Obtener número de columnas
 * @return int NumColumnas
 */
public int getCol(){
return this.col;
}

/**
 * Obtener número de columnas
 * @return String NumColumnas
 */
public String getColString(){
return String.valueOf(this.col);
}

/**
 * Obtener número de filas
 * @param m Matriz
 * @return int NumFilas
 */
public static int getFil(Matriz m){
return m.fil;
}

/**
 * Obtener número de filas
 * @return int NumFilas
 */
public int getFil(){
return this.fil;
}

/**
 * Obtener número de filas
 * @return String NumFilas
 */
public String getFilString(){
return String.valueOf(this.fil);
}

/**
 * Convertir matriz en array
 * @return Double array[][]
 */
public double[][] toArray(){
return this.mat;
}

/**
 * Convertir matriz en array
 * @param m Matriz
 * @return Double array[][]
 */
public static double[][] toArray(Matriz m){
return m.mat;
}


/**
 *Colocar valor en posicion[f][c]
 * @param f índice de fila
 * @param c índice de columna
 * @param value Valor que se coloca en el arreglo de la matriz
 */
public void setFC(int f,int c, double value){
this.mat[f][c]=value;
}


/**
 *Obtener valor en posición[f][c]
 * @param f índice fila
 * @param c índice columna
 * @return double valor
 */
public double getFC(int f,int c){
return this.mat[f][c];
}


/**
 *Convertir la matriz en un String
 * @param m Matriz a convertir
 * @return String con las filas y las columnas de la matriz
 * debidamente ordenadas.
 */
public static String toStringM(Matriz m){
DecimalFormat df = new DecimalFormat("0.00");
StringBuffer mat1= new StringBuffer();
 for (int j=0;j<m.getFil();j++){

     for (int i=0;i<m.getCol();i++){
            mat1.append(" ");
            mat1.append(df.format(m.toArray()[j][i]));
            }
        mat1.append("\n");
 }
String salida = mat1.toString();
return salida;
}

/**
 *Convertir Matriz a String
 @return String con las filas y las columnas de la matriz
 * debidamente ordenadas.
 */
public String toStringM(){
DecimalFormat df = new DecimalFormat("0.00");
StringBuffer mat1= new StringBuffer();
 for (int j=0;j<this.getFil();j++){

     for (int i=0;i<this.getCol();i++){
            mat1.append(" ");
            mat1.append(df.format((this.toArray()[j][i])));
            }
        mat1.append("\n");
 }
String salida = mat1.toString();
return salida;
}


/**
 *Transponer matriz
 * @param m matriz a transponer
 * @return Matriz m'
 */
public static Matriz transponer(Matriz m){
double retorno[][];
retorno=new double[m.getCol()][m.getFil()];

for (int i=0; i<m.getFil();i++){
        for (int j=0; j<m.getCol();j++){

            retorno[j][i]=m.toArray()[i][j];

        }
}
Matriz ret= new Matriz(retorno);
return ret;
}

/**
 *Sumar matrices
 * @param mA sumandoA
 * @param mB sumandoB
 * @return Matriz (ma+mB)
 */
public static Matriz sumar(Matriz mA, Matriz mB){
double retorno[][];
retorno=new double[mB.getFil()][mB.getCol()];
Matriz ret= new Matriz(retorno);
for (int i=0; i<mA.getFil();i++){
        for (int j=0; j<mA.getCol();j++){

           ret.setFC(i, j, (mA.getFC(i, j)+mB.getFC(i, j)));

        }
}

return ret;
}

/**
 *Restar matrices
 * @param mA Minuendo
 * @param mB Sustraendo
 * @return Matriz diferencia= mA-mB
 */
public static Matriz restar(Matriz mA, Matriz mB){
double retorno[][];
retorno=new double[mB.getFil()][mB.getCol()];
Matriz ret= new Matriz(retorno);
for (int i=0; i<mA.getFil();i++){
        for (int j=0; j<mA.getCol();j++){

           ret.setFC(i, j, (mA.getFC(i, j)-mB.getFC(i, j)));

        }
}

return ret;
}

/**
 *Multiplicar matrices
 * @param mA factor A
 * @param mB factor B
 * @return mAxmB
 * La matriz de retorno tiene dimensions [fA]x[cB]
 */
public static Matriz multiplicar(Matriz mA, Matriz mB){
double retorno[][];
double tmp=0;
retorno=new double[mA.getFil()][mB.getCol()];
Matriz ret= new Matriz(retorno);

for (int i=0; i<mA.getFil();i++){
       
    for (int j=0; j<mB.getCol();j++){
                tmp=0;
                  for (int k=0; k<mA.getCol();k++){

                   tmp+=mA.getFC(i,k)*mB.getFC(k, j);

                }
                ret.setFC(i, j, tmp);
        }
}
return ret;
}

/**
 *Calcular la respueta más probable
 * @param resp Matriz con las respuestas de la simulación [1]x[10]
 * @param nom Arreglo de Strings con los nombres de los patrones
 * @return String con el patrón más probable del arreglo
 */
public  static String masProbable(Matriz resp,String nom[]){
int index=0;
double tmp=resp.toArray()[0][0];
    for (int i=1;i<resp.toArray()[0].length;i++){

            if(resp.toArray()[0][i]>tmp){
                tmp=resp.toArray()[0][i];
                index=i;
            }
    }
return nom[index];
}

/**
 *Obtener columna
 * @param index índice de la columna a obtener
 * @return Matriz Columna con todos los valores de la columna indicada
 */
public  Matriz getColumna(int index){
double tmp[][]= new double [this.getFil()][1];

    for (int i=0;i<this.getFil();i++){
    tmp[i][0]=this.toArray()[i][index];
    }
Matriz retorno = new Matriz(tmp);
return retorno;

}


/**
 *Multiplicar Matriz por escalar
 * @param m Matriz a multiplicar
 * @param esc factor escalar
 * @return Matriz escalada
 */
public static Matriz multEscalar(Matriz m, double esc){

 double tmp [][]= new double [m.getFil()][m.getCol()];
    for (int i=0;i<m.getFil();i++){

             for (int j=0;j<m.getCol();j++){
             tmp[i][j]=m.toArray()[i][j]*esc;
            }

    }

Matriz ret = new Matriz (tmp);
return ret;
}

/**
 *Multiplicar elementos entre matrices
 * @param m1 Matriz 1
 * @param m2 Matriz 2
 * @return Devuelve una matriz con las mismas dimensiones
 * con los productos de los elementos de cada matriz
 */
public static Matriz multElementos(Matriz m1, Matriz m2){

 double tmp [][]= new double [m1.getFil()][m2.getCol()];
    for (int i=0;i<m1.getFil();i++){

             for (int j=0;j<m1.getCol();j++){
             tmp[i][j]=m1.toArray()[i][j]*m2.toArray()[i][j];
            }

    }

Matriz ret = new Matriz (tmp);
return ret;
}


}
[/code]

Red
[code]package redesneuronales;
import java.util.Random;
import java.lang.Math.*;

/**
 * ´
 *Clase Red:Define las matrices de pesos, los métodos de entrenamiento, de propagación
 * y en general todos los aspectos de campos y funcionalidad de la red neuronal
 * propuesta como trabajo e implementada en Java
 * @author Pablo Borbón
 */
public class Red {
   
    Matriz wI;//matriz de pesos de entrada-oculta 18x35
    Matriz wO;//matriz de pesos de oculta salida 10x18
    Matriz trainMP;//matriz 10 patrones de entrada 35x10
    Matriz trainMT;//matriz de 10 patrones de salida 10x10
    Random generadorAl = new Random();//PAra inicializar los pesos
    int epocas=0;



    //CONSTRUCTORES


    /**
     *Constructor con matrices de patrones
     * @param mP1 Matriz de patrones de entrada [35x10]
     * @param mT1 Matriz de objetivos [10x10]
     */
    public Red(Matriz mP1, Matriz mT1){

this.trainMP=mP1;
this.trainMT=mT1;
}

/**
 *Constructor vacío
 */
public Red(){

}





// METODOS

/**
 *Establecer pesos
 * Coloca las matrices de la capa oculta y la capa de salida en
 * el objeto Red.
 * @param pesosI pesos de la capa oculta
 * @param pesosO pesos de la capa de salida
 */
public void setPesos(Matriz pesosI, Matriz pesosO){
this.wI=pesosI;
this.wO=pesosO;
}

/**
 *Inicializar red
 * Inicializa los pesos de la red neuronal pasada como parámetro
 * con un número aleatorio dentro de una distribución de probabilidad
 * Gaussiana con valores entre [-0.5,0.5]
 * @param redNeu Red Neuronal Objetivo
 */
public static void init(Red redNeu){
double tempI[][]=new double [18][35];
double tempO[][]=new double [10][18];
    for (int i=0;i<18;i++){
        for (int j=0;j<35;j++){
        tempI[i][j]=redNeu.generadorAl.nextGaussian()*0.5;
        }
    }

for (int i=0;i<10;i++){
        for (int j=0;j<18;j++){
        tempO[i][j]=redNeu.generadorAl.nextGaussian()*0.5;
        }
    }

redNeu.wI= new Matriz(tempI);
redNeu.wO= new Matriz(tempO);
}

/**
 * Obtener Wi
 * Devuelve la matriz de pesos de la capa oculta
 * @return Matriz Wi [18x35]
 */
public Matriz getWi(){
return this.wI;
}

/**
 *Obtener Wo
 * Devuelve la matriz de pesos de la capa de salida
 * @return Matriz Wo[10x18]
 */
public Matriz getWo(){
return this.wO;
}

/**
 *Obtener patrones de entrada
 * Devuelve la matriz con los patrones de entrada de entrenamiento
 * @return Matriz patronesEntrada[35x10]
 */
public Matriz getTrainMP(){
return this.trainMP;
}

/**
 *Obtener salidas objetivo
 * devuelve la matriz con los objetivos de entrenamiento
 * @return Matriz con los vectores de salida
 * @ Matriz salidas [10x10]
 */
public Matriz getTrainMT(){
return this.trainMT;
}


/**
 *fNetLog
 * Evalúa la  función sigmoidal 1/(1+e^-n) de un valor dado
 * @param value valor a evaluar
 * @return
 * @return1/(1+e^-value)
 */
public static double fNetLog(double value){
double num=1;
double den=0;
double f;
double exp=(-1)*value;
den=(1 + Math.pow(Math.E, (exp)) );
f=num/den;
return f;
}

/**
 *f prima de net
 * Evalúa la primera derivada de la función sigmoidal 1/(1+e^-n)
 * @param value valor a evaluar
 * @return (1/(1+e^-n))*(1-1/(1+e^-n))
 */
public static double fPrimaNetLog(double value){
double f;

f=Red.fNetLog(value)*(1-Red.fNetLog(value));
return f;
}



/**
 *F (net) a matriz
 * Evalúa la función sigmoidal a toda una matriz
 * @param mat matriz a evaluar
 * @return Matriz con sus elementos evaluados
 */
public static Matriz fNetMatrizLog(Matriz mat){
  double retorno[][];
  retorno=new double[mat.getFil()][mat.getCol()];
  Matriz res = new Matriz(retorno);

  for (int i=0;i<mat.getFil();i++){

        for (int j=0;j<mat.getCol();j++){

        res.setFC(i, j, Red.fNetLog(mat.getFC(i, j)));

        }

 }
return res;

}

/**
 *Evaluar f'(net) a matriz
 * Evalúa la derivada de la función sigmoidal a toda una matriz
 * @param mat matriz a evaluar
 * @return Matriz con sus elementos evaluados
 */
public static Matriz fNetPrimaMatrizLog(Matriz mat){
  double retorno[][];
  retorno=new double[mat.getFil()][mat.getCol()];
  Matriz res = new Matriz(retorno);

  for (int i=0;i<mat.getFil();i++){

        for (int j=0;j<mat.getCol();j++){

        res.setFC(i, j, Red.fPrimaNetLog(mat.getFC(i, j)));

        }

 }
return res;

}


/**
 *Simular Red Neuronal
 * Simula el comportamiento de la red neuronal.
 * Multiplica matrices, evalua las funciones de propagación y en general
 * propaga la red hacia adelante.
 * @param redNeu Red Neuronal modelo
 * @param Ventrada Vector de entrada a evaluar[35x1]
 * @return Matriz con un vector de respuestas de la red [10x1]
 */
public static Matriz simNet(Red redNeu, Matriz Ventrada){
//Ventrada 35x1
Matriz netI;
Matriz fNetI;

Matriz netO;
Matriz fNetO;


//MULTIPLICACION [NET]=[WI][XI]
netI= Matriz.multiplicar(redNeu.getWi(), Ventrada);
fNetI = Red.fNetMatrizLog(netI);

//MULTIPLICACION [NET]=[WO][FNETO]
netO= Matriz.multiplicar(redNeu.getWo(), fNetI);
fNetO = Red.fNetMatrizLog(netO);

return fNetO;
//salida de 10x1
}

/**
 *Establecer épocas
 * Establece el número de épocas de entrenamiento han transcurrido
 * en un proceso de entrenamiento tras la condición de salida
 * @param num contador de épocas
 */
public void setEpocas(int num){
this.epocas=num;
}

/**
 *Obtener el número de épocas
 * Devuelve el número de épocas que tuvo una red para alcanzar la condición
 * de salida.
 * @return int numEpocas
 */
public int getEpocas(){
return this.epocas;
}

/**
 *Obtener Error cuadrático
 * @param errores Matriz con los errores (yd-o)[10x1]
 * @return Double con la sumatoria de los errores al cuadrado multiplicado
 * por 1/2
 */
public static double getErrorCuadratico(Matriz errores){
double tmp=0;
        for (int i=0;i<errores.getFil();i++){
            tmp+=Math.pow(errores.getFC(i, 0), 2);
        }
tmp=tmp*0.5;
return tmp;
}

/**
 *Entrenar red neuronal
 * Entrena la red neuronal con el siguiente algoritmo:
 * <br>1.Se inicializa a red (valores aleatorios de wi y wo)
 * <br>2.huboError=true;
 *<br>
 * <br>Ciclo1.Mientras (epocas < iteracionesMáximas)&& (huboError==true))
 * <br>Ciclo2 for j=0;j<10;j++
 *<br>      3.Se presenta el patrón j y se propaga la red hacia adelante
 *<br>     4 Se calcula el error
 *<br>      Cond1 .If error>error:
 *<br>              -huboError
 *<br>              -Se propaga la red hacia atrás
 *<br>              -Se actualizan los pesos
 *<br>            
 *<br>
 *<br>           fin del ciclo2
 *<br>            epocas++;
 * <br>         fin del cliclo1
 *<br>El algoritmo se termina cuando todos los patrones tengan un valor de
 *error medio cuadrático menor que el establecido como parámetro o cuando
 *se supera el número máximo de iteraciones
 *
 * @param redNeu Red neuronal modelo
 * @param alpha factor de aprendizaje
 * @param error error objetivo por patrón
 * @param iteraciones numero máximo de iteraciones del algoritmo
 * @return String cadena con los resultados del entrenamiento
 */
public static String trainNetLog(Red redNeu,double alpha,double error, int iteraciones){

Red.init(redNeu);
    //Ventrada 35x1
int contEpocas=0;
int j=0;
Matriz netI;
Matriz fNetI;
Matriz fNetPrimaI;
Matriz wI;
Matriz eI;
Matriz dI;

Matriz netO;
Matriz fNetO;
Matriz fNetPrimaO;
Matriz wO;
Matriz eO;
Matriz dO;

double errG[]=new double[10];
double errGvalue=0;
double errP;
boolean huboError=true;

redNeu.setEpocas(0);

while((contEpocas<iteraciones)&&huboError==true){

huboError=false;
    for (j=0;j<10;j++){
//********************PASO HACIA ADELANTE*************************************
        //PROPAGAR LA CAPA OCULTA
        //[18x1] = [18x35] * [35x1] Net=WIxXI
        netI=Matriz.multiplicar(redNeu.getWi(), redNeu.getTrainMP().getColumna(j));
        //[18x1] = f([18x1])
        fNetI=Red.fNetMatrizLog(netI);

        //PROPAGAR LA SALIDA
        //[10x1] = [10x18] * [18x1]
        netO=Matriz.multiplicar(redNeu.getWo(),fNetI);
        //[10x1] = f([10x1])
        fNetO= Red.fNetMatrizLog(netO);

        //CALCULAR LOS ERRORES
        //[10x1] = [10x1] - [10x1] (yd-o)
        eO=Matriz.restar(redNeu.getTrainMT().getColumna(j), fNetO);

        //calcular el error cuadrático
        errP=Red.getErrorCuadratico(eO);
        errG[j]=errP;

//**************CONDICION DE ERROR : PASO HACIA ATRÁS**************************
        if(errP>error){

          huboError=true;

               //SE CALCULAN LAS DERIVADAS
               //[18x1] = f'([18x1])
                fNetPrimaI=Red.fNetPrimaMatrizLog(netI);

              //[10x1] = f'([10x1])
                fNetPrimaO=Red.fNetPrimaMatrizLog(fNetO);


            //CALCULAR dO
            //[10x1]=e[10x1]xe[10x1]  = (yd-o)*f'(netO)
            dO=Matriz.multElementos(eO, fNetPrimaO);


            //Calcular dI .. error propagado
            //[18x10]=[10x18]'T
            Matriz woT=Matriz.transponer(redNeu.getWo());
            //[18x1]=[18x10]x[10x1]
            Matriz tmp=Matriz.multiplicar(woT,dO);
            //[18x1]=e[18x1]xe[18x1]
            dI=Matriz.multElementos(tmp,fNetPrimaI);

            //ACTUALIZAR LOS PESOS
            //[10x18]=[10x1][18x1]'T
            Matriz deltaWO=Matriz.multEscalar(Matriz.multiplicar(dO,Matriz.transponer(fNetI)),alpha);
            wO=Matriz.sumar(redNeu.getWo(), deltaWO);

            //[18x35]=[18x1][35x1]'T
            Matriz deltaWI=Matriz.multEscalar(Matriz.multiplicar(dI,Matriz.transponer(redNeu.getTrainMP().getColumna(j))),alpha);
            wI=Matriz.sumar(redNeu.getWi(), deltaWI);


            //Se actualizan los pesos
            redNeu.setPesos(wI, wO);
          
            //Vuelve al primer patrón
     
        }
    }

 contEpocas++;//Una época más (iteración)
}
redNeu.setEpocas(contEpocas);


String ep=String.valueOf(redNeu.getEpocas());

if (huboError==false){

for (int i=0;i<10;i++)errGvalue+=errG[i];
 String errorG=String.valueOf(errGvalue);  
    return "¡Red entrenada con éxito!\n"+"Épocas: "+ep+"\nValor de error alcanzado\nError Global: "+errorG+"\n";

}else{
return "¡Red entrenada con éxito!\n"+"Épocas: "+ep+"\nValor de error NO alcanzado\n";
}



}


}[
/code] 
 RedesNeuronalesAboutBox
[code]package redesneuronales;

import org.jdesktop.application.Action;

/**
 * Ventana "Acerca de"
 * Muestra la información del curso, profesor, autor y el logo de la ECI
 * @author Pablo Borbón
 */
public class RedesNeuronalesAboutBox extends javax.swing.JDialog {

    /**
     *
     * @param parent
     */
    public RedesNeuronalesAboutBox(java.awt.Frame parent) {
        super(parent);
        initComponents();
        getRootPane().setDefaultButton(closeButton);
    }

    /**
     *
     */
    @Action public void closeAboutBox() {
        dispose();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        closeButton = new javax.swing.JButton();
        javax.swing.JLabel appTitleLabel = new javax.swing.JLabel();
        javax.swing.JLabel versionLabel = new javax.swing.JLabel();
        javax.swing.JLabel appVersionLabel = new javax.swing.JLabel();
        javax.swing.JLabel vendorLabel = new javax.swing.JLabel();
        javax.swing.JLabel appVendorLabel = new javax.swing.JLabel();
        javax.swing.JLabel homepageLabel = new javax.swing.JLabel();
        javax.swing.JLabel appHomepageLabel = new javax.swing.JLabel();
        javax.swing.JLabel appDescLabel = new javax.swing.JLabel();
        javax.swing.JLabel imageLabel = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(redesneuronales.RedesNeuronalesApp.class).getContext().getResourceMap(RedesNeuronalesAboutBox.class);
        setTitle(resourceMap.getString("title")); // NOI18N
        setModal(true);
        setName("aboutBox"); // NOI18N
        setResizable(false);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(redesneuronales.RedesNeuronalesApp.class).getContext().getActionMap(RedesNeuronalesAboutBox.class, this);
        closeButton.setAction(actionMap.get("closeAboutBox")); // NOI18N

        appTitleLabel.setFont(appTitleLabel.getFont().deriveFont(appTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, appTitleLabel.getFont().getSize()+4));
        appTitleLabel.setText(resourceMap.getString("Application.title")); // NOI18N

        versionLabel.setFont(versionLabel.getFont().deriveFont(versionLabel.getFont().getStyle() | java.awt.Font.BOLD));
        versionLabel.setText(resourceMap.getString("versionLabel.text")); // NOI18N

        appVersionLabel.setText(resourceMap.getString("Application.version")); // NOI18N

        vendorLabel.setFont(vendorLabel.getFont().deriveFont(vendorLabel.getFont().getStyle() | java.awt.Font.BOLD));
        vendorLabel.setText(resourceMap.getString("vendorLabel.text")); // NOI18N

        appVendorLabel.setText(resourceMap.getString("Application.vendor")); // NOI18N

        homepageLabel.setFont(homepageLabel.getFont().deriveFont(homepageLabel.getFont().getStyle() | java.awt.Font.BOLD));
        homepageLabel.setText(resourceMap.getString("homepageLabel.text")); // NOI18N

        appHomepageLabel.setText(resourceMap.getString("Application.homepage")); // NOI18N

        appDescLabel.setText(resourceMap.getString("appDescLabel.text")); // NOI18N

        imageLabel.setIcon(resourceMap.getIcon("imageLabel.icon")); // NOI18N

        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(imageLabel)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(versionLabel)
                            .addComponent(vendorLabel)
                            .addComponent(homepageLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(appVendorLabel)
                            .addComponent(appVersionLabel)
                            .addComponent(appHomepageLabel)))
                    .addComponent(appTitleLabel, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(appDescLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                    .addComponent(closeButton))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(imageLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 177, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(appTitleLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(appDescLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(versionLabel)
                    .addComponent(appVersionLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(vendorLabel)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(homepageLabel)
                    .addComponent(appHomepageLabel)
                    .addComponent(appVendorLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                .addComponent(closeButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                       
   
    // Variables declaration - do not modify                    
    private javax.swing.JButton closeButton;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                  
   
}
[
/code]
RedesNeuronalesView
[code]
 package redesneuronales;

import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.text.DecimalFormat;


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;





/**
 * La ventana principal de la aplicación. Elementos de la interfaz gráfica.
 */
public class RedesNeuronalesView  extends FrameView {

/****************************************************************************
 * VARIABLES DE INICIO
 *****************************************************************************/

int iX=0, iY=0;//Variables para la captura del dibujo
int contPatrones=0;//Variable para indicar el No de patrones ingresados
//Matriz para capturar el patrón en tiempo real
double matriz[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int ID=0;

double matPatrones[][]=new double[10][35];//Array temporal con los patrones
String nomPatrones[]= new String[10];//Array String con los nombres de los patrones
double matObjetivos[][]=new double[10][10];//Array con los valores objetivo

Red miRedJA=null;

Matriz entrada;


//MATRICES (OBJETOS)
Matriz patronesM;
Matriz objetivosM;




/**
 * Crear el fame principal
 * @param frame
 */
@Override
    public void setFrame(JFrame frame) {
        super.setFrame(frame);
      this.getFrame().setResizable(false);
    
    }



/**
 *
 * @param app
 */
public RedesNeuronalesView(SingleFrameApplication app) {
        super(app);
/****************************************************************************
 * RUTINAS DE INICIALIZACIÓN
 *****************************************************************************/

        //INICIAR VECTOR OBJETIVO
int pos=0;//variable para inicializar la matriz objetivo
        for (int i=0;i<10;i++){
                for (int j=0;j<10;j++){
                if(j==pos){
                    matObjetivos[i][j]=1;}
                else{
                 matObjetivos[i][j]=0;
                }
             
                }
                pos++;
        }


        //INICIO DEL FRAME Y MENSAJES DE BIENVENIDA
        initComponents();
        this.getFrame().setResizable(false);
        label5.setForeground(Color.red);
        label5.setText("APRENDIZAJE");
        label2.setText("Vector de entrada:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]");
        label7.setText("1");
        debug.setText("Iniciando la aplicación...\nEn ésta ventana apareceran los mensajes del sistema\n");
        debug.append("\nMODO DE APRENDIZAJE\n");
        debug.append("La red neuronal requiere 10 patrones de dibujo a mano alzada con sus respectivos nombres para configurarse.\n");
        debug.append("Por favor, dibuje la forma del patrón en el recuadro de dibujo.\n");
        debug.append("Luego introduzca un nombre para el patrón y de clic al botón \"Agregar patrón\"\n\n");
        entrenar.setEnabled(false);
        calcularJ.setEnabled(false);
     

       //OCULTACIÓN DE ELEMENTOS GRÁFICOS
    
  
   
      
      

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

/**
 *
 */
@Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = RedesNeuronalesApp.getApplication().getMainFrame();
            aboutBox = new RedesNeuronalesAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        RedesNeuronalesApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                        
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        zona = new java.awt.Canvas();
        label2 = new java.awt.Label();
        label3 = new java.awt.Label();
        label4 = new java.awt.Label();
        label5 = new java.awt.Label();
        textField1 = new java.awt.TextField();
        label6 = new java.awt.Label();
        label7 = new java.awt.Label();
        debug = new java.awt.TextArea();
        label8 = new java.awt.Label();
        label9 = new java.awt.Label();
        respuesta = new java.awt.Label();
        jLabel2 = new javax.swing.JLabel();
        label11 = new java.awt.Label();
        label1 = new java.awt.Label();
        button1 = new javax.swing.JButton();
        entrenar = new javax.swing.JButton();
        calcularJ = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setMaximumSize(new java.awt.Dimension(440, 280));
        mainPanel.setMinimumSize(new java.awt.Dimension(440, 280));
        mainPanel.setName("mainPanel"); // NOI18N
        mainPanel.setPreferredSize(new java.awt.Dimension(800, 600));
        mainPanel.setRequestFocusEnabled(false);
        mainPanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                mainPanelMouseEntered(evt);
            }
        });
        mainPanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                mainPanelMouseMoved(evt);
            }
        });

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(redesneuronales.RedesNeuronalesApp.class).getContext().getResourceMap(RedesNeuronalesView.class);
        zona.setBackground(resourceMap.getColor("zona.background")); // NOI18N
        zona.setName("zona"); // NOI18N
        zona.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                zonaMousePressed(evt);
            }
        });
        zona.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                zonaComponentShown(evt);
            }
        });
        zona.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                zonaMouseDragged(evt);
            }
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                zonaMouseMoved(evt);
            }
        });
        zona.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                zonaFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                zonaFocusLost(evt);
            }
        });
        zona.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                zonaPropertyChange(evt);
            }
        });

        label2.setAlignment(java.awt.Label.CENTER);
        label2.setName("label2"); // NOI18N
        label2.setText(resourceMap.getString("label2.text")); // NOI18N

        label3.setFont(resourceMap.getFont("label3.font")); // NOI18N
        label3.setForeground(resourceMap.getColor("label3.foreground")); // NOI18N
        label3.setName("label3"); // NOI18N
        label3.setText(resourceMap.getString("label3.text")); // NOI18N

        label4.setFont(resourceMap.getFont("label4.font")); // NOI18N
        label4.setName("label4"); // NOI18N
        label4.setText(resourceMap.getString("label4.text")); // NOI18N

        label5.setAlignment(java.awt.Label.CENTER);
        label5.setFont(resourceMap.getFont("label5.font")); // NOI18N
        label5.setName("label5"); // NOI18N
        label5.setText(resourceMap.getString("label5.text")); // NOI18N

        textField1.setName("textField1"); // NOI18N
        textField1.setText(resourceMap.getString("textField1.text")); // NOI18N

        label6.setName("labelPatron"); // NOI18N
        label6.setText(resourceMap.getString("labelPatron.text")); // NOI18N

        label7.setName("label7"); // NOI18N
        label7.setText(resourceMap.getString("label7.text")); // NOI18N

        debug.setBackground(resourceMap.getColor("debug.background")); // NOI18N
        debug.setEditable(false);
        debug.setFont(resourceMap.getFont("debug.font")); // NOI18N
        debug.setForeground(resourceMap.getColor("debug.foreground")); // NOI18N
        debug.setName("debug"); // NOI18N

        label8.setFont(resourceMap.getFont("label8.font")); // NOI18N
        label8.setName("label8"); // NOI18N
        label8.setText(resourceMap.getString("label8.text")); // NOI18N

        label9.setName("label9"); // NOI18N

        respuesta.setFont(resourceMap.getFont("respuesta.font")); // NOI18N
        respuesta.setForeground(resourceMap.getColor("respuesta.foreground")); // NOI18N
        respuesta.setName("respuesta"); // NOI18N
        respuesta.setText(resourceMap.getString("respuesta.text")); // NOI18N

        jLabel2.setIcon(resourceMap.getIcon("jLabel2.icon")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        label11.setFont(resourceMap.getFont("label11.font")); // NOI18N
        label11.setForeground(resourceMap.getColor("label11.foreground")); // NOI18N
        label11.setName("label11"); // NOI18N
        label11.setText(resourceMap.getString("label11.text")); // NOI18N

        label1.setAlignment(java.awt.Label.CENTER);
        label1.setFont(resourceMap.getFont("label1.font")); // NOI18N
        label1.setName("label1"); // NOI18N
        label1.setText(resourceMap.getString("label1.text")); // NOI18N

        button1.setText(resourceMap.getString("button1.text")); // NOI18N
        button1.setName("button1"); // NOI18N
        button1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button1ActionPerformed(evt);
            }
        });

        entrenar.setText(resourceMap.getString("entrenar.text")); // NOI18N
        entrenar.setName("entrenar"); // NOI18N
        entrenar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                entrenarActionPerformed(evt);
            }
        });

        calcularJ.setText(resourceMap.getString("calcularJ.text")); // NOI18N
        calcularJ.setName("calcularJ"); // NOI18N
        calcularJ.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calcularJActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap(232, Short.MAX_VALUE)
                .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(224, 224, 224))
            .addComponent(label2, javax.swing.GroupLayout.DEFAULT_SIZE, 826, Short.MAX_VALUE)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(133, 133, 133)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(calcularJ, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE)
                            .addComponent(label11, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(entrenar, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE))
                        .addGap(44, 44, 44)
                        .addComponent(jLabel2)
                        .addGap(174, 174, 174)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(label1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(zona, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))
                        .addGap(50, 50, 50)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(textField1, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(button1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18))
                    .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
                            .addComponent(label8, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(respuesta, javax.swing.GroupLayout.PREFERRED_SIZE, 453, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(label9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(debug, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 778, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(20, 20, 20))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(label4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(48, 48, 48)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(label6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(mainPanelLayout.createSequentialGroup()
                                        .addComponent(label7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(23, 23, 23)
                                .addComponent(button1))
                            .addGroup(mainPanelLayout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(mainPanelLayout.createSequentialGroup()
                                        .addComponent(label11, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(28, 28, 28)
                                        .addComponent(entrenar)
                                        .addGap(28, 28, 28)
                                        .addComponent(calcularJ))
                                    .addComponent(zona, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))))
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGap(76, 76, 76)
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(label8, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(label9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(label3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(respuesta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                        .addComponent(label5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(20, 20, 20)))
                .addComponent(debug, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(1, 1, 1)
                .addComponent(label2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(22, 22, 22))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N
        fileMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fileMenuActionPerformed(evt);
            }
        });

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(redesneuronales.RedesNeuronalesApp.class).getContext().getActionMap(RedesNeuronalesView.class, this);
        jMenuItem1.setAction(actionMap.get("reinciar")); // NOI18N
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        fileMenu.add(jMenuItem1);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setText(resourceMap.getString("exitMenuItem.text")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setText(resourceMap.getString("aboutMenuItem.text")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addGap(508, 508, 508)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusPanelLayout.createSequentialGroup()
                        .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(statusAnimationLabel)
                        .addContainerGap())))
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>                      

    private void zonaMousePressed(java.awt.event.MouseEvent evt) {                                
 /****************************************************************************
 * AREA DE DIBUJO: MOUSE PRESIONADO
 *****************************************************************************/
        //Capturo la posción del evento
         int fX = evt.getX();
        int fY = evt.getY();
        Graphics g=zona.getGraphics();


        iX=fX;
        iY=fY;
        int i;

     /*Código para llenar el vector de entrada
     Según la posición del puntero se determina la zona y se pone 1 o 0 en el
     vector correspondiente*/
        //Fila1
        if ((fY >0 && fY <=20)){
            if(fX >0 && fX <=20){matriz[0]=1;g.fillRect(0, 0, 20, 20);}
            if(fX >20 && fX <=40){matriz[1]=1;g.fillRect(20, 0, 20, 20);}
            if(fX >40 && fX <=60){matriz[2]=1;g.fillRect(40, 0, 20, 20);}
            if(fX >60 && fX <=80){matriz[3]=1;g.fillRect(60, 0, 20, 20);}
            if(fX >80 && fX <=100){matriz[4]=1;g.fillRect(80, 0, 20, 20);}
        }
         //Fila2
        if ((fY >20 && fY <=40)){
            if(fX >0 && fX <=20){matriz[5]=1;g.fillRect(0, 20, 20, 20);}
            if(fX >20 && fX <=40){matriz[6]=1;g.fillRect(20, 20, 20, 20);}
            if(fX >40 && fX <=60){matriz[7]=1;g.fillRect(40, 20, 20, 20);}
            if(fX >60 && fX <=80){matriz[8]=1;g.fillRect(60, 20, 20, 20);}
            if(fX >80 && fX <=100){matriz[9]=1;g.fillRect(80, 20, 20, 20);}
        }
         //Fila3
        if ((fY >40 && fY <=60)){
            if(fX >0 && fX <=20){matriz[10]=1;g.fillRect(0, 40, 20, 20);}
            if(fX >20 && fX <=40){matriz[11]=1;g.fillRect(20, 40, 20, 20);}
            if(fX >40 && fX <=60){matriz[12]=1;g.fillRect(40, 40, 20, 20);}
            if(fX >60 && fX <=80){matriz[13]=1;g.fillRect(60, 40, 20, 20);}
            if(fX >80 && fX <=100){matriz[14]=1;g.fillRect(80,40, 20, 20);}
        }
         //Fila4
        if ((fY >60 && fY <=80)){
            if(fX >0 && fX <=20){matriz[15]=1;g.fillRect(0, 60, 20, 20);}
            if(fX >20 && fX <=40){matriz[16]=1;g.fillRect(20, 60, 20, 20);}
            if(fX >40 && fX <=60){matriz[17]=1;g.fillRect(40, 60, 20, 20);}
            if(fX >60 && fX <=80){matriz[18]=1;g.fillRect(60, 60, 20, 20);}
            if(fX >80 && fX <=100){matriz[19]=1;g.fillRect(80, 60, 20, 20);}
        }
         //Fila5
        if ((fY >80 && fY <=100)){
            if(fX >0 && fX <=20){matriz[20]=1;g.fillRect(0, 80, 20, 20);}
            if(fX >20 && fX <=40){matriz[21]=1;g.fillRect(20, 80, 20, 20);}
            if(fX >40 && fX <=60){matriz[22]=1;g.fillRect(40, 80, 20, 20);}
            if(fX >60 && fX <=80){matriz[23]=1;g.fillRect(60, 80, 20, 20);}
            if(fX >80 && fX <=100){matriz[24]=1;g.fillRect(80, 80, 20, 20);}
        }
         //Fila6
        if ((fY >100 && fY <=120)){
            if(fX >0 && fX <=20){matriz[25]=1;g.fillRect(0, 100, 20, 20);}
            if(fX >20 && fX <=40){matriz[26]=1;g.fillRect(20, 100, 20, 20);}
            if(fX >40 && fX <=60){matriz[27]=1;g.fillRect(40, 100, 20, 20);}
            if(fX >60 && fX <=80){matriz[28]=1;g.fillRect(60, 100, 20, 20);}
            if(fX >80 && fX <=100){matriz[29]=1;g.fillRect(80, 100, 20, 20);}
        }
         //Fila7
        if ((fY >120 && fY <=140)){
            if(fX >0 && fX <=20){matriz[30]=1;g.fillRect(0, 120, 20, 20);}
            if(fX >20 && fX <=40){matriz[31]=1;g.fillRect(20, 120, 20, 20);}
            if(fX >40 && fX <=60){matriz[32]=1;g.fillRect(40, 120, 20, 20);}
            if(fX >60 && fX <=80){matriz[33]=1;g.fillRect(60, 120, 20, 20);}
            if(fX >80 && fX <=100){matriz[34]=1;g.fillRect(80, 120, 20, 20);}
        }


        //Código para mostrar en tiempo real el valor del vector de entrada
        StringBuffer mat= new StringBuffer();
        mat.append(matriz[0]);
        for (i=1;i<matriz.length;i++){
        mat.append(" ");
        mat.append(matriz[i]);
        }
        String matS = mat.toString();

        label2.setText("Vector de entrada:["+ matS +"]");
        g.dispose();
    }                               

    private void zonaMouseDragged(java.awt.event.MouseEvent evt) {                                
 /****************************************************************************
 * AREA DE DIBUJO: MOUSE ARRASTRADO
 *****************************************************************************/
     
        //Código para ir dibujando líneas mientras se arrastra el puntero
        int fX = evt.getX();
        int fY = evt.getY();
        Graphics g=zona.getGraphics();
      
      
        iX=fX;
        iY=fY;
        int i;

     /*Código para llenar el vector de entrada
     Según la posición del puntero se determina la zona y se pone 1 o 0 en el
     vector correspondiente*/
        //Fila1
        if ((fY >0 && fY <=20)){
            if(fX >0 && fX <=20){matriz[0]=1;g.fillRect(0, 0, 20, 20);}
            if(fX >20 && fX <=40){matriz[1]=1;g.fillRect(20, 0, 20, 20);}
            if(fX >40 && fX <=60){matriz[2]=1;g.fillRect(40, 0, 20, 20);}
            if(fX >60 && fX <=80){matriz[3]=1;g.fillRect(60, 0, 20, 20);}
            if(fX >80 && fX <=100){matriz[4]=1;g.fillRect(80, 0, 20, 20);}
        }
         //Fila2
        if ((fY >20 && fY <=40)){
            if(fX >0 && fX <=20){matriz[5]=1;g.fillRect(0, 20, 20, 20);}
            if(fX >20 && fX <=40){matriz[6]=1;g.fillRect(20, 20, 20, 20);}
            if(fX >40 && fX <=60){matriz[7]=1;g.fillRect(40, 20, 20, 20);}
            if(fX >60 && fX <=80){matriz[8]=1;g.fillRect(60, 20, 20, 20);}
            if(fX >80 && fX <=100){matriz[9]=1;g.fillRect(80, 20, 20, 20);}
        }
         //Fila3
        if ((fY >40 && fY <=60)){
            if(fX >0 && fX <=20){matriz[10]=1;g.fillRect(0, 40, 20, 20);}
            if(fX >20 && fX <=40){matriz[11]=1;g.fillRect(20, 40, 20, 20);}
            if(fX >40 && fX <=60){matriz[12]=1;g.fillRect(40, 40, 20, 20);}
            if(fX >60 && fX <=80){matriz[13]=1;g.fillRect(60, 40, 20, 20);}
            if(fX >80 && fX <=100){matriz[14]=1;g.fillRect(80,40, 20, 20);}
        }
         //Fila4
        if ((fY >60 && fY <=80)){
            if(fX >0 && fX <=20){matriz[15]=1;g.fillRect(0, 60, 20, 20);}
            if(fX >20 && fX <=40){matriz[16]=1;g.fillRect(20, 60, 20, 20);}
            if(fX >40 && fX <=60){matriz[17]=1;g.fillRect(40, 60, 20, 20);}
            if(fX >60 && fX <=80){matriz[18]=1;g.fillRect(60, 60, 20, 20);}
            if(fX >80 && fX <=100){matriz[19]=1;g.fillRect(80, 60, 20, 20);}
        }
         //Fila5
        if ((fY >80 && fY <=100)){
            if(fX >0 && fX <=20){matriz[20]=1;g.fillRect(0, 80, 20, 20);}
            if(fX >20 && fX <=40){matriz[21]=1;g.fillRect(20, 80, 20, 20);}
            if(fX >40 && fX <=60){matriz[22]=1;g.fillRect(40, 80, 20, 20);}
            if(fX >60 && fX <=80){matriz[23]=1;g.fillRect(60, 80, 20, 20);}
            if(fX >80 && fX <=100){matriz[24]=1;g.fillRect(80, 80, 20, 20);}
        }
         //Fila6
        if ((fY >100 && fY <=120)){
            if(fX >0 && fX <=20){matriz[25]=1;g.fillRect(0, 100, 20, 20);}
            if(fX >20 && fX <=40){matriz[26]=1;g.fillRect(20, 100, 20, 20);}
            if(fX >40 && fX <=60){matriz[27]=1;g.fillRect(40, 100, 20, 20);}
            if(fX >60 && fX <=80){matriz[28]=1;g.fillRect(60, 100, 20, 20);}
            if(fX >80 && fX <=100){matriz[29]=1;g.fillRect(80, 100, 20, 20);}
        }
         //Fila7
        if ((fY >120 && fY <=140)){
            if(fX >0 && fX <=20){matriz[30]=1;g.fillRect(0, 120, 20, 20);}
            if(fX >20 && fX <=40){matriz[31]=1;g.fillRect(20, 120, 20, 20);}
            if(fX >40 && fX <=60){matriz[32]=1;g.fillRect(40, 120, 20, 20);}
            if(fX >60 && fX <=80){matriz[33]=1;g.fillRect(60, 120, 20, 20);}
            if(fX >80 && fX <=100){matriz[34]=1;g.fillRect(80, 120, 20, 20);}
        }


        //Código para mostrar en tiempo real el valor del vector de entrada
        StringBuffer mat= new StringBuffer();
        mat.append(matriz[0]);
        for (i=1;i<matriz.length;i++){
        mat.append(" ");
        mat.append(matriz[i]);
        }
        String matS = mat.toString();
    
        label2.setText("Vector de entrada:["+ matS +"]");
        g.dispose();

    }                               

    private void zonaMouseMoved(java.awt.event.MouseEvent evt) {                              
         this.dibujarGuias();
    }                             

    private void zonaComponentShown(java.awt.event.ComponentEvent evt) {                                  
        // TODO add your handling code here:
       this.dibujarGuias();
    }                                 

    private void zonaPropertyChange(java.beans.PropertyChangeEvent evt) {                                  
        // TODO add your handling code here:
 
    
    }                                 

    private void zonaFocusGained(java.awt.event.FocusEvent evt) {                               
        // TODO add your handling code here:
      
    }                              

    private void mainPanelMouseEntered(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:
        //this.dibujarGuias();
    }                                    

    private void mainPanelMouseMoved(java.awt.event.MouseEvent evt) {                                   
 
    }                                  

    private void zonaFocusLost(java.awt.event.FocusEvent evt) {                             
        // TODO add your handling code here:
 
    }                            

    private void button1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
        /****************************************************************************
 * BOTÓN: AGREGAR PATRÓN
 *****************************************************************************/

  zona.repaint();
        dibujarGuias();
      
    /*se captura el array de patrones temporal(1x35) y se guarda en el array
     * final de patrones en la fila=contPatrones*/
    for (int j=0;j<35;j++)matPatrones[contPatrones][j]=matriz[j];
    nomPatrones[contPatrones]=textField1.getText();//Se guarda el nombre del patrón

    //Se pasa el valor del patrón capturado a String para visualizarlo en debug
        StringBuffer mat= new StringBuffer();
        mat.append(matriz[0]);
        for (int i=1;i<35;i++){
        mat.append(" ");
        mat.append(matriz[i]);
        }
        String matS = mat.toString();

        debug.append("¡Capturado patrón "+String.valueOf(contPatrones+1)+" con éxito!\n");
        debug.append("Nombre: \""+nomPatrones[contPatrones]+"\" valor:\n");
        debug.append("["+ matS +"]\n");

        //se incremente al contador de patrones y se actualizan las etiquetas
        contPatrones++;
        label7.setText(String.valueOf(contPatrones+1));
        textField1.setText("");


        //SI SE HA ALCANZADO EL NÚMERO MÁXIMO DE PATRONES:

        if (contPatrones==10){
                //Deshabilito elementos gráficos y cambio el estado
                label7.setVisible(false);
                button1.setEnabled(false);
                label6.setEnabled(false);
                textField1.setEnabled(false);
             


                label5.setText("EJECUCIÓN");
                label5.setForeground(Color.GREEN);

                patronesM = new Matriz(matPatrones);//Se inicializa la matriz de patrones
                patronesM = Matriz.transponer(patronesM);//Se transpone => 35x10
                objetivosM= new Matriz(matObjetivos);//Se inicializa la matriz objetivos
                objetivosM= Matriz.transponer(objetivosM);//Se transpone => 10x10

                miRedJA = new Red(patronesM,objetivosM);
              

                debug.append("\nMatriz de objetivos ["+objetivosM.getFilString()+"x"+objetivosM.getColString()+"]:\n");
                debug.append(objetivosM.toStringM());


                debug.append("\nMatriz de patrones ["+patronesM.getFilString()+"x"+patronesM.getColString()+"]:\n");
                debug.append(patronesM.toStringM());

                //guardar las matrices para matlab
           
                debug.append("\nMODO DE EJECUCIÓN\n");
                debug.append("Para comenzar a utilizar la red neuronal calculada en JAVA presione primero \"Entrenar\" y luego\n ");
                debug.append("\"CalcularJ\" bajo el título Java de ésta interfaz \n");
                //nuevos elementos gráficos
                entrenar.setEnabled(true);
              
         

        }



       //Reiniciar vector de entrada
      for(int j=0;j<=34;j++){
      matriz[j]=0;

      }

          zona.repaint();
        dibujarGuias();
        StringBuffer mat1= new StringBuffer();
        mat1.append(matriz[0]);
        for (int i=1;i<matriz.length;i++){
        mat1.append(" ");
        mat1.append(matriz[i]);
        }

          zona.repaint();
        dibujarGuias();
        String matS1 = mat1.toString();
        label2.setText("Vector de entrada:["+ matS1 +"]");
      
    
     
    }                                     

    private void entrenarActionPerformed(java.awt.event.ActionEvent evt) {                                       
     
        // TODO add your handling code here:
       calcularJ.setEnabled(false);
      
     
       String alfaS = JOptionPane.showInputDialog(null, "Por favor digite el factor de aprendizaje (alfa)");
       double alfa= Double.valueOf(alfaS);
     
       String errorS = JOptionPane.showInputDialog(null, "Por favor digite el valor de error mínimo por patrón (ep)");
       double error= Double.valueOf(errorS);
     
       String itS = JOptionPane.showInputDialog(null, "Por favor digite el número máximo de iteraciones (épocas)");
       int it= Integer.valueOf(itS);
       debug.append("\nEntrenando la red por favor espere...");
          
          String res=Red.trainNetLog(miRedJA, alfa,error, it);

          debug.append(res);
          calcularJ.setEnabled(true);
          zona.repaint();
        dibujarGuias();
    
    }                                      

    private void calcularJActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:

        Matriz tmp = new Matriz(matriz);
        tmp=Matriz.transponer(tmp);

        Matriz resp= Red.simNet(miRedJA, tmp);
        DecimalFormat df = new DecimalFormat("0.00");

        debug.append("\n\nRESULTADOS SEGÚN LA RED NEURONAL DE JAVA:\n");
        for (int i=0;i<10;i++){
        debug.append(nomPatrones[i]+": "+String.valueOf(df.format(Matriz.transponer(resp).toArray()[0][i]))+"  ");
        }
        debug.append("\n");

        //Inicializo de nuevo la matriz de captura y redibujo el lienzo
        for(int j=0;j<=34;j++){
              matriz[j]=0;
              }
    
        tmp=new Matriz(Matriz.transponer(resp).toArray()[0]);
        respuesta.setText(Matriz.masProbable(tmp, nomPatrones));

       zona.repaint();
        dibujarGuias();
     
    }                                       

    private void fileMenuActionPerformed(java.awt.event.ActionEvent evt) {                                       


    }                                      


    // Variables declaration - do not modify                   
    private javax.swing.JButton button1;
    private javax.swing.JButton calcularJ;
    private java.awt.TextArea debug;
    private javax.swing.JButton entrenar;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenuItem jMenuItem1;
    private java.awt.Label label1;
    private java.awt.Label label11;
    private java.awt.Label label2;
    private java.awt.Label label3;
    private java.awt.Label label4;
    private java.awt.Label label5;
    private java.awt.Label label6;
    private java.awt.Label label7;
    private java.awt.Label label8;
    private java.awt.Label label9;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private java.awt.Label respuesta;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private java.awt.TextField textField1;
    private java.awt.Canvas zona;
    // End of variables declaration                 

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;

private void dibujarGuias(){
 Graphics g=zona.getGraphics();
        g.setColor(Color.blue);
        g.drawLine(0, 0, 0, 140);
        g.drawLine(20, 0, 20, 140);
        g.drawLine(40, 0, 40, 140);
        g.drawLine(60, 0, 60, 140);
        g.drawLine(80, 0, 80, 140);
        g.drawLine(99, 0, 99, 140);

        g.drawLine(0, 0, 100, 0);
        g.drawLine(0, 20, 100, 20);
        g.drawLine(0, 40, 100, 40);
        g.drawLine(0, 60, 100, 60);
        g.drawLine(0, 80, 100, 80);
        g.drawLine(0, 100, 100, 100);
        g.drawLine(0, 120, 100, 120);
        g.drawLine(0, 139, 100, 139);
        g.dispose();
}

/**
 * Reiniciar aplicación
 * Reinicia los vectores y en general todos los datos de la aplicación
 */
@Action
    public void reinciar() {
             // TODO add your handling code here:
         contPatrones=0;
                label7.setVisible(true);
                button1.setEnabled(true);
                label6.setEnabled(true);
                textField1.setEnabled(true);
                label5.setForeground(Color.red);
        label5.setText("APRENDIZAJE");
        label2.setText("Vector de entrada:[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]");
        label7.setText("1");
        debug.setText("Iniciando la aplicación...\nEn ésta ventana apareceran los mensajes del sistema\n");
        debug.append("\nMODO DE APRENDIZAJE\n");
        debug.append("La red neuronal requiere 10 patrones de dibujo a mano alzada con sus respectivos nombres para configurarse.\n");
        debug.append("Por favor, dibuje la forma del patrón en el recuadro de dibujo.\n");
        debug.append("Luego introduzca un nombre para el patrón y de clic al botón \"Agregar patrón\"\n\n");
        entrenar.setEnabled(false);
        calcularJ.setEnabled(false);
        zona.repaint();
        dibujarGuias();
      
    }



}

[/code] 
RedesNeuronalesApp
[code]
 package redesneuronales;

import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;

/**
 * La clase principal de la aplicación. Se encarga de "lanzar" la ventana principal
 */
public class RedesNeuronalesApp extends SingleFrameApplication {

    /**
     * At startup create and show the main frame of the application.
     */
    @Override protected void startup() {
        show(new RedesNeuronalesView(this));
    }

    /**
     * This method is to initialize the specified window by injecting resources.
     * Windows shown in our application come fully initialized from the GUI
     * builder, so this additional configuration is not needed.
     * @param root
     */
    @Override protected void configureWindow(java.awt.Window root) {
    }

    /**
     * A convenient static getter for the application instance.
     * @return the instance of RedesNeuronalesApp
     */
    public static RedesNeuronalesApp getApplication() {
        return Application.getInstance(RedesNeuronalesApp.class);
    }

    /**
     * Main method launching the application.
     * @param args
     */
    public static void main(String[] args) {
        launch(RedesNeuronalesApp.class, args);
    }
}

[/code]