Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication1; import java.awt.BorderLayout; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; /** * * @author Sammy Guergachi <sguergachi at gmail.com> */ public class AlgoritmoGenetico extends javax.swing.JFrame { /** * Creates new form AlgoritmoGenetico */ public AlgoritmoGenetico() { initComponents(); } /** * 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">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); numeroDeIndividuostext = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); errorDeConvergencia = new javax.swing.JTextField(); btnIniciar = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); numeroDeIteraciontxt = new javax.swing.JTextField(); panel1 = new javax.swing.JPanel(); panel2 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Numero de Individuos"); jLabel2.setText("Error De Convergencia"); btnIniciar.setText("INICIAR"); btnIniciar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnIniciarActionPerformed(evt); } }); jLabel3.setText("Numero de Iteraciones "); panel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Error por patron")); panel1.setLayout(new java.awt.BorderLayout()); panel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Error por Iteracion")); panel2.setLayout(new java.awt.BorderLayout()); jButton1.setText("ir a la Simulacion"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(24, 24, 24).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup().addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(numeroDeIteraciontxt)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup().addComponent(jLabel2) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(errorDeConvergencia, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup().addComponent(jLabel1) .addGap(18, 18, 18).addComponent(numeroDeIndividuostext, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(layout.createSequentialGroup().addGap(100, 100, 100).addComponent(btnIniciar))) .addGap(38, 38, 38) .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(panel2, javax.swing.GroupLayout.PREFERRED_SIZE, 560, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(37, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE).addComponent(jButton1).addGap(542, 542, 542))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(47, 47, 47).addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jLabel1) .addComponent(numeroDeIndividuostext, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2).addComponent(errorDeConvergencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3).addComponent(numeroDeIteraciontxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(59, 59, 59).addComponent(btnIniciar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(34, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(panel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panel1, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)) .addGap(35, 35, 35).addComponent(jButton1).addGap(55, 55, 55))); pack(); }// </editor-fold>//GEN-END:initComponents private void btnIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIniciarActionPerformed ArrayList<Individuo> mustra = new ArrayList<>(); int numeroDeIndividios = Integer.parseInt(numeroDeIndividuostext.getText()); for (int i = 0; i < numeroDeIndividios; i++) { Individuo ind = new Individuo(); ind.generarMatrizAleatoria(); ind.generarMatrizBinaria(); ind.generarVectorBinario(); mustra.add(ind); //mostrarEnConsola(ind.getMatriz()); //mostrarMatrizBinaria(ind.getMatrizBinaria()); // JOptionPane.showMessageDialog(null," individuo "+i); } //System.out.println(mustra.get(0).getMatriz()[0][0]); Sintoma sintoma = new Sintoma(); Enfermedad enfermedad = new Enfermedad(); Sigmoide sigmoide = new Sigmoide(); Cruce cruce; double yc[] = new double[4]; double error[] = new double[4]; double errorPatron[] = new double[10]; double errorIteracion[] = new double[Integer.parseInt(numeroDeIteraciontxt.getText())]; boolean bandera = true; int it = 0; do { for (int p = 0; p < 10; p++) { //estos son los patrones int x[] = sintoma.getFila(p); int y[] = enfermedad.getFila(p); for (Individuo indi : mustra) { double R[][] = indi.getMatriz(); double suma = 0; double sumaError = 0; if (indi.getErrorPatron() == 0) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 7; j++) { double aux = x[j] * R[j][i]; suma += aux; } yc[i] = sigmoide.function(suma); suma = 0; error[i] = y[i] - yc[i]; } for (int i = 0; i < error.length; i++) { sumaError += Math.abs(error[i]); } indi.setErrorPatron(sumaError / 4); } } //Ordenar de menor a mayor para obtener los mejores individuos para la reproduccion Collections.sort(mustra, new Comparator<Individuo>() { @Override public int compare(Individuo p1, Individuo p2) { // Aqui esta el truco, ahora comparamos p2 con p1 y no al reves como antes return new Double(p1.getErrorPatron()).compareTo(new Double(p2.getErrorPatron())); } }); System.out.println("//////////////Cargando////////////////////////////"); errorPatron[p] = mustra.get(0).getErrorPatron(); cruce = new Cruce(numeroDeIndividios, mustra); mustra = cruce.nuevaGenaracion(); graficarErrorPatron(errorPatron); } errorIteracion[it] = errorIteracion(errorPatron); graficarErrorIteracion(errorIteracion); it++; if (it >= Integer.parseInt(numeroDeIteraciontxt.getText())) { bandera = false; } else { if (errorIteracion[it - 1] <= Double.parseDouble(errorDeConvergencia.getText())) { bandera = false; } } } while (bandera); if (errorIteracion[it - 1] <= Double.parseDouble(errorDeConvergencia.getText())) { int s = JOptionPane.showConfirmDialog(null, "Encontro Individuo mas apto con un error de: " + mustra.get(0).getErrorPatron()); if (s == 0) { db conexion; try { conexion = new db(); individuoDAO indDao = new individuoDAO(conexion); indDao.insert(mustra.get(0)); } catch (SQLException ex) { Logger.getLogger(AlgoritmoGenetico.class.getName()).log(Level.SEVERE, null, ex); } } } else { JOptionPane.showMessageDialog(null, "convergio..."); } }//GEN-LAST:event_btnIniciarActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed try { new FormularioDiagnostico().setVisible(true); this.setVisible(false); } catch (SQLException ex) { Logger.getLogger(AlgoritmoGenetico.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton1ActionPerformed public double errorIteracion(double[] errorPatron) { double suma = 0; for (int i = 0; i < errorPatron.length; i++) { suma += errorPatron[i]; } return suma / 10; } public void graficarErrorPatron(double[] errorPatron) { //Fuentes de datos DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset(); for (int i = 0; i < errorPatron.length; i++) { line_chart_dataset.setValue(errorPatron[i], "Error", String.valueOf(i + 1)); } // Creando el Grafico JFreeChart chart = ChartFactory.createLineChart("Errores por patron", "patrones", "Errores", line_chart_dataset, PlotOrientation.VERTICAL, true, true, false); // Mostrar Grafico ChartPanel chartPanel = new ChartPanel(chart); panel1.removeAll(); panel1.add(chartPanel, BorderLayout.CENTER); panel1.validate(); } public void graficarErrorIteracion(double[] errorPatron) { //Fuentes de datos DefaultCategoryDataset line_chart_dataset = new DefaultCategoryDataset(); for (int i = 0; i < errorPatron.length; i++) { if (errorPatron[i] != 0) { line_chart_dataset.setValue(errorPatron[i], "Error", String.valueOf(i + 1)); line_chart_dataset.setValue(Double.valueOf(errorDeConvergencia.getText()), "Error de convergencia", String.valueOf(i + 1)); } } // Creando el Grafico JFreeChart chart = ChartFactory.createLineChart("Errores por Iteracion", "Iteracion", "Error Iteracion", line_chart_dataset, PlotOrientation.VERTICAL, true, true, false); // Mostrar Grafico ChartPanel chartPanel = new ChartPanel(chart); panel2.removeAll(); panel2.add(chartPanel, BorderLayout.CENTER); panel2.validate(); } private void mostrarEnConsola(double numeros[][]) { for (int i = 0; i < numeros.length; i++) { for (int j = 0; j < numeros[i].length; j++) { System.out.println(numeros[i][j] + " "); } System.out.println(""); } } private void mostrarMatrizBinaria(String numeros[][]) { for (int i = 0; i < numeros.length; i++) { for (int j = 0; j < numeros[i].length; j++) { System.out.println(numeros[i][j] + " "); } System.out.println(""); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AlgoritmoGenetico.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AlgoritmoGenetico.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AlgoritmoGenetico.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AlgoritmoGenetico.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AlgoritmoGenetico().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnIniciar; private javax.swing.JTextField errorDeConvergencia; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JTextField numeroDeIndividuostext; private javax.swing.JTextField numeroDeIteraciontxt; private javax.swing.JPanel panel1; private javax.swing.JPanel panel2; // End of variables declaration//GEN-END:variables }